跳到主要内容

购物车 API

购物车 API 返回当前会话或已登录用户的购物车当前状态。

所有 POST 接口都需要一个 随机数 Token 或一个 购物车 Token,并在完成时返回完整的购物车更新后的状态。

获取购物车

GET /cart

此接口不需要任何参数。

curl "https://example-store.com/wp-json/wc/store/v1/cart"

返回完整的购物车对象回复(参见 购物车回复)。

回复

/cart 下的所有接口(如本文档中所列)都以相同的格式返回回复:一个购物车对象,其中包含购物车项目、已应用的优惠券、配送地址和费率,以及非敏感的客户数据。

购物车回复

本节描述了购物车相关的回复。

请求参数:

  • cart_id: 购物车ID (整数)
  • user_id: 用户ID (整数)

请求示例:

GET /api/v1/cart/%s?user_id=%d

回复格式:

{
"status": "success",
"data": {
"cart_id": %d,
"user_id": %d,
"items": [
{
"product_id": %d,
"quantity": %d
}
]
}
}

错误代码:

代码描述
400错误的请求参数。
401未授权。
404购物车不存在。
500服务器内部错误。

示例回复:

{
"status": "success",
"data": {
"cart_id": 123,
"user_id": 456,
"items": [
{
"product_id": 789,
"quantity": 2
}
]
}
}

错误回复示例:

{
"status": "error",
"code": 404,
"message": "Cart not found."
}

注意事项:

  • status 字段表示请求是否成功。
  • data 字段包含购物车信息。
  • code 字段表示错误代码。
  • message 字段包含错误信息。

其他:

  • on 状态表示购物车已启用。
  • off 状态表示购物车已禁用。

