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

Shopify自定义应用扩展:如何程序化添加商品至购物车?

Shopify托管店铺自定义应用:商品添加至购物车实现方案

核心结论先明确

  1. 不要用Admin API:Admin API是给商家后台操作使用的,需要高权限,不能在顾客端(商品页面)调用,会有安全风险。
  2. Storefront API完全适用Shopify托管店铺:你的理解有误,Storefront API就是为Shopify托管店铺的顾客端场景设计的,包括主题、自定义应用的前端交互。
  3. 购物车存储逻辑:未登录用户的购物车确实存储在浏览器的cart Cookie中;登录用户的购物车会同步到Shopify服务器,与用户账号绑定。

两种实现商品添加至购物车的方案

方案一:使用Shopify AJAX API(最简单高效)

Shopify主题自带轻量AJAX接口,无需额外配置API密钥,直接在商品页面的扩展中调用即可:

// 绑定按钮点击事件,替换成你的变体ID和按钮选择器
document.querySelector('#add-attachment-btn').addEventListener('click', async () => {
  const variantId = 123456789; // 替换为你要添加的商品变体ID
  const quantity = 1;

  try {
    const res = await fetch('/cart/add.js', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({ id: variantId, quantity })
    });

    const data = await res.json();
    if (res.ok) {
      console.log('附加商品已加入购物车', data);
      // 可选:调用/cart.js获取最新购物车数据,更新页面UI
      const cartRes = await fetch('/cart.js');
      const cartData = await cartRes.json();
      // 这里可以更新购物车图标数量等
    } else {
      console.error('添加失败:', data.message);
    }
  } catch (err) {
    console.error('请求错误:', err);
  }
});

方案二:使用Storefront API(GraphQL)

如果需要更复杂的操作(比如同时添加多个商品、获取更多购物车详情),可以用Storefront API的GraphQL mutation:

// 注意:需要先获取店铺的Storefront API公钥,在Shopify后台设置中生成
const storefrontAccessToken = 'your-storefront-access-token';
const shopDomain = 'your-shop.myshopify.com';

async function addToCartWithGraphQL(variantId, quantity = 1) {
  const query = `
    mutation addToCart($cartId: ID!, $lines: [CartLineInput!]!) {
      cartLinesAdd(cartId: $cartId, lines: $lines) {
        cart {
          id
          totalQuantity
        }
      }
    }
  `;

  // 先获取当前用户的购物车ID(从Cookie或创建新购物车)
  let cartId = localStorage.getItem('shopifyCartId');
  if (!cartId) {
    // 如果没有购物车,创建一个新的
    const createCartQuery = `mutation createCart { cartCreate { cart { id } } }`;
    const createRes = await fetch(`https://${shopDomain}/api/2024-07/graphql.json`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Shopify-Storefront-Access-Token': storefrontAccessToken
      },
      body: JSON.stringify({ query: createCartQuery })
    });
    const createData = await createRes.json();
    cartId = createData.data.cartCreate.cart.id;
    localStorage.setItem('shopifyCartId', cartId);
  }

  // 添加商品到购物车
  const variables = {
    cartId,
    lines: [{ merchandiseId: `gid://shopify/ProductVariant/${variantId}`, quantity }]
  };

  const res = await fetch(`https://${shopDomain}/api/2024-07/graphql.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': storefrontAccessToken
    },
    body: JSON.stringify({ query, variables })
  });

  const data = await res.json();
  if (data.errors) {
    console.error('GraphQL错误:', data.errors);
  } else {
    console.log('商品添加成功', data.data.cartLinesAdd.cart);
  }
}

注意事项

  • 无论用哪种方案,都需要获取商品变体ID(不是产品ID),因为购物车只能添加具体的变体。
  • 自定义应用的商品页扩展(App Block)运行在Shopify的页面环境中,直接调用/cart/add.js不会有跨域问题。
  • 如果你需要在添加后更新购物车UI,可以调用/cart.js获取完整的购物车数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:17:36