WooCommerce REST API 文档

title: "简介 #" post_status: publish comment_status: open taxonomy: category: - woocommerce-rest-api post_tag: - V3 - Includes - Source


简介

WooCommerce 2.1 版本引入的 REST API 允许使用 JSON 格式对 WooCommerce 数据进行创建、读取、更新和删除操作。

要求

您必须使用 WooCommerce 2.1 或更高版本,并且需要在 WooCommerce > 设置 下启用 REST API。同时,您必须在 设置 > 固定链接 中启用美观的固定链接(默认的固定链接将无法工作)。

版本

当前 API 版本为 v3,它在端点中占据首要位置。下表展示了每个主要 WooCommerce 版本中存在的 API 版本:

API 版本 WooCommerce
v1 2.1.x, 2.2.x, 2.3.x 和 2.4.x
v2 2.2.x, 2.3.x 和 2.4.x
v3 2.4.x, 2.5.x

v1v2 API 将在未来版本中被移除。

v3 版本有哪些变化?

v1 与 v2 版本差异

历史版本 API 文档

架构

可通过以下端点访问此 API:

https://www.your-store.com/wc-api/v3

必须启用固定链接。您可以通过 HTTP 或 HTTPS 访问 API。在可能的情况下,建议使用 HTTPS,因为身份验证更简单。API 索引将声明站点是否支持 SSL。

请求/响应

默认响应格式为 JSON。包含消息体的请求使用纯 JSON 来设置或更新资源属性。成功的请求将返回 200 OK HTTP 状态码。

关于响应的一些通用信息:

认证

根据网站是否支持 SSL,有两种 API 认证方式。请记住,Index 端点会指示网站是否支持 SSL。

通过 HTTPS

您可以使用 HTTP 基本认证,将 API 消费者密钥作为用户名,API 消费者密钥作为密码。

HTTP 基本认证示例

curl https://www.example.com/wc-api/v3/orders \
    -u consumer_key:consumer_secret

有时某些服务器可能无法正确解析 Authorization 标头(如果在 SSL 认证时看到“Consumer key is missing”错误,则说明您的服务器有问题)。在这种情况下,您可以将消费者密钥/密钥作为查询字符串参数提供。

针对无法正确解析 Authorization 标头的服务器的示例:

curl https://www.example.com/wc-api/v3/orders?consumer_key=123&consumer_secret=abc

通过 HTTP 访问

您必须使用 OAuth 1.0a "单腿式" 认证 来确保 API 凭据不被截获。通常,您可以使用所选语言中的任何标准 OAuth 1.0a 库来处理认证,或按照以下说明生成必要的参数。

生成 OAuth 签名

1) 设置请求的 HTTP 方法:

GET

2) 设置你的基础请求 URI —— 这是不包含查询字符串参数的完整请求 URI —— 并根据 RFC 3986 进行 URL 编码:

http://www.example.com/wc-api/v1/orders

编码后:

http%3A%2F%2Fwww.example.com%2Fwc-api%2Fv1%2Forders

3) 收集并规范化你的查询字符串参数。这包括除签名外的所有 oauth_* 参数。参数应根据 RFC 3986(PHP 中的 rawurlencode)进行 URL 编码,并且百分号(%)字符应进行双重编码(例如,% 变为 %25)。

4) 按字节顺序对参数进行排序(PHP 中使用 uksort( $params, 'strcmp' )

5) 用编码后的等号(%3D)连接每个参数:

oauth_signature_method%3DHMAC-SHA1

6) 用编码后的与符号(%26)连接每个参数的键/值对:

oauth_consumer_key%3Dabc123%26oauth_signature_method%3DHMAC-SHA1

7) 通过用未编码的与符号(&)连接 HTTP 方法、编码后的基础请求 URI 和编码后的参数字符串,形成待签名字符串:

GET&http%3A%2F%2Fwww.example.com%2Fwc-api%2Fv1%2Forders&oauth_consumer_key%3Dabc123%26oauth_signature_method%3DHMAC-SHA1

8) 使用待签名字符串和你的消费者密钥生成签名

如果你在生成正确签名时遇到问题,应检查待签名字符串是否存在编码错误。认证源代码也有助于理解如何正确生成签名。

OAuth 使用技巧

参数

所有端点都接受可选参数,可通过 HTTP 查询字符串参数传递,例如 GET /orders?status=completed。参数分为通用参数和端点特定参数,这些参数会随相应端点一同记录。

筛选参数

