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

如何通过Shopify Buy SDK获取指定商品的当前库存?

解决Shopify Buy SDK获取指定商品库存的问题

核心问题梳理

  • 用SDK默认的product.fetch()方法拿不到totalInventory字段,哪怕已经开启unauthenticated_read_product_inventory权限也没用
  • 用GraphQL查商品列表时,普通SDK版本不支持totalInventory,切换到未优化版本(index.unoptimized.umd)可以正常查询,但查单个商品时误用addConnection导致报错——因为product是单个对象,不是带分页的连接类型,根本没有pageInfo字段

可行解决方案

方案1:用未优化SDK版本,通过GraphQL直接查单个商品

单个商品不能用addConnection,得用addField指定查询单个product对象,另外注意Shopify的GraphQL ID必须是gid://shopify/Product/xxx这种Base64格式的完整ID。

代码示例:

var Client = require('shopify-buy/index.unoptimized.umd');
const shopify = Client.buildClient({
    domain: REDACTED_SHOPIFY_DOMAIN,
    storefrontAccessToken: REDACTED_SHOPIFY_TOKEN
});

async function getSingleProductInventory(productId) {
    // 这里的productId必须是gid://shopify/Product/xxx格式
    const productQuery = shopify.graphQLClient.query((root) => {
        root.addField('product', { args: { id: productId } }, (product) => {
            product.add('title');
            product.add('totalInventory');
            // 也可以顺便查每个变体的单独库存
            product.addConnection('variants', { args: { first: 10 } }, (variant) => {
                variant.add('title');
                variant.add('inventoryQuantity');
            });
        });
    });

    try {
        const { data } = await shopify.graphQLClient.send(productQuery);
        console.log('商品及库存信息:', data.product);
        return data.product;
    } catch (error) {
        console.error('查询失败:', error);
    }
}

// 调用示例
getSingleProductInventory('gid://shopify/Product/你的商品ID');

方案2:通过变体库存求和得到总库存

如果不想切换SDK版本,也可以用默认product.fetch()拿到的variants字段,遍历所有变体把inventoryQuantity加起来得到总库存:

代码示例:

var Client = require('shopify-buy');
const shopify = Client.buildClient({
    domain: REDACTED_SHOPIFY_DOMAIN,
    storefrontAccessToken: REDACTED_SHOPIFY_TOKEN
});

async function getProductTotalInventory(productId) {
    let product = await shopify.product.fetch(productId);
    // 遍历变体累加库存
    const totalInventory = product.variants.reduce((sum, variant) => {
        return sum + variant.inventoryQuantity;
    }, 0);
    console.log('总库存:', totalInventory);
    return totalInventory;
}

// 调用示例
getProductTotalInventory('你的商品ID');

关键注意事项

  • totalInventory字段依赖unauthenticated_read_product_inventory权限,必须确保已经在Shopify应用设置里开启
  • 单个商品查询只能用addField,addConnection是给列表类型(比如products)用的
  • Shopify GraphQL查询用的ID必须是gid://shopify/Product/xxx格式,不能直接用数字ID

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:52:57