在 WooCommerce 商店运营中,库存管理非常重要。通过 WooCommerce REST API,开发者可以实现自动化库存更新,减少人工操作,提高数据同步效率。本文会详细介绍使用 WooCommerce API 更新产品库存的方法,帮助你快速上手。
1. 为什么使用 API 更新库存
对于拥有 ERP、POS、WMS 系统或多渠道销售平台的商家,API 更新库存有以下优势:
实时同步:避免超卖或库存信息滞后。
自动化流程:减少手动更新工作量。
对接第三方系统:无缝连接库存管理系统和 WooCommerce。
2. 准备工作
在调用 WooCommerce API 前,需要完成以下配置:
生成 API Key
登录 WordPress 后台
前往 WooCommerce > 设置 > 高级 > REST API
点击 添加密钥
选择用户,设置权限为 Read/Write
生成后保存 Consumer Key 和 Consumer Secret
确认 API 访问权限
确保目标用户拥有更新产品的权限(通常为管理员)。
获取产品 ID
库存更新需要对应产品或变体的 ID,可通过 API 查询或在后台查看。
3. 使用 WooCommerce REST API 更新库存
3.1 API Endpoint
更新产品库存使用的 Endpoint 格式为:
PUT /wp-json/wc/v3/products/{product_id}
对于变体库存:
PUT /wp-json/wc/v3/products/{product_id}/variations/{variation_id}
3.2 请求示例
以下以 PHP + cURL 为例,演示如何更新单个产品的库存数量:
<?php
$ck = ‘ck_xxxxxxxxxxxxxxxxxxxxxxx’; // Consumer Key
$cs = ‘cs_xxxxxxxxxxxxxxxxxxxxxxx’; // Consumer Secret
$site = ‘https://yourstore.com’;
$product_id = 123; // 替换为实际产品 ID
$data = [
‘stock_quantity’ => 50, // 更新为库存数量
‘manage_stock’ => true, // 启用库存管理
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $site . ‘/wp-json/wc/v3/products/’ . $product_id);
curl_setopt($ch, CURLOPT_USERPWD, $ck . ‘:’ . $cs);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, ‘PUT’);
curl_setopt($ch, CURLOPT_HTTPHEADER, [‘Content-Type: application/json’]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
if(curl_errno($ch)){
echo ‘Error:’ . curl_error($ch);
}
curl_close($ch);
echo $response;
?>
3.3 请求参数说明
stock_quantity:库存数量
manage_stock:是否启用库存管理(true/false)
in_stock:是否有库存(true/false)
如果使用 Postman 或其他语言(如 Python requests、Node.js axios),请求结构与上述一致。
4. 批量更新库存
WooCommerce REST API 也支持 Batch 更新,通过 products/batch Endpoint,可一次更新多个产品,减少 API 调用次数。
使用 Postman 测试
打开 Postman
创建一个 PUT 请求URL 输入:https://yourstore.com/wp-json/wc/v3/products/batch
认证使用 Basic Auth,填写 Username 填写 Consumer Key, Password 填写 Consumer Secret
Body 选择 raw -> JSON,粘贴这段 JSON 数据
发送测试,检查返回结果
示例 JSON 结构
{
“update”: [
{
“id”: 123,
“stock_quantity”: 50,
“manage_stock”: true
},
{
“id”: 124,
“stock_quantity”: 30,
“manage_stock”: true
}
]
}
请求方式同样为 PUT,Endpoint 为:
/wp-json/wc/v3/products/batch
5. 注意事项
API 权限:确认密钥拥有 write 权限。
库存同步频率:如果第三方系统库存变动频繁,建议设置合适的更新间隔,避免 API 调用过多。
限流和性能:WooCommerce REST API 有服务器并发限制,批量接口可以减少请求次数。
多变体产品:变体库存更新需要调用变体专用 Endpoint。
6. 总结
使用 WooCommerce API 更新库存,是自动化电商运营的核心环节。无论是对接 ERP、WMS,还是自建库存管理系统,掌握 REST API 的调用方法,都能帮助你构建稳定高效的库存更新流程,避免超卖风险,提升用户体验。