函数:

  • get_cart_response(cart_id, user_id): 获取购物车回复。
  • create_cart(user_id): 创建新的购物车。
  • update_cart_item(cart_id, product_id, quantity): 更新购物车中的商品数量。
  • delete_cart_item(cart_id, product_id): 从购物车中删除商品。
  • clear_cart(cart_id): 清空购物车。
{
"items": [
{
"key": "a5771bce93e200c36f7cd9dfd0e5deaa",
"id": 38,
"quantity": 1,
"quantity_limits": {
"minimum": 1,
"maximum": 9999,
"multiple_of": 1,
"editable": true
},
"name": "带有Logo的帽子",
"short_description": "<p>这是一个简单的产品。</p>",
"description": "<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>",
"sku": "Woo-beanie-logo",
"low_stock_remaining": null,
"backorders_allowed": false,
"show_backorder_badge": false,
"sold_individually": false,
"permalink": "https://local.wordpress.test/product/beanie-with-logo/",
"images": [
{
"id": 61,
"src": "https://local.wordpress.test/wp-content/uploads/2023/03/beanie-with-logo-1.jpg",
"thumbnail": "https://local.wordpress.test/wp-content/uploads/2023/03/beanie-with-logo-1-450x450.jpg",
"srcset": "https://local.wordpress.test/wp-content/uploads/2023/03/beanie-with-logo-1.jpg 800w, https://local.wordpress.test/wp-content/uploads/2023/03/beanie-with-logo-1-450x450.jpg 450w, https://local.wordpress.test/wp-content/uploads/2023/03/beanie-with-logo-1-100x100.jpg 100w, https://local.wordpress.test/wp-content/uploads/2023/03/beanie-with-logo-1-600x600.jpg 600w, https://local.wordpress.test/wp-content/uploads/2023/03/beanie-with-logo-1-300x300.jpg 300w, https://local.wordpress.test/wp-content/uploads/2023/03/beanie-with-logo-1-150x150.jpg 150w, https://local.wordpress.test/wp-content/uploads/2023/03/beanie-with-logo-1-768x768.jpg 768w",
"sizes": "(max-width: 800px) 100vw, 800px",
"name": "beanie-with-logo-1.jpg",
"alt": ""
}
],
"variation": [],
"item_data": [],
"prices": {
"price": "1800",
"regular_price": "2000",
"sale_price": "1800",
"price_range": null,
"currency_code": "USD",
"currency_symbol": "$",
"currency_minor_unit": 2,
"currency_decimal_separator": ".",
"currency_thousand_separator": ",",
"currency_prefix": "$",
"currency_suffix": "",
"raw_prices": {
"precision": 6,
"price": "18000000",
"regular_price": "20000000",
"sale_price": "18000000"
}
},
"totals": {
"line_subtotal": "1800",
"line_subtotal_tax": "180",
"line_total": "1530",
"line_total_tax": "153",
"currency_code": "USD",
"currency_symbol": "$",
"currency_minor_unit": 2,
"currency_decimal_separator": ".",
"currency_thousand_separator": ",",
"currency_prefix": "$",
"currency_suffix": ""
},
"catalog_visibility": "visible",
"extensions": {}
},
{
"key": "b6d767d2f8ed5d21a44b0e5886680cb9",
"id": 22,
"quantity": 1,
"quantity_limits": {
"minimum": 1,
"maximum": 9999,
"multiple_of": 1,
"editable": true
},
"name": "腰带",
"short_description": "<p>这是一个简单的产品。</p>",
"description": "<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>",
"sku": "woo-belt",
"low_stock_remaining": null,
"backorders_allowed": false,
"show_backorder_badge": false,
"sold_individually": false,
"permalink": "https://local.wordpress.test/product/belt/",
"images": [
{
"id": 51,
"src": "https://local.wordpress.test/wp-content/uploads/2023/03/belt-2.jpg",
"thumbnail": "https://local.wordpress.test/wp-content/uploads/2023/03/belt-2-450x450.jpg",
"srcset": "https://local.wordpress.test/wp-content/uploads/2023/03/belt-2.jpg 801w, https://local.wordpress.test/wp-content/uploads/2023/03/belt-2-450x450.jpg 450w, https://local.wordpress.test/wp-content/uploads/2023/03/belt-2-100x100.jpg 100w, https://local.wordpress.test/wp-content/uploads/2023/03/belt-2-600x600.jpg 600w, https://local.wordpress.test/wp-content/uploads/2023/03/belt-2-300x300.jpg 300w, https://local.wordpress.test/wp-content/uploads/2023/03/belt-2-150x150.jpg 150w, https://local.wordpress.test/wp-content/uploads/2023/03/belt-2-768x768.jpg 768w",
"sizes": "(max-width: 801px) 100vw, 801px",
"name": "belt-2.jpg",
"alt": ""
}
],
"variation": [],
"item_data": [],
"prices": {
"price": "5500",
"regular_price": "6500",
"sale_price": "5500",
"price_range": null,
"currency_code": "USD",
"currency_symbol": "$",
"currency_minor_unit": 2,
"currency_decimal_separator": ".",
"currency_thousand_separator": ",",
"currency_prefix": "$",
"currency_suffix": "",
"raw_prices": {
"precision": 6,
"price": "55000000",
"regular_price": "65000000",
"sale_price": "55000000"
}
},
"totals": {
"line_subtotal": "5500",
"line_subtotal_tax": "550",
"line_total": "4675",
"line_total_tax": "468",
"currency_code": "USD",
"currency_symbol": "$",
"currency_minor_unit": 2,
"currency_decimal_separator": ".",
"currency_thousand_separator": ",",
"currency_prefix": "$",
"currency_suffix": ""
},
"catalog_visibility": "visible",
"extensions": {}
}
],
"coupons": [
{
"code": "test",
"discount_type": "percent",
"totals": {
"total_discount": "1095",
"total_discount_tax": "109",
"currency_code": "USD",
"currency_symbol": "$",
"currency_minor_unit": 2,
"currency_decimal_separator": ".",
"currency_thousand_separator": ",",
"currency_prefix": "$",
"currency_suffix": ""
}
}
],
"fees": [],
"totals": {
"total_items": "7300",
"total_items_tax": "730",
"total_fees": "0",
"total_fees_tax": "0",
"total_discount": "1095",
"total_discount_tax": "110",
"total_shipping": "1300",
"total_shipping_tax": "130",
"total_price": "8256",
"total_tax": "751",
"tax_lines": [
{
"name": "税费",
"price": "751",
"rate": "10%"
}
],
"currency_code": "USD",
"currency_symbol": "$",
"currency_minor_unit": 2,
"currency_decimal_separator": ".",
"currency_thousand_separator": ",",
"currency_prefix": "$",
"currency_suffix": ""
},
"shipping_address": {
"first_name": "John",
"last_name": "Doe",
"company": "",
"address_1": "Hello street",
"address_2": "",
"city": "beverly hills",
"state": "CA",
"postcode": "90211",
"country": "US",
"phone": "123456778"
},
"billing_address": {
"first_name": "John",
"last_name": "Doe",
"company": "",
"address_1": "Hello street",
"address_2": "",
"city": "beverly hills",
"state": "CA",
"postcode": "90211",
"country": "US",
"email": "checkout@templates.com",
"phone": "123456778"
},
"needs_payment": true,
"needs_shipping": true,
"payment_requirements": [ "products" ],
"has_calculated_shipping": true,
"shipping_rates": [
{
"package_id": 0,
"name": "Shipment 1",
"destination": {
"address_1": "Hello street",
"address_2": "",
"city": "beverly hills",
"state": "CA",
"postcode": "90211",
"country": "US"
},
"items": [
{
"key": "a5771bce93e200c36f7cd9dfd0e5deaa",
"name": "带有Logo的帽子",
"quantity": 1
},
{
"key": "b6d767d2f8ed5d21a44b0e5886680cb9",
"name": "腰带",
"quantity": 1
}
],
"shipping_rates": [
{
"rate_id": "flat_rate:10",
"name": "统一费率",
"description": "",
"delivery_time": "",
"price": "1300",
"taxes": "130",
"instance_id": 10,
"method_id": "flat_rate",
"meta_data": [
{
"key": "Items",
"value": "带有Logo的帽子 &times; 1, 腰带 &times; 1"
}
],
"selected": true,
"currency_code": "USD",
"currency_symbol": "$",
"currency_minor_unit": 2,
"currency_decimal_separator": ".",
"currency_thousand_separator": ",",
"currency_prefix": "$",
"currency_suffix": ""
},
{
"rate_id": "free_shipping:12",
"name": "免费配送",
"description": "",
"delivery_time": "",
"price": "0",
"taxes": "0",
"instance_id": 12,
"method_id": "free_shipping",
"meta_data": [
{
"key": "Items",
"value": "带有Logo的帽子 &times; 1, 腰带 &times; 1"
}
],
"selected": false,
"currency_code": "USD",
"currency_symbol": "$",
"currency_minor_unit": 2,
"currency_decimal_separator": ".",
"currency_thousand_separator": ",",
"currency_prefix": "$",
"currency_suffix": ""
},
{
"rate_id": "local_pickup:13",
"name": "本地自提",
"description": "",
"delivery_time": "",
"price": "0",
"taxes": "0",
"instance_id": 13,
"method_id": "local_pickup",
"meta_data": [
{
"key": "Items",
"value": "带有Logo的帽子 &times; 1, 腰带 &times; 1"
}
],
"selected": false,
"currency_code": "USD",
"currency_symbol": "$",
"currency_minor_unit": 2,
"currency_decimal_separator": ".",
"currency_thousand_separator": ",",
"currency_prefix": "$",
"currency_suffix": ""
}
]
}
],
"items_count": 2,
"items_weight": 0,
"cross_sells": [],
"errors": [],
"payment_methods": [ "bacs", "cod" ],
"extensions": {}
}

错误回复

如果无法执行购物车操作,将返回一个错误回复。 这将包含一个错误代码和一个错误消息:

{
"code": "woocommerce_rest_cart_invalid_product",
"message": "该产品无法添加到购物车。",
"data": {
"status": 400
}
}

某些错误回复表示冲突(错误 409),例如,当某个项目无法找到或优惠券不再生效时。 当返回此类回复时,服务器的购物车当前状态也会作为错误数据的一部分返回:

{
"code": "woocommerce_rest_cart_invalid_key",
"message": "购物车项目不再存在或无效。",
"data": {
"status": 409,
"cart": { ... }
}
}

这允许客户端在不发出额外请求的情况下,与购物车数据保持同步,即使购物车发生更改或已过期。

添加项目

将项目添加到购物车,并返回完整的购物车响应,或者返回一个错误。

除非提供了有效的 随机数 Token购物车 Token,否则此端点将返回一个错误。

POST /cart/add-item
属性类型必需描述
idinteger购物车中商品的 ID 或变体 ID。
quantityinteger购物车中此商品的数量。
variationarray选择的属性(用于变体),包含一个对象数组,每个对象包含键 attributevalue。 请注意,关于属性命名的说明见下文。
curl --header "Nonce: 12345" --request POST https://example-store.com/wp-json/wc/store/v1/cart/add-item?id=100&quantity=1

如果成功,则返回完整的 购物车响应;如果失败,则返回一个 错误响应

如果您希望在将购物车项目数据传递给 CartController::add_to_cart 之前添加补充数据,可以使用 woocommerce_store_api_add_to_cart_data 过滤器。 例如:

