-4

How to add to cart via Api Rest in woocommerce with javascript?

I'm adding this question to be able to help anyone who is looking for the answer with the new versions of Woocommerce Api Rest, after 7 hours I have achieved it and if I can help someone save this time a pleasure.

IMPORTANT

I suggest using tools such as postman or insomnia that are in the documentation of the woocommerce rest api that fully helped me to generate the correct code and do the tests.

Very good here the code with which I can add a simple product via api rest is this.

fetch("https://yourdomain.com/wp-json/wc/store/cart/add-item", {
  "method": "POST",
  "headers": {
    "X-WC-Store-API-Nonce": "here-your-nonce-woo-not-wp-nonce", // see how to create the nonce for woo that is not the same as wordpress, it is another
    "Content-Type": "application/json"
  },
  "body": "{\"id\":\"3665\",\"quantity\":\"1\"}"
})
.then(response => {
  console.log(response);
})
.catch(err => {
  console.error(err);
});

To see everything you can do with the cart, execute https://yourdomain.com/wp-json/wc/store/ and you will see all the possible routes, the most complex thing is perhaps to correctly assemble the so-called post with the correct nonce and others header that requests the documentation.

For the Add to cart there is little documentation with rest api ajala this help someone and can increase the doc in woocommerce.

A hug

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 20 '21 at 02:44

1 Answers1

-2

First very important create a nonce woocommerce

This the info to create a woocommerce nonce

https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/trunk/src/StoreApi/docs/nonce-tokens.md#generating-security-nonces-from-wordpress

It is very important for various requests with the cart via api rest in woocommerce.

// wp_create_nonce( 'wc_store_api' ) 
$woononce = wp_create_nonce( 'wc_store_api' ), 
return $woononce

create nonce woocommerce api rest

After making sure you have the woocommerce nonce, the next data to locate is the id of the product you want to add and do the fecth either traditional or with async await as you feel more comfortable.

fetch("https://yourxdomainx.com/wp-json/wc/store/cart/add-item", {
          "method": "POST",
          "headers": {
            "X-WC-Store-API-Nonce": 'NONCEHERE'// woononce,
            "Content-Type": "application/json"
          },
          "body": `{\"id\":\"${id_item}\",\"quantity\":\"-${negativenumber}\"}`  
        })
        .then(response => {
          console.log(response);
        })
        .catch(err => {
          console.error(err);
          console.log('err');
        });