首页 > 解决方案 > 如何使用 javascript 在 woocommerce 中通过 Api Rest 添加到购物车?

问题描述

如何使用 javascript 在 woocommerce 中通过 Api Rest 添加到购物车?

我添加这个问题是为了能够帮助任何正在寻找新版本的 Woocommerce Api Rest 答案的人,在 7 小时后我已经实现了它,如果我可以帮助某人节省这个时间。

重要的

我建议使用 woocommerce rest api 文档中的 postman 或 insomnia 等工具,它们完全帮助我生成正确的代码并进行测试。

很好,我可以通过 api rest 添加一个简单产品的代码就是这个。

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);
});

要查看您可以使用购物车执行的所有操作,请执行https://yourdomain.com/wp-json/wc/store/,您将看到所有可能的路线,最复杂的事情可能是正确组装所谓的 post使用正确的 nonce 和其他请求文档的标头。

对于添加到购物车,rest api ajala 的文档很少,这可以帮助某人并且可以增加 woocommerce 中的文档。

一个拥抱

标签: javascriptwordpresswoocommercefetch-apiwoocommerce-rest-api

解决方案


首先非常重要的是创建一个nonce woocommerce

这是创建 woocommerce 随机数的信息

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

通过 woocommerce 中的 api rest 对购物车的各种请求非常重要。

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

创建nonce woocommerce api rest

在确保您拥有 woocommerce 随机数之后,要定位的下一个数据是您要添加的产品的 ID,并在您感觉更舒服时执行传统或异步等待的 fecth。

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');
        }); 

推荐阅读