cart-logic

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cart Logic

购物车逻辑

Overview

概述

Cart logic covers how your store manages items a shopper intends to buy: adding, removing, and updating items; persisting the cart across page loads and devices; and merging a guest cart into an account when the customer logs in. On Shopify, WooCommerce, and BigCommerce, the cart is built into the platform — the goal is to configure it correctly and extend it when needed. Custom code is only required for headless storefronts.
购物车逻辑涵盖了店铺如何管理购物者打算购买的商品:包括添加、删除和更新商品;在页面刷新和跨设备时保持购物车状态;以及当客户登录时将访客购物车合并到账户购物车中。在Shopify、WooCommerce和BigCommerce平台上,购物车是内置功能——目标是正确配置它,并在需要时进行扩展。只有无头店铺(headless storefronts)才需要自定义代码。

When to Use This Skill

何时使用此技能

  • When cart state is lost when users navigate between pages (missing persistence)
  • When guest cart items disappear after login (missing merge logic)
  • When implementing real-time cart price updates (coupons, quantity changes, shipping estimates)
  • When building a headless storefront that needs a custom cart implementation
  • 当用户在页面间导航时购物车状态丢失(缺少持久化机制)
  • 登录后访客购物车商品消失(缺少合并逻辑)
  • 实现购物车价格实时更新(优惠券、数量变更、运费估算)
  • 构建需要自定义购物车实现的无头店铺

Core Instructions

核心操作指南

Step 1: Understand how your platform handles cart logic

步骤1:了解你的平台如何处理购物车逻辑

PlatformCart BehaviorWhere to Configure
ShopifyBuilt-in cart with automatic persistence; uses cookies/localStorageTheme Liquid templates + Cart API; extend with Cart Transform Shopify Function
WooCommerceBuilt-in cart with session persistence; configures via PHP hooksWooCommerce settings +
woocommerce_add_cart_item_data
and
woocommerce_cart_item_price
filters
BigCommerceBuilt-in Storefront Cart API; cart persists via cookieBigCommerce Stencil theme + Storefront Cart API
Custom / HeadlessMust build from scratch using platform APIs or Shopify/BigCommerce Storefront APISee Custom / Headless section below
平台购物车行为配置位置
Shopify内置购物车,自动持久化;使用cookies/localStorage主题Liquid模板 + Cart API;通过Cart Transform Shopify Function扩展
WooCommerce内置购物车,基于会话持久化;通过PHP钩子配置WooCommerce设置 +
woocommerce_add_cart_item_data
woocommerce_cart_item_price
过滤器
BigCommerce内置Storefront Cart API;通过cookie保持购物车状态BigCommerce Stencil主题 + Storefront Cart API
自定义/无头必须使用平台API或Shopify/BigCommerce Storefront API从头构建见下文「自定义/无头」部分

Step 2: Configure and extend cart behavior

步骤2:配置并扩展购物车行为



Shopify

Shopify

Shopify's cart is managed automatically. To extend it:
Customize the cart drawer or page:
  1. Go to Online Store → Themes → Customize
  2. Select the cart section and configure: cart type (drawer vs. page), item display, quantity controls
  3. Enable Cart notes and Shipping estimate in the cart settings if needed
Enable cart persistence across devices (requires accounts):
  • Shopify automatically persists cart for logged-in customers; the cart is stored server-side on their account
  • For guest carts, Shopify uses a
    cart_token
    cookie (30-day expiry by default)
Merge guest cart on login:
  • Shopify handles this automatically — when a guest logs in, their cart is merged with any existing account cart
Cart customization via Shopify Functions: Use Cart Transform Shopify Functions to modify cart items, apply custom discounts, or bundle products. Go to Settings → Custom data and deploy a Cart Transform function via the Shopify CLI.
Custom cart upsells and cross-sells: Install CartHook, ReConvert, or Frequently Bought Together from the Shopify App Store for cart upsell logic without custom code.

Shopify的购物车由系统自动管理。如需扩展功能:
自定义购物车抽屉或页面:
  1. 进入 在线商店 → 主题 → 自定义
  2. 选择购物车板块并配置:购物车类型(抽屉式 vs 页面式)、商品展示、数量控制
  3. 如有需要,在购物车设置中启用 购物车备注运费估算