所有端点都接受一个 filter 参数,该参数使用方括号来限定单个筛选条件,例如日期筛选:

GET /orders?filter[created_at_min]=2013-11-01

可以包含多个 filter 参数,并与其他参数混合使用:

GET /orders?status=completed&filter[created_at_min]=2013-11-01&filter[created_at_max]=2013-11-30

请注意,以下筛选条件适用于除 reports 端点外的所有端点,该端点有自己的一套筛选条件,这些条件与该端点一同记录。

可用过滤器

Filter Description
created_at_min given a date, only resources created after the provided date will be returned
created_at_max given a date, only resources created before the provided date will be returned
updated_at_min given a date, only resources updated after the provided date will be returned
updated_at_max given a date, only resources updated before the provided date will be returned
q performs a keyword search and returns resources that match, e.g. GET /products?filter[q]=search-keyword. Note that search terms should be URL-encoded as they will be decoded internally with urldecode
order controls the ordering of the resources returned, accepted values are ASC (default) or DESC
orderby controls the field that is used for ordering the resources returned. Accepts the same arguments as WP_Query. Defaults to date. You can order by meta_value but you must provide orderby_meta_key
orderby_meta_key the meta key to order returned resources by when using orderby=meta_value. For example, you could order products by price using GET /products?filter[orderby]=meta_value_num&filter[orderby_meta_key]=_price
post_status limits resources to only those with the specified post status. Most useful for returning unpublished products, e.g. GET /products?filter[post_status]=draft
meta resource meta is excluded by default, but it can be included by setting meta=true, e.g. GET /orders?filter[meta]=true. Protected meta (meta whose key is prefixed with an underscore) is not included in the response
pagination explained below

请注意,日期应以 RFC3339 格式在 UTC 时区提供:YYYY-MM-DDTHH:MM:SSZ。如果需要,可以省略时间和时区。

字段参数

您可以使用 fields 参数来限制响应中返回的字段:

GET /orders?fields=id

要包含多个字段,请用逗号分隔它们:

GET /orders?fields=id,status

您可以使用点符号指定子字段:

GET /orders?fields=id,status,payment_details.method_title

对于具有多个结构体的资源(例如订单的行项目),子字段无法被限制。例如,以下请求将只返回行项目,但每个行项目将包含完整的信息集,而不仅仅是产品ID:

GET /orders?fields=line_items.product_id

分页

返回多个项目的请求默认会分页为每页 10 个项目。站点管理员可以通过更改 posts_per_page 选项来修改此默认值。或者,也可以使用 ?filter[limit] 参数指定每页的项目数:

GET /orders?filter[limit]=15

您可以使用 ?page 参数指定后续页面:

GET /orders?page=2

您还可以使用 ?filter[offset] 参数指定从第一个资源开始的偏移量:

GET /orders?filter[offset]=5

页码从 1 开始计数,省略 ?page 参数将返回第一页。

资源总数和总页数始终包含在 X-WC-TotalX-WC-TotalPages HTTP 头中。

链接头部

分页信息包含在链接头部中。建议您尽可能遵循这些值,而不是自行构建 URL。

Link: <https://www.example.com/wc-api/v1/products?page=2>; rel="next",
<https://www.example.com/wc-api/v1/products?page=3>; rel="last"`

为便于阅读,已包含换行

可能的 rel 值有:

描述
next 显示下一页结果的 URL
last 显示最后一页结果的 URL
first 显示第一页结果的 URL
prev 显示上一页结果的 URL

错误处理

访问 API 时,您偶尔可能会遇到错误。主要有以下四种类型:

400 Bad Request 示例:

{
  "errors" : [
    {
      "code" : "woocommerce_api_unsupported_method",
      "message" : "Unsupported request method"
    }
  ]
}

401 Unauthorized 示例:

{
  "errors" : [
    {
      "code" : "woocommerce_api_authentication_error",
      "message" : "Consumer Key is invalid"
    }
  ]
}

404 Not Found 示例:

{
  "errors" : [
    {
      "code" : "woocommerce_api_invalid_order",
      "message" : "Invalid order"
    }
  ]
}

500 Internal Server Error 示例:

{
  "errors" : [
    {
      "code" : "woocommerce_api_invalid_handler",
      "message" : "The handler for the route is invalid"
    }
  ]
}

错误会返回相应的 HTTP 状态码和一个响应对象,该对象包含 codemessage 属性。如果某个端点有任何自定义错误,将在该端点的文档中进行说明。

HTTP Verbs

The API uses the appropriate HTTP verb for each action:

