简体   繁体   中英

Add a product to cart through api call

I have set up the wordpress REST api to create an endpoint listening to calls by a specific third party service. This third party service will send a POST request containing the product data. This data needs to be available to woocommerce so it can add the product to the cart. Problem is i cannot access the WC() function which will return the woocommerce instance. The third pary service expects a json response, which can just be about anything as long as it's json. After it receives the response it will redirect the user to the cart.

I have tried adding an inside the callback function for the endpoint, which will in turn run a function that adds the product to cart. Tried hooking this function to a couple of different points like: init, wp, woocommerce_loaded, rest_api_init and wp_footer.

I also tried sending a cURL get request with a parameter like ?add-to-cart=".$request->get_param('productId') This was also not working.

I cannot publish the third party service, but the wp rest api endpoint is just a plain endpoint listening for POST requests.

I fixed the problem by using this code:

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;

}

I set the namespace equal to the namespace of the API route.

I hope this helps someone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM