# 简介 #

WooCommerce (WC) 2.6+ 已与 WordPress [REST](http://en.wikipedia.org/wiki/Representational_State_Transfer) API 完全集成。这使得可以使用 JSON 格式的请求、WordPress REST API 认证方法以及大多数 HTTP 客户端都能理解的标准 HTTP 动词来创建、读取、更新和删除 WC 数据。

当前的 WP REST API 集成版本为 `v2`，它在端点中占据首要位置。

下表展示了每个 WooCommerce 主要版本中存在的 API 版本：

| API 版本   |   WC 版本      |  WP 版本    |       文档               |
|-------------|----------------|--------------|---------------------------|
| `v2`        | 3.0.x 或更高   | 4.4 或更高   | -                         |
| `v1`        | 2.6.x 或更高   | 4.4 或更高   | [v1 文档](source/includes/wp-api-v2/wp-api-v1.html) |

在 2.6 版本之前，WooCommerce 拥有一个独立于 WordPress 的 REST API，现在称为旧版 API。您可以单独找到旧版 API 的文档。

| API 版本     | WC 版本       | WP 版本    | 文档                     |
|-------------|---------------|------------|---------------------------|
| `Legacy v3` | 2.4.x 或更高  | 4.1 或更高 | [Legacy v3 文档](source/includes/wp-api-v2/v3.html) |
| `Legacy v2` | 2.2.x 或更高  | 4.1 或更高 | [Legacy v2 文档](source/includes/wp-api-v2/v2.html) |
| `Legacy v1` | 2.1.x 或更高  | 4.1 或更高 | [Legacy v1 文档](source/includes/wp-api-v2/v1.html) |

## 要求 ##

要使用最新版本的 REST API，您必须满足以下条件：

* WooCommerce 2.6 或更高版本。
* WordPress 4.4 或更高版本。
* 在 `设置 > 固定链接` 中启用美观的固定链接，以支持自定义端点。__默认的固定链接将无法工作。__
* 您可以通过 HTTP 或 HTTPS 访问 API，但*建议尽可能使用 HTTPS*。

如果您使用 ModSecurity 并看到 `501 方法未实现` 错误，请参阅 [此问题](https://github.com/woocommerce/woocommerce/issues/9838) 了解详情。

<aside class="notice">
	请注意，您 <strong>无需</strong> 安装 <a href="https://wordpress.org/plugins/rest-api/" target="_blank">WP REST API (WP API)</a> 插件。
</aside>

## 请求/响应格式 ##

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

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

* 日期以 ISO8601 格式返回：`YYYY-MM-DDTHH:MM:SS`
* 资源 ID 以整数形式返回。
* 任何十进制货币金额，例如价格或总计，将以保留两位小数的字符串形式返回。
* 其他数量，例如项目计数，以整数形式返回。
* 空字段通常包含为 `null` 或空字符串，而非被省略。

### JSONP 支持 ###

WP REST API 默认支持 JSONP。JSONP 响应使用 `application/javascript` 内容类型。对于 `GET` 请求，您可以使用 `?_jsonp` 参数指定回调函数，使响应包装在 JSON 函数中：

<div class="api-endpoint">
	<div class="endpoint-data">
		<i class="label label-get">GET</i>
		<h6>/wp-json/wc/v2?_jsonp=callback</h6>
	</div>
</div>

```shell
curl https://example.com/wp-json/wc/v2/products/tags/34?_jsonp=tagDetails \
	-u consumer_key:consumer_secret
```

```javascript
WooCommerce.get("products/tags/34?_jsonp=tagDetails")
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error.response.data);
  });
```

```php
<?php print_r($woocommerce->get('products/tags/34', ['_jsonp' => 'tagDetails'])); ?>
```

```python
print(wcapi.get("products/tags/34?_jsonp=tagDetails").json())
```

```ruby
woocommerce.get("products/tags/34", _jsonp: "tagDetails").parsed_response
```

> 响应示例：

```
/**/tagDetails({"id":34,"name":"Leather Shoes","slug":"leather-shoes","description":"","count":0,"_links":{"self":[{"href":"https://example.com/wp-json/wc/v2/products/tags/34"}],"collection":[{"href":"https://example.com/wp-json/wc/v2/products/tags"}]}})%
```

## Errors ##

Occasionally you might encounter errors when accessing the REST API. There are four possible types:

| Error Code | Error Type |
|------------|------------|
| `400 Bad Request` | Invalid request, e.g. using an unsupported HTTP method | 
| `401 Unauthorized` | Authentication or permission error, e.g. incorrect API keys |
| `404 Not Found` | Requests to resources that don't exist or are missing |
| `500 Internal Server Error` | Server error |

> WP REST API error example:

```json
{
  "code": "rest_no_route",
  "message": "No route was found matching the URL and request method",
  "data": {
    "status": 404
  }
}
```

> WooCommerce REST API error example:

```json
{
  "code": "woocommerce_rest_term_invalid",
  "message": "Resource doesn't exist.",
  "data": {
    "status": 404
  }
}
```

Errors return both an appropriate HTTP status code and response object which contains a `code`, `message` and `data` attribute.

## 参数 ##

几乎所有端点都接受可选参数，可通过 HTTP 查询字符串参数传递，例如 `GET /orders?status=completed`。所有参数均随各端点文档一同说明。

## 分页 ##

返回多个项目的请求默认会分页为每页 10 项。站点管理员可以通过修改 `posts_per_page` 选项来更改此默认值。或者，也可以通过 `?per_page` 参数指定每页的项目数：

`GET /orders?per_page=15`

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

`GET /orders?page=2`

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

`GET /orders?offset=5`

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

资源总数和总页数始终包含在 `X-WP-Total` 和 `X-WP-TotalPages` HTTP 头中。

### 链接头信息 ###

分页信息包含在[链接头信息](http://tools.ietf.org/html/rfc5988)中。建议您尽可能遵循这些值，而不是自行构建URL。

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

可能的 `rel` 值包括：

|   值    |                        描述                         |
|---------|-----------------------------------------------------|
| `next`  | 显示下一页结果的URL。                                 |
| `last`  | 显示最后一页结果的URL。                               |
| `first` | 显示第一页结果的URL。                                 |
| `prev`  | 显示上一页结果的URL。                                 |

## Libraries and Tools ##

### Official libraries ###

- [JavaScript](https://www.npmjs.com/package/@woocommerce/woocommerce-rest-api) Library
- [PHP](https://packagist.org/packages/automattic/woocommerce) Library
- [Python](https://pypi.python.org/pypi/WooCommerce) Library
- [Ruby](https://rubygems.org/gems/woocommerce_api) Library

```javascript
// Install:
// npm install --save @woocommerce/woocommerce-rest-api

// Setup:
const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;
// import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api"; // Supports ESM

const WooCommerce = new WooCommerceRestApi({
  url: 'http://example.com', // Your store URL
  consumerKey: 'consumer_key', // Your consumer key
  consumerSecret: 'consumer_secret', // Your consumer secret
  version: 'wc/v2' // WooCommerce WP REST API version
});
```

```php
<?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
    [
        'wp_api' => true, // Enable the WP REST API integration
        'version' => 'wc/v2' // WooCommerce WP REST API version
    ]
);
?>
```

```python
# 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
    wp_api=True, # Enable the WP REST API integration
    version="wc/v2" # WooCommerce WP REST API version
)
```

```ruby
# Install:
# gem install woocommerce_api

# Setup:
require "woocommerce_api"

woocommerce = WooCommerce::API.new(
  "https://example.com", # Your store URL
  "consumer_key", # Your consumer key
  "consumer_secret", # Your consumer secret
  {
    wp_api: true, # Enable the WP REST API integration
    version: "wc/v2" # WooCommerce WP REST API version
  }
)
```

<aside class="notice">
	Use the tabs in the top-right corner of this page to see how to install and use each library.
</aside>

### 第三方库 ###

- [Java](https://github.com/icoderman/wc-api-java) 库
- [.NET](https://github.com/XiaoFaye/WooCommerce.NET) 库
- [Android](https://github.com/gilokimu/WooDroid) 库

<aside class="notice">
	请注意，我们不提供对第三方库的支持，因此如果您对如何使用这些库有任何疑问，请联系相应的作者。
</aside>

### 工具 ###

以下是一些可用于访问 API 的实用工具：

- [Insomnia](https://insomnia.rest) - 跨平台 GraphQL 和 REST 客户端，适用于 Mac、Windows 和 Linux。
- [Postman](https://www.getpostman.com/) - 跨平台 REST 客户端，适用于 Mac、Windows 和 Linux。
- [RequestBin](https://requestbin.com) - 允许你测试 Webhooks。
- [Hookbin](https://hookbin.com/) - 另一个测试 Webhooks 的工具。