购物车 API 实现

本指南提供了在 2026-04-08 版中集成通用商务协议 (UCP) 购物车 API 的技术 API 参考文档和载荷架构。

在构建端点之前,请务必查看 购物车 API 概览,了解高级 概念和前提条件。

创建购物车

此端点允许创建新的购物车会话。如需集成,请实现 CreateCart 端点 (POST /carts)。当用户选择转移购物车时,Google 会使用专列项详细信息调用此端点。您的系统必须使用 continue_url 进行响应,将用户定向到您网站上预先填充的购物车。

  • 端点POST /carts
  • 触发条件: 用户点击商品上的“添加到购物车”,并将第一件商品添加到商家的购物车中。

请求: Google 会发送要添加到购物车的 line_items 数组。

请求示例:

{
  "line_items": [
    {
      "item": {
        "id": "item_123"
      },
      "quantity": 2
    }
  ]
}

响应: 您会返回已初始化的购物车会话,包括专列项详细信息、总计和 continue_url。响应中的 continue_url 字段必须将用户定向回您网站上的一个页面,以便他们继续管理购物车。这通常会链接到您的购物车或结账页,并预先加载由 id 标识的会话。

响应示例:

{
  "ucp": {
    "version": "2026-04-08",
    "capabilities": {
      "dev.ucp.shopping.cart": [{"version": "2026-04-08"}]
    }
  },
  "id": "cart_abc123",
  "line_items": [
    {
      "id": "li_1",
      "item": {
        "id": "item_123",
        "title": "Red T-Shirt",
        "price": 2500
      },
      "quantity": 2,
      "totals": [
        {"type": "subtotal", "amount": 5000},
        {"type": "total", "amount": 5000}
      ]
    }
  ],
  "currency": "USD",
  "totals": [
    {
      "type": "subtotal",
      "amount": 5000
    },
    {
      "type": "total",
      "amount": 5000,
      "display_text": "Estimated total (taxes calculated at checkout)"
    }
  ],
  // Used for redirecting the user back to the merchant's cart experience from Google surfaces.
  "continue_url": "https://business.example.com/checkout?cart=cart_abc123",
  // Indicate the timestamp at which the cart session will expire and become invalid.
  "expires_at": "2026-01-16T12:00:00Z"
}

错误处理

如需了解有关如何设置错误消息格式以及协议错误和业务逻辑错误之间区别的完整指南,请参阅错误代码