add_filter( 'woocommerce_store_api_add_to_cart_data', function( $add_to_cart_data, \WP_REST_Request $request ) {
if ( ! empty( $request['custom-request-param'] ) ) {
$add_to_cart_data['cart_item_data']['custom-request-data'] = sanitize_text_field( $request['custom-request-param'] );
}
return $add_to_cart_data;
}, 10, 2 );

变体属性命名:

在将变体添加到购物车时,属性的命名非常重要。

对于全局属性,发布到 API 的属性应该是属性的别名。 应该有一个 pa_ 前缀。 例如,如果您的属性名为 Color,则别名为 pa_color

对于特定于产品的属性,发布到 API 的属性可以是以下之一:

  • 属性的名称。 例如,如果您的属性名为 Size,则名称为 Size。 这对大小写敏感。
  • 属性的别名。 例如,如果您的属性名为 Autograph ✏️,则名称为 attribute_autograph-%e2%9c%8f%ef%b8%8f。 这对大小写敏感。 您可以从产品页面的相关 select 中获取此别名。

示例 POST 请求体:

# 添加商品变体到购物车

以下示例向购物车添加了一个商品变体,该变体具有尺寸和颜色等属性。

**批量操作:**

如果您想一次性添加多个项目,则需要使用批量接口:

```http
POST /wc/store/v1/batch

向购物车添加多个项目的 JSON 数据格式如下:

{
"requests": [
{
"path": "/wc/store/v1/cart/add-item",
"method": "POST",
"cache": "no-store",
"body": {
"id": 26,
"quantity": 1
},
"headers": {
"Nonce": "1db1d13784"
}
},
{
"path": "/wc/store/v1/cart/add-item",
"method": "POST",
"cache": "no-store",
"body": {
"id": 27,
"quantity": 1
},
"headers": {
"Nonce": "1db1d13784"
}
}
]
}
{
"id": 13,
"quantity": 1,
"variation": [
{
"attribute": "pa_color",
"value": "blue"
},
{
"attribute": "attribute_autograph-%e2%9c%8f%ef%b8%8f",
"value": "Yes"
},
{
"attribute": "Logo",
"value": "Yes"
}
]
}

该示例添加了一个具有尺寸和颜色属性的产品变体到购物车。

Batching:

如果您想一次添加多个项目,您需要使用批量接口:

POST /wc/store/v1/batch

用于向购物车添加多个项目的 JSON 数据如下:

{
"requests": [
{
"path": "/wc/store/v1/cart/add-item",
"method": "POST",
"cache": "no-store",
"body": {
"id": 26,
"quantity": 1
},
"headers": {
"Nonce": "1db1d13784"
}
},
{
"path": "/wc/store/v1/cart/add-item",
"method": "POST",
"cache": "no-store",
"body": {
"id": 27,
"quantity": 1
},
"headers": {
"Nonce": "1db1d13784"
}
}
]
}

解释:

  • Variation: 变体
  • Nonce: 随机数
  • Attribute: 属性
  • Quantity: 数量
  • Requests: 请求
  • Product: 产品
  • Method: 方法
  • Cache: 缓存
  • Color: 颜色
  • Value: 价值
  • Store: 商店
  • Path: 路径
  • Auto: 自动
  • Blue: 蓝色
  • Cart: 购物车
  • Item: 项目
  • Log: 日志
  • and: 和
  • Use: 使用
  • For: 为

移除项目

从购物车中移除一个项目,并返回完整的购物车响应,或者返回一个错误。

除非提供了有效的 随机数 Token购物车 Token,否则此接口将返回一个错误。

POST /cart/remove-item
属性类型必需描述
key字符串要编辑的购物车项目的键。
curl --header "Nonce: 12345" --request POST https://example-store.com/wp-json/wc/store/v1/cart/remove-item?key=e369853df766fa44e1ed0ff613f563bd

在成功时,返回完整的 购物车响应,在失败时,返回一个 错误响应

更新项目

更新购物车中的一个项目,并返回完整的购物车响应,或者返回一个错误。

除非提供了有效的 随机数 Token购物车 Token,否则此接口将返回一个错误。

POST /cart/update-item
属性类型必需描述
key字符串要编辑的购物车项目的键。
quantity整数购物车中此项目的数量。
curl --header "Nonce: 12345" --request POST https://example-store.com/wp-json/wc/store/v1/cart/update-item?key=e369853df766fa44e1ed0ff613f563bd&quantity=10

在成功时,返回完整的 购物车响应,在失败时,返回一个 错误响应

应用优惠券

将优惠券应用于购物车,并返回完整的购物车响应,或者返回一个错误。

除非提供了有效的 随机数 Token购物车 Token,否则此接口将返回一个错误。

POST /cart/apply-coupon/
属性类型必需描述
code字符串您希望应用于购物车的优惠券代码。
curl --header "Nonce: 12345" --request POST https://example-store.com/wp-json/wc/store/v1/cart/apply-coupon?code=20off

在成功时,返回完整的 购物车响应,在失败时,返回一个 错误响应

移除优惠券

从购物车中移除一个优惠券,并返回完整的购物车响应,或者返回一个错误。

除非提供了有效的 随机数购物车令牌,否则此接口将返回一个错误。

POST /cart/remove-coupon/
属性类型必需描述
code字符串您希望从购物车中移除的优惠券代码。
curl --header "Nonce: 12345" --request POST https://example-store.com/wp-json/wc/store/v1/cart/remove-coupon?code=20off

在成功时,返回完整的 购物车响应,在失败时,返回一个 错误响应

更新客户信息

更新客户信息,并返回完整的购物车信息,或者返回一个错误。

除非提供了有效的 随机数 Token购物车 Token,否则此 API 将返回一个错误。

POST /cart/update-customer

客户地址信息

本节描述了客户地址信息的结构。

属性类型必填描述
billing_addressobject客户的账单地址。
billing_address.first_namestring客户的名。
billing_address.last_namestring客户的姓氏。
billing_address.address_1string配送地址的第一行。
billing_address.address_2string配送地址的第二行。
billing_address.citystring配送地址的城市。
billing_address.statestring州、省或地区的 ISO 代码,或名称,用于表示配送地址。
billing_address.postcodestring配送地址的邮政编码。
billing_address.countrystring配送地址所在国家的 ISO 代码。
billing_address.emailstring客户的邮件地址。
billing_address.phonestring客户的电话号码。
shipping_addressobject客户的配送地址。
shipping_address.first_namestring客户的名。
shipping_address.last_namestring客户的姓氏。
shipping_address.address_1string配送地址的第一行。
shipping_address.address_2string配送地址的第二行。
shipping_address.citystring配送地址的城市。
shipping_address.statestring州、省或地区的 ISO 代码,或名称,用于表示配送地址。
shipping_address.postcodestring配送地址的邮政编码。
shipping_address.countrystring配送地址所在国家的 ISO 代码。

以下是一些示例:

# 示例 1: 创建一个包含账单地址和配送地址的客户对象。
customer = {
"billing_address": {
"first_name": "名",
"last_name": "姓氏",
"address_1": "地址",
"address_2": "",
"city": "城市",
"state": "州",
"postcode": "邮政编码",
"country": "国家",
"email": "邮件",
"phone": "电话号码"
},
"shipping_address": {
"first_name": "名",
"last_name": "姓氏",
"address_1": "地址",
"address_2": "",
"city": "城市",
"state": "州",
"postcode": "邮政编码",
"country": "国家"
}
}

# 示例 2: 设置一个客户的属性。
set_customer_attribute(customer, "description", "描述")

# 示例 3: 获取一个数值。
number = get_number()

# 示例 4: 循环 %d 秒。
for i in range(1, %d):
print("一 %s 秒" % "second")

# 示例 5: 检查一个条件。
if no:
print("否")
else:
print("是")

# 示例 6: 使用 Code

请注意,String 是一个 String 类型。 Phone Number 必须是有效的 Phone NumberFirst name 不能为空。 Attribute 必须是有效的 AttributeLast Name 不能为空。 Shipping 必须是有效的 Shipping 地址。 Address 必须是有效的 AddressSecond 表示 Secondnumber 表示 numberCode 表示 CodeMail 表示 MailRed 表示 Redone 表示 oneFor 表示 ForIn 表示 InNo 表示 NoShipping Address 表示 Shipping AddressDescription 表示 DescriptionCustomer 表示 Customer

返回全部购物车回复,如果成功;否则,返回一个 错误回复

选择配送费率

选择一个可用的配送费率,然后返回完整的购物车响应,或者返回一个错误。

除非提供了有效的 随机数 Token购物车 Token,否则此接口将返回一个错误。

POST /cart/select-shipping-rate
属性类型必需描述
package_idinteger购物车中配送包的 ID。
rate_idstring选定的配送包的费率 ID。
curl --header "Nonce: 12345" --request POST /cart/select-shipping-rate?package_id=1&rate_id=flat_rate:1

在成功时,返回完整的 购物车响应,在失败时,返回一个 错误响应