javascript - 如何使用 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 中的文档。
一个拥抱
解决方案
首先非常重要的是创建一个nonce woocommerce
这是创建 woocommerce 随机数的信息
通过 woocommerce 中的 api rest 对购物车的各种请求非常重要。
// wp_create_nonce( 'wc_store_api' )
$woononce = wp_create_nonce( 'wc_store_api' ),
return $woononce
在确保您拥有 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');
});
推荐阅读
- c# - 我怎样才能使这个装饰标签控件工作?
- javascript - 如何嵌套多个 Promise.all
- python - 使用 Python 监控 Postgres 数据库
- android-studio - Android Studio-Designer 不显示颜色作为模拟器/手机
- python - 如何安排数据集进行多变量分类?
- python - 直接打开/加载图像为 numpy ndarray
- c# - 将二进制文件添加到存档
- regex - 正则表达式 vb.net ismatch 总是返回 true
- spring - Spring 2.0.0-RELEASE ConfigurationProperties 绑定不起作用
- docker - docker无法访问主机可以访问的内网