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

如何通过GraphQL获取Shopify销售渠道ID并创建关联商品

使用Python + Shopify GraphQL API 获取销售渠道ID并创建关联商品

一、获取销售渠道ID

你尝试的两个查询中,salesChannels 是有效的GraphQL查询字段(channels字段已被弃用)。需确保你的Access Token拥有read_sales_channels权限。

正确的GraphQL查询语句

{
  salesChannels(first: 20) {
    edges {
      node {
        id
        name
        type
      }
    }
  }
}

添加first:20可控制返回的渠道数量,最大支持100个。

Python代码获取销售渠道ID

import requests
import json

shop_url = "你的店铺域名(如https://xxx.myshopify.com)"
access_token = "你的Shopify访问令牌"
graphql_url = f"{shop_url}/admin/api/2023-10/graphql.json"

# 查询销售渠道的GraphQL语句
query = """
{
  salesChannels(first: 20) {
    edges {
      node {
        id
        name
        type
      }
    }
  }
}
"""

headers = {
    "Content-Type": "application/json",
    "X-Shopify-Access-Token": access_token,
}

response = requests.post(graphql_url, json={"query": query}, headers=headers)

if response.status_code == 200:
    result = response.json()
    print("获取到的销售渠道:")
    print(json.dumps(result, indent=2))
else:
    print(f"请求失败,状态码:{response.status_code}")
    print(response.text)

执行后会返回所有销售渠道的ID、名称和类型,可从中提取需要关联的渠道ID。

二、创建关联销售渠道的商品

使用productCreate mutation,并在参数中指定salesChannelIds字段,即可创建关联指定销售渠道的商品。

完整Python代码示例

import requests
import json

shop_url = "你的店铺域名(如https://xxx.myshopify.com)"
access_token = "你的Shopify访问令牌"
graphql_url = f"{shop_url}/admin/api/2023-10/graphql.json"

# 创建商品并关联销售渠道的mutation
mutation = """
mutation ProductCreate($input: ProductInput!) {
  productCreate(input: $input) {
    product {
      id
      title
      handle
    }
    userErrors {
      field
      message
    }
  }
}
"""

# 替换为你要关联的销售渠道ID,可传入多个
target_sales_channel_ids = ["gid://shopify/SalesChannel/123456789"]

# 商品参数
variables = {
  "input": {
    "title": "测试关联渠道商品",
    "descriptionHtml": "<p>这是一个关联指定销售渠道的测试商品</p>",
    "vendor": "测试商家",
    "productType": "测试类型",
    "salesChannelIds": target_sales_channel_ids
  }
}

headers = {
    "Content-Type": "application/json",
    "X-Shopify-Access-Token": access_token,
}

response = requests.post(
    graphql_url,
    json={"query": mutation, "variables": variables},
    headers=headers
)

if response.status_code == 200:
    result = response.json()
    if result.get("data", {}).get("productCreate", {}).get("userErrors"):
        print("创建商品时出现错误:")
        print(json.dumps(result["data"]["productCreate"]["userErrors"], indent=2))
    else:
        print("商品创建成功:")
        print(json.dumps(result["data"]["productCreate"]["product"], indent=2))
else:
    print(f"请求失败,状态码:{response.status_code}")
    print(response.text)

注意事项

  • 确保Access Token拥有write_products和write_sales_channels权限
  • salesChannelIds接受数组格式,可同时关联多个销售渠道
  • 若要给已存在的商品关联销售渠道,可使用productUpdate mutation,参数结构类似

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 17:35:13