You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取正确Shopify Cart ID以调用cartDiscountCodesUpdate API?

如何获取Shopify购物车创建后的正确Cart ID用于Storefront API?

我想在购物车页面通过Shopify Storefront API的cartDiscountCodesUpdate接口应用折扣码,该接口要求传入Cart ID。我已经创建了cart/create webhook,其返回的payload里包含类似1eef2aa2c2b2e889ec325db72f0877ec格式的id字符串。

我将这个id拼接成gid格式后调用接口,代码如下:

mutation cartDiscountCodesUpdate($cartId: ID!, $discountCodes: [String!]) {
  cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $discountCodes) {
   cart {
     id
   }
   userErrors {
     field
     message
   }
  }
 }

查询变量:

{
"cartId": "gid://shopify/Cart/1eef2aa2c2b2e889ec325db72f0877ec",
"discountCodes": [
"64J1ZQMBN9W5"
]
}

但接口返回错误:

{
  "data": {
  "cartDiscountCodesUpdate": {
  "cart": null,
  "userErrors": [
    {
      "field": [
        "cartId"
      ],
      "message": "The specified cart does not exist."
    }
    ]
   }
  }
 }

我怀疑是Cart ID不正确,请问该如何获取购物车创建后的正确Cart ID?


解决方案
  • 区分后台与前端购物车ID体系:cart/create webhook返回的是Shopify后台管理层面的购物车ID,和Storefront API使用的前端访客购物车属于完全独立的资源体系,不能直接转换混用。后台ID仅适用于Admin API操作,无法在Storefront API中使用。

  • 通过Storefront API创建购物车获取合法ID:在前端场景下,必须直接调用Storefront API的cartCreate mutation来创建购物车,接口会返回标准的gid格式Cart ID,这个ID才能用于后续的cartDiscountCodesUpdate等操作。示例代码:

mutation cartCreate($input: CartInput!) {
  cartCreate(input: $input) {
    cart {
      id
      checkoutUrl
    }
    userErrors {
      field
      message
    }
  }
}

对应的变量示例:

{
  "input": {
    "lines": [
      {
        "quantity": 1,
        "merchandiseId": "gid://shopify/ProductVariant/123456789"
      }
    ]
  }
}
  • 保证会话一致性:Storefront API的购物车与访客会话绑定,调用相关接口时需携带有效的X-Shopify-Storefront-Access-Token,并且要在前端存储好返回的Cart ID(比如用localStorage),确保后续操作使用同一个ID,避免因会话不一致导致“购物车不存在”的错误。

内容的提问来源于stack exchange,提问作者user254153

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 08:48:20