使用PHP CURL通过REST API更新WooCommerce产品价格失败咨询
问题根因
你在请求头中指定了Content-Type: application/json,但传入CURLOPT_POSTFIELDS的是未序列化的PHP数组,cURL会自动将数组格式转为application/x-www-form-urlencoded格式提交,和请求头声明的格式不匹配,WooCommerce API无法正确解析传入的价格参数,因此不会执行更新操作。命令行调用时你是直接传了JSON字符串,所以可以正常执行。
修复方案
只需要将提交的$data数组做JSON序列化后再传入即可,修正后的代码如下:
<?php $url = "https://wooexample.com/wp-json/wc/v3/products/455"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_PUT, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $headers = array( "Content-Type: application/json", "Authorization: Basic " . base64_encode ( 'ck_33fbff7b90dcddba9bd4cbedaeda6b2fa3:cs_4156da18fc357b288e42a7e7b75fa6682b' ), ); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); $data = [ 'regular_price' => '24', 'price' => '24' ]; // 新增:将数组序列化为JSON字符串 curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); //for debug only! curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $resp = curl_exec($curl); curl_close($curl); print_r(json_decode($resp));
额外验证点
- 检查返回的响应数据中
regular_price字段是否已经更新为你提交的值,如果返回值已经更新但后台仍显示旧价格,可清空WooCommerce缓存后再查看。 - 确认你使用的API密钥具备产品读写权限,只读权限会导致接口正常返回产品数据但不会执行更新操作。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

