购物车 API 实现

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

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

创建购物车

此端点允许创建新的购物车会话。如需集成,请实现 CreateCart 端点 (POST /carts)。当用户选择转移其购物车时,Google 会调用此端点并提供所有商品详情。您的系统必须通过 continue_url 进行响应,将用户引导至您网站上预先填充的购物车。

  • 端点POST /carts
  • 触发条件:仅当用户点击转移按钮(例如,在商家网站上结账)以将其购物车转移到您的商店时,才会触发单个 CreateCart (POST /carts) 请求。

购物车流程

购物车流程和状态的工作方式如下:

  • Google 上的累积:当用户将商品添加到购物车时,Google 会在本地累积这些商品。Google 不会在添加商品时触发多次 API 调用。
  • 载荷:单个 POST /carts 请求将包含所有累积的 line_items 的完整数组。
  • 重定向和状态:商家的后端会通过 continue_url 进行响应,指向其网站上预先填充的购物车。

请求: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"
}

错误处理

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