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