如何通过Shopify Storefront API获取指定客户的购物车ID及详情
Shopify Storefront API:跨设备/登出后获取购物车ID方案
默认通过cartCreate创建的是匿名购物车,和顾客账号无绑定关系,无法直接通过Customer Token获取未关联的购物车ID。要实现跨设备或登出后找回购物车,可采用以下方案:
1. 将购物车绑定到顾客身份(推荐)
当用户完成登录后,使用cartBuyerIdentityUpdate mutation把匿名购物车与顾客身份关联,请求时需携带有效的Customer Token:
mutation cartBuyerIdentityUpdate($cartId: ID!, $buyerIdentity: CartBuyerIdentityInput!) { cartBuyerIdentityUpdate(cartId: $cartId, buyerIdentity: $buyerIdentity) { cart { id buyerIdentity { email customer { id } } } } }
关联完成后,用户后续换设备登录或登出再登录时,可通过Customer Token查询顾客关联的购物车:
query getCustomerCart($customerAccessToken: String!) { customer(customerAccessToken: $customerAccessToken) { cart { id createdAt updatedAt lines(first: 10) { edges { node { id quantity merchandise { ... on ProductVariant { id } } } } } cost { totalAmount { amount currencyCode } } } } }
2. 本地存储购物车ID(匿名用户临时方案)
对于未登录的匿名用户,创建购物车后将cart id存储在浏览器的localStorage(持久化)或sessionStorage(会话级)中;如果是移动端APP,则存储在本地沙箱存储内。
- 局限性:仅在同一设备/浏览器有效,换设备后无法获取,且购物车会在Shopify默认的14天过期后被清理。
3. 自建服务器存储关联关系
如果你的平台有独立用户体系,可在用户登录时,将购物车ID与用户ID绑定后存储到自有数据库中。用户换设备登录时,从数据库取出对应购物车ID,再调用Storefront API查询详情。
内容的提问来源于stack exchange,提问作者Md. Rakibul hasan
相关产品推荐
相关产品推荐