启用跨设备购物车持久化(需要账户功能):
  • Shopify会自动为登录客户保存购物车;购物车存储在服务器端的客户账户中
  • 对于访客购物车,Shopify使用
    cart_token
    cookie(默认有效期30天)
登录时合并访客购物车:
  • Shopify会自动处理此操作——当访客登录时,其购物车会与账户中已有的购物车合并
通过Shopify Functions自定义购物车: 使用 Cart Transform Shopify Functions修改购物车商品、应用自定义折扣或捆绑商品。进入 设置 → 自定义数据,通过Shopify CLI部署Cart Transform函数。
购物车追加销售和交叉销售: 从Shopify应用商店安装 CartHookReConvertFrequently Bought Together,无需自定义代码即可实现购物车追加销售逻辑。

WooCommerce

WooCommerce

WooCommerce's cart is built-in and session-based.
Configure cart behavior:
  1. Go to WooCommerce → Settings → Products → General to configure cart and add-to-cart behavior
  2. Enable or disable Redirect to cart page after successful addition based on your store's UX preference
  3. Under WooCommerce → Settings → Advanced → Cart page, verify the cart page is assigned
Enable persistent cart for logged-in users:
  1. Go to WooCommerce → Settings → Accounts & Privacy
  2. Enable Persistent cart — this stores a logged-in customer's cart in the database so it survives across sessions and devices
Guest cart to account merge: WooCommerce automatically merges the guest cart with the customer's saved cart when they log in. To ensure this works, keep Persistent cart enabled.
Extend cart item data (e.g., for product customization options): Use the
woocommerce_add_cart_item_data
filter in your theme's
functions.php
or a custom plugin to attach extra data to cart items (gift messages, engraving text, etc.).
Cart abandonment tracking: Install CartFlows or WooCommerce Cart Abandonment Recovery plugin to track and recover abandoned carts.

WooCommerce的购物车是内置的,基于会话管理。
配置购物车行为:
  1. 进入 WooCommerce → 设置 → 商品 → 常规 配置购物车和加入购物车行为
  2. 根据店铺的UX偏好,启用或禁用 成功加入后重定向到购物车页面
  3. WooCommerce → 设置 → 高级 → 购物车页面 中,确认已指定购物车页面
为登录用户启用持久化购物车:
  1. 进入 WooCommerce → 设置 → 账户与隐私
  2. 启用 持久化购物车——此功能会将登录客户的购物车存储在数据库中,使其在不同会话和设备间保持有效
访客购物车与账户购物车合并: 当客户登录时,WooCommerce会自动将访客购物车与客户保存的购物车合并。确保此功能正常工作,请保持 持久化购物车 处于启用状态。
扩展购物车商品数据(例如产品自定义选项): 在主题的
functions.php
或自定义插件中使用
woocommerce_add_cart_item_data
过滤器,为购物车商品附加额外数据(礼品留言、雕刻文字等)。
购物车弃购追踪: 安装 CartFlowsWooCommerce Cart Abandonment Recovery 插件,追踪并挽回弃购购物车。

BigCommerce

BigCommerce

BigCommerce uses its Storefront Cart API for cart management.
Configure cart settings:
  1. Go to Settings → Storefront to configure cart and checkout behavior
  2. Cart persistence is automatic via BigCommerce's session management
Customize the cart via Stencil theme: Edit cart templates in your Stencil theme (
templates/components/cart/
) to modify the cart page layout, item display, and available actions.
Cart upsells: Use the BigCommerce Cart API to detect items in the cart and conditionally show related products or promotions in the cart template.

BigCommerce使用Storefront Cart API管理购物车。
配置购物车设置:
  1. 进入 设置 → 店铺前端 配置购物车和结账行为
  2. 通过BigCommerce的会话管理自动实现购物车持久化
通过Stencil主题自定义购物车: 编辑Stencil主题中的购物车模板(
templates/components/cart/
),修改购物车页面布局、商品展示和可用操作。
购物车追加销售: 使用BigCommerce Cart API检测购物车中的商品,并在购物车模板中条件性展示相关商品或促销活动。

Custom / Headless

自定义/无头

For a headless storefront, use your platform's Storefront API rather than building cart storage from scratch:
Shopify Storefront API (recommended for Shopify-backed headless stores):
javascript
// Create a cart
const createCart = async () => {
  const response = await fetch(`https://${SHOP_DOMAIN}/api/2024-01/graphql.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': STOREFRONT_TOKEN,
    },
    body: JSON.stringify({
      query: `
        mutation cartCreate($input: CartInput!) {
          cartCreate(input: $input) {
            cart { id checkoutUrl }
            userErrors { field message }
          }
        }
      `,
      variables: { input: { lines: [{ merchandiseId: variantGid, quantity: 1 }] } },
    }),
  });
  const { data } = await response.json();
  return data.cartCreate.cart;
};

// Add an item to an existing cart
const addToCart = async (cartId, variantGid, quantity) => {
  const response = await fetch(`https://${SHOP_DOMAIN}/api/2024-01/graphql.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': STOREFRONT_TOKEN,
    },
    body: JSON.stringify({
      query: `
        mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
          cartLinesAdd(cartId: $cartId, lines: $lines) {
            cart { id totalQuantity cost { totalAmount { amount currencyCode } } }
          }
        }
      `,
      variables: { cartId, lines: [{ merchandiseId: variantGid, quantity }] },
    }),
  });
  const { data } = await response.json();
  return data.cartLinesAdd.cart;
};
Store the
cartId
in a cookie or localStorage. On login, use
cartBuyerIdentityUpdate
to associate the cart with the customer's account — Shopify handles the merge automatically.
BigCommerce Storefront API (for BigCommerce-backed headless stores):
Use the BigCommerce Storefront Cart API (
/api/storefront/carts
) which handles cart creation, item management, and customer association automatically.
对于无头店铺,建议使用平台的Storefront API,而非从头构建购物车存储:
Shopify Storefront API(推荐用于基于Shopify的无头店铺):
javascript
// Create a cart
const createCart = async () => {
  const response = await fetch(`https://${SHOP_DOMAIN}/api/2024-01/graphql.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': STOREFRONT_TOKEN,
    },
    body: JSON.stringify({
      query: `
        mutation cartCreate($input: CartInput!) {
          cartCreate(input: $input) {
            cart { id checkoutUrl }
            userErrors { field message }
          }
        }
      `,
      variables: { input: { lines: [{ merchandiseId: variantGid, quantity: 1 }] } },
    }),
  });
  const { data } = await response.json();
  return data.cartCreate.cart;
};

// Add an item to an existing cart
const addToCart = async (cartId, variantGid, quantity) => {
  const response = await fetch(`https://${SHOP_DOMAIN}/api/2024-01/graphql.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': STOREFRONT_TOKEN,
    },
    body: JSON.stringify({
      query: `
        mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
          cartLinesAdd(cartId: $cartId, lines: $lines) {
            cart { id totalQuantity cost { totalAmount { amount currencyCode } } }
          }
        }
      `,
      variables: { cartId, lines: [{ merchandiseId: variantGid, quantity }] },
    }),
  });
  const { data } = await response.json();
  return data.cartLinesAdd.cart;
};
cartId
存储在cookie或localStorage中。登录时,使用
cartBuyerIdentityUpdate
将购物车与客户账户关联——Shopify会自动处理合并操作。
BigCommerce Storefront API(用于基于BigCommerce的无头店铺):
使用BigCommerce Storefront Cart API(
/api/storefront/carts
),它会自动处理购物车创建、商品管理和客户关联。

Step 3: Implement key cart UX behaviors

步骤3:实现关键购物车UX行为

Regardless of platform, these are the cart behaviors that most affect conversion:
  1. Show mini-cart on add-to-cart — most Shopify, WooCommerce, and BigCommerce themes support a slide-out cart drawer that opens when an item is added; enable this instead of redirecting to the cart page
  2. Show stock levels in the cart — display "Only 2 left" warnings on items with low inventory; both Shopify and WooCommerce support this via metafields and cart item data
  3. Guest cart persistence — ensure guest carts survive for at least 30 days so returning visitors find their items; Shopify does this by default; WooCommerce requires the session duration setting to be configured
  4. Free shipping progress bar — show a "You're $X away from free shipping" bar in the cart; install Free Shipping Bar (Shopify) or WooCommerce Free Shipping Bar plugin
无论使用哪个平台,以下购物车行为对转化率影响最大:
  1. 加入购物车时显示迷你购物车——大多数Shopify、WooCommerce和BigCommerce主题支持滑出式购物车抽屉,添加商品时自动打开;建议启用此功能,而非重定向到购物车页面
  2. 在购物车中显示库存水平——对库存不足的商品显示"仅剩2件"警告;Shopify和WooCommerce均可通过元字段和购物车商品数据实现此功能
  3. 访客购物车持久化——确保访客购物车至少保留30天,以便回访用户能找到之前的商品;Shopify默认支持此功能;WooCommerce需要配置会话时长设置
  4. 免运费进度条——在购物车中显示"还差X元即可享受免运费"进度条;安装Free Shipping Bar(Shopify)或WooCommerce Free Shipping Bar插件

Best Practices

最佳实践

  • Use your platform's native cart — Shopify, WooCommerce, and BigCommerce carts are battle-tested and handle edge cases (stock validation, price changes, tax calculation) correctly
  • Enable persistent cart for logged-in customers — all three platforms support server-side cart storage for accounts; enable it
  • Validate stock at checkout, not only on add-to-cart — items may sell out while in a guest's cart; re-validate at checkout time (platforms do this automatically)
  • Show the cart total prominently — including item count and subtotal; reduces anxiety about total spend
  • For headless: use the platform's Storefront API — Shopify and BigCommerce Storefront APIs are production-hardened and handle cart merging, stock checks, and checkout initiation correctly
  • 使用平台原生购物车——Shopify、WooCommerce和BigCommerce的购物车均经过实战检验,能正确处理边缘情况(库存验证、价格变更、税费计算)
  • 为登录客户启用持久化购物车——这三个平台均支持为账户用户提供服务器端购物车存储;请启用此功能
  • 在结账时验证库存,而非仅在加入购物车时——访客购物车中的商品可能在结账前售罄;结账时重新验证库存(平台会自动处理此操作)
  • 突出显示购物车总额——包括商品数量和小计;减少用户对总花费的焦虑
  • 对于无头店铺:使用平台的Storefront API——Shopify和BigCommerce的Storefront API经过生产环境验证,能正确处理购物车合并、库存检查和结账启动

Common Pitfalls

常见问题与解决方案

ProblemSolution
Cart disappears when user logs in (WooCommerce)Ensure Persistent cart is enabled in WooCommerce → Settings → Accounts & Privacy
Guest cart is empty after browser restartCheck cookie expiry settings; Shopify uses 30-day cart tokens by default; WooCommerce session duration is configurable
Same item added twice instead of incrementing quantityThe platform's native cart handles this; if using headless with Storefront API, use
cartLinesUpdate
to increment quantity on existing lines
Cart shows outdated prices after a price changeShopify and WooCommerce automatically use current prices at checkout, not add-to-cart prices; a "price changed" notice appears automatically
Custom add-to-cart code bypasses stock checksAlways use the platform's official add-to-cart mechanisms; custom code that writes directly to cart storage skips inventory validation
问题解决方案
登录后购物车消失(WooCommerce)确保在WooCommerce → 设置 → 账户与隐私中启用 持久化购物车
浏览器重启后访客购物车为空检查cookie过期设置;Shopify默认使用30天有效期的cart token;WooCommerce可配置会话时长
同一商品被添加两次而非增加数量平台原生购物车会处理此问题;如果使用无头架构并调用Storefront API,请使用
cartLinesUpdate
增加现有商品的数量
价格变更后购物车显示过时价格Shopify和WooCommerce会在结账时自动使用当前价格,而非加入购物车时的价格;系统会自动显示"价格已变更"提示
自定义加入购物车代码绕过库存检查始终使用平台官方的加入购物车机制;直接写入购物车存储的自定义代码会跳过库存验证

Related Skills

相关技能

  • @checkout-flow-optimization
  • @guest-checkout
  • @inventory-tracking
  • @stripe-integration
  • @checkout-flow-optimization
  • @guest-checkout
  • @inventory-tracking
  • @stripe-integration