Verb Description
HEAD Can be used for any endpoint to return just the HTTP header information
GET Used for retrieving resources
PUT Used for updating resources
POST Used for creating resources
DELETE Used for deleting resources

JSONP Support

The API supports JSONP by default. JSONP responses use the application/javascript content-type. You can specify the callback using the ?_jsonp parameter for GET requests to have the response wrapped in a JSON function:

GET
/wc-api/v3/orders/count?_jsonp=ordersCount
curl https://example.com/wc-api/v3/orders/count?_jsonp=ordersCount \
    -u consumer_key:consumer_secret

Response:

\**\ordersCount({"count":8})

If the site administrator has chosen to disable it, you will receive a 400 Bad Request error:

{
  "errors": [
    {
      "code": "woocommerce_api_jsonp_disabled",
      "message": "JSONP support is disabled on this site"
    }
  ]
}

If your callback contains invalid characters, you will receive a 400 Bad Request error:

{
  "errors": [
    {
      "code": "woocommerce_api_jsonp_callback_invalid",
      "message": "The JSONP callback function is invalid"
    }
  ]
}

Webhooks

Webhooks 可通过 WooCommerce 设置界面或使用 REST API 端点进行管理。WC_Webhook 类负责管理自定义文章类型的所有数据存储与检索,以及将 webhook 操作加入队列、处理/发送/记录 webhook。在 woocommerce_init 时,会加载活跃的 webhooks 并添加其关联的钩子。

每个 webhook 包含:

主题

主题是资源(例如订单)和事件(例如创建)的组合,并映射到一个或多个钩子名称(例如 woocommerce_checkout_order_processed)。可以使用主题名称创建 Webhook,相应的钩子会自动添加。

核心主题包括:

也可以使用自定义主题,它们映射到单个钩子名称。例如,您可以添加一个主题为 action.woocommerce_add_to_cart 的 Webhook,该 Webhook 将在该事件触发时执行。自定义主题会将第一个钩子参数传递给有效载荷,因此在此示例中,cart_item_key 将包含在有效载荷中。

交付/负载

交付默认使用 wp_remote_post()(HTTP POST)完成,并通过 wp-cron 在后台处理。请求中添加了几个自定义标头,以帮助接收方处理 webhook:

负载采用 JSON 编码,对于 API 资源(优惠券、客户、订单、产品),其响应与通过 REST API 请求时完全相同。

日志记录

请求/响应以评论形式记录在 webhook 自定义文章类型中。每条投递日志包含:

为减少评论表膨胀,仅保留最近的 25 条投递日志。

连续 5 次投递失败(定义为非 HTTP 2xx 响应代码)后,webhook 将被禁用,必须通过 REST API 编辑以重新启用。

可通过 REST API 端点或使用 WC_Webhook::get_delivery_logs() 代码获取投递日志。

端点

请参阅 Webhook 资源部分

可视化界面

您可以通过访问“WooCommerce” > “设置” > “API” > “Webhooks”找到 Webhooks 界面,更多详情请参阅我们的可视化 Webhooks 文档

故障排除

Official Libraries

// Install:
// npm install --save woocommerce-api

// Setup:
var WooCommerceAPI = require('woocommerce-api');

var WooCommerce = new WooCommerceAPI({
  url: 'http://example.com', // Your store URL
  consumerKey: 'consumer_key', // Your consumer key
  consumerSecret: 'consumer_secret', // Your consumer secret
  version: 'v3' // WooCommerce API version
});
<?php 
// Install:
// composer require automattic/woocommerce

// Setup:
require __DIR__ . '/vendor/autoload.php';

use Automattic\WooCommerce\Client;

$woocommerce = new Client(
    'http://example.com', // Your store URL
    'consumer_key', // Your consumer key
    'consumer_secret', // Your consumer secret
    [
        'version' => 'v3' // WooCommerce API version
    ]
);
?>
# Install:
# pip install woocommerce

# Setup:
from woocommerce import API

wcapi = API(
    url="http://example.com", # Your store URL
    consumer_key="consumer_key", # Your consumer key
    consumer_secret="consumer_secret", # Your consumer secret
    version="v3" # WooCommerce API version
)
# Install:
# gem install woocommerce_api

# Setup:
require "woocommerce_api"

woocommerce = WooCommerce::API.new(
  "http://example.com", # Your store URL
  "consumer_key", # Your consumer key
  "consumer_secret", # Your consumer secret
  {
    version: "v3" # WooCommerce API version
  }
)

工具