实时掌握店铺数据(订单、销量、客户数、库存等)可以帮你快速决策。用 WooCommerce API 自动获取这些关键数据,还能生成报表、监控业务。本文会介绍具体怎么做。
一、为什么使用 WooCommerce API 获取统计数据
WooCommerce 后台提供可视化的统计面板,但使用 API 获取数据有以下优势:
自动化:可集成到 ERP、BI、CRM 等系统,实时拉取数据更新。
多维度分析:结合外部数据库和工具,生成自定义报表。
跨平台管理:多店铺管理时,通过 API 集中汇总不同站点数据。
二、API 准备工作
2.1 生成 API Key
登录 WordPress 后台 → WooCommerce → 设置 → 高级 → REST API。
点击【添加密钥】,填写描述,选择用户(建议使用管理员账户),权限选择【读取/写入】(如果需要修改数据)。
生成后,复制 Consumer Key 与 Consumer Secret,用于 API 鉴权。
2.2 确认 API URL 结构
API 端点一般为:
https://你的域名/wp-json/wc/v3/
例如获取统计数据:
https://你的域名/wp-json/wc-analytics/{endpoint}
鉴权方式同 WooCommerce REST API,使用 Consumer Key 与 Consumer Secret 进行 Basic Auth 认证。
三、常用统计 API 端点与示例
2.1 获取销售概览
接口 URL:
GET /wp-json/wc-analytics/reports/revenue/stats
示例请求(使用 curl):
curl -X GET https://你的域名/wp-json/wc-analytics/reports/revenue/stats
-u ck_xxxxxxxxxxxxxxxxx:cs_xxxxxxxxxxxxxxxxx
常用查询参数:
参数说明示例值before结束日期(ISO8601)2025-07-07after开始日期(ISO8601)2025-07-01interval时间粒度day, week, month, year
返回示例:
{
“totals”: {
“total_sales”: 25000,
“net_revenue”: 23000,
“orders_count”: 45,
“avg_order_value”: 511.11
},
“intervals”: [
{
“date_start”: “2025-07-01”,
“date_end”: “2025-07-01”,
“subtotals”: {
“total_sales”: 5000,
“net_revenue”: 4500,
“orders_count”: 10,
“avg_order_value”: 500
}
},
…
]
}
2.2 获取订单统计
接口 URL:
GET /wp-json/wc-analytics/orders
示例请求(Python requests):
import requests
from requests.auth import HTTPBasicAuth
url = “https://你的域名/wp-json/wc-analytics/orders”
consumer_key = “ck_xxxxxxxxxxxxxxxxx”
consumer_secret = “cs_xxxxxxxxxxxxxxxxx”
response = requests.get(url, auth=HTTPBasicAuth(consumer_key, consumer_secret))
if response.status_code == 200:
data = response.json()
for order in data[‘orders’]:
print(“订单ID:”, order[‘id’], “金额:”, order[‘total’])
else:
print(“请求失败,状态码:”, response.status_code)
2.3 获取顾客统计
新版 Analytics API 提供顾客统计端点:
GET /wp-json/wc-analytics/customers/stats
示例返回:
{
“totals”: {
“customers_count”: 120,
“new_customers”: 15,
“returning_customers”: 105
}
}
可以结合 after 和 before 参数获取指定日期范围的新增用户数据。
四、分页与速率限制
默认每页返回 10 条,可通过 per_page 参数设置(最大 100)。
使用 page 参数遍历所有数据。
WooCommerce API 没有严格速率限制,但建议合理调用频率,避免影响服务器性能。
五、最佳实践与安全建议
开启 HTTPS:避免 API Key 在传输过程中被截获。
限制 API 权限:如果只查询数据,生成读取权限的 key,避免误操作导致数据变更。
分页处理:WooCommerce API 默认每页最多返回 100 条,如果数据量大需要遍历分页获取。
与 BI 工具结合:可以使用 Power BI、Tableau、Looker Studio 连接 WooCommerce API,制作可视化仪表盘。
六、总结
用 WooCommerce API 轻松获取店铺数据:销售额、订单、客户、库存等,还能对接企业系统,让管理更高效。想实现自动同步订单、实时更新库存?查看官方 API 文档就可以开发。