簡體   English   中英

通過api調用將產品添加到購物車

[英]Add a product to cart through api call

我已經設置了wordpress REST api來創建一個端點,以偵聽特定第三方服務的呼叫。 此第三方服務將發送包含產品數據的POST請求。 此數據需要woocommerce可用,以便可以將產品添加到購物車。 問題是我無法訪問WC()函數,該函數將返回woocommerce實例。 第三個pary服務期望json響應,只要是json,就可以是任何東西。 收到響應后,它將把用戶重定向到購物車。

我嘗試為端點添加一個內部回調函數,這將依次運行一個將產品添加到購物車的函數。 嘗試將此函數掛接到幾個不同的點,例如:init,wp,woocommerce_loaded,rest_api_init和wp_footer。

我還嘗試發送帶有諸如?add-to-cart =“。$ request-> get_param('productId')之類的參數的cURL get請求。

我無法發布第三方服務,但是wp rest api端點只是偵聽POST請求的普通端點。

我通過使用以下代碼解決了這個問題:

add_filter( 'woocommerce_is_rest_api_request', [ $this, 'simulate_as_not_rest' ] );
/**
* We have to tell WC that this should not be handled as a REST request.
* Otherwise we can't use the product loop template contents properly.
* Since WooCommerce 3.6
*
* @param bool $is_rest_api_request
* @return bool
*/
public function simulate_as_not_rest( $is_rest_api_request ) {
if ( empty( $_SERVER['REQUEST_URI'] ) ) {
        return $is_rest_api_request;
}

// Bail early if this is not our request.
if ( false === strpos( $_SERVER['REQUEST_URI'], $this->namespace ) ) {
    return $is_rest_api_request;
}

return false;

}

我將名稱空間設置為等於API路由的名稱空間。

我希望這可以幫助別人

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM