5

I am aware of the fact that Woocommerce provides APIs for most of its functionalities. I have gone through the below documentation

Woocommerce REST API

Now cart is one of the most important features of any e-commerce application. I did some research and found that the cart works with sessions on the web. Now I am not understanding how to create API for cart in Woocommerce. I have done a lot of research but in vain. Nothing seems to work. There must be a way to do this. Any help is appreciated.

Nmk
  • 1,281
  • 2
  • 14
  • 25
  • **You can't** as Rest API don't handle Live Objects Like Cart and Sessions and that is normal… – LoicTheAztec Jan 12 '18 at 10:47
  • Is there any alternative way to achieve it? – Sayantan Mitra Jan 12 '18 at 11:59
  • You should try web hooks may be, but live/session objects are maid to be live on the "mother" software, so here WooCommerce only. – LoicTheAztec Jan 12 '18 at 12:04
  • You should try this [create order](http://woocommerce.github.io/woocommerce-rest-api-docs/#create-an-order) api enpoint, i did not test that yet, but there should be some workflow, after all a cart becomes an order after checkout :-) – JBoulhous Jan 16 '18 at 22:16
  • @JBoulhous I know. That is what happens after checkout. A new order is created. The API for creating new order is available in the documentation I shared above. My question was how to access the cart data of my woocommerce web from my android application. I am unable to figure out any API for that. – Sayantan Mitra Jan 17 '18 at 12:21
  • You should handle your cart data logic in your android app, then create the order, and i think there's a mail you could trigger that will send to the order customer email details of the order with a payment link if not paid yet. – JBoulhous Jan 17 '18 at 12:25
  • 2
    Okay let me explain you more specifically. Say I have added two items in my cart from the web but didn't complete the checkout. When the same user logs in from the android application, he should see two items in the cart. My question is how to achieve that. – Sayantan Mitra Jan 17 '18 at 12:35
  • 1
    @SayantanMitraI am facing the same problem. Did you get the solution? – Mukul Sharma Aug 20 '18 at 10:51

1 Answers1

0

To synchronize the cart with your backend, you would need to listen for the woocommerce_add_to_cart and send information about the cart to your backend whenever an item gets added to the cart.

Within your functions.php add the code below to add a hook to listen for the woocommerce_add_to_cart function and run the track_add_to_cart method.

add_action('woocommerce_add_to_cart', 'track_add_to_cart');
function track_add_to_cart() {
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

    foreach($items as $item => $values) { 
        $_product =  wc_get_product( $values['data']->get_id()); 
        // build a POST request and send product info to your server
    } 
}
Hermes
  • 2,828
  • 2
  • 14
  • 34