Shopify
通过 curl 使用 Shopify Admin 和 Storefront GraphQL API。涵盖商品、订单、客户、库存、元字段。
技能元数据
| 来源 | 可选 — 使用 hermes skills install official/productivity/shopify 安装 |
| 路径 | optional-skills/productivity/shopify |
| 版本 | 1.0.0 |
| 作者 | community |
| 许可证 | MIT |
| 平台 | linux, macos, windows |
| 标签 | Shopify, E-commerce, Commerce, API, GraphQL |
| 相关技能 | airtable, xurl |
参考:完整 SKILL.md
以下是 Hermes 在触发此技能时加载的完整技能定义。这是技能激活时代理所看到的指令。
Shopify — Admin & Storefront GraphQL APIs
直接通过 curl 操作 Shopify 店铺:列出商品、管理库存、拉取订单、更新客户、读取元字段。无需 SDK,无需应用框架——只需 GraphQL 端点和自定义应用访问令牌。
REST Admin API 自 2024-04 起已成为遗留版本,仅接收安全修复。所有管理工作请使用 GraphQL Admin。Storefront GraphQL 用于面向客户的只读查询(商品、集合、购物车)。
前提条件
- 在 Shopify 后台:Settings → Apps and sales channels → Develop apps → Create an app。
- 点击 Configure Admin API scopes,选择所需权限(见下方示例),保存。
- Install app → Admin API 访问令牌仅显示一次。请立即复制——Shopify 永远不会再次显示它。令牌以
shpat_开头。 - 保存至
~/.hermes/.env:SHOPIFY_ACCESS_TOKEN=shpat_xxxxxxxxxxxxxxxxxxxx
SHOPIFY_STORE_DOMAIN=my-store.myshopify.com
SHOPIFY_API_VERSION=2026-01
注意: 截至 2026 年 1 月 1 日,在 Shopify 后台创建的新“遗留自定义应用”已不再可用。新设置应使用 Dev Dashboard (
shopify.dev/docs/apps/build/dev-dashboard)。现有在后台创建的应用仍可正常工作。如果用户的店铺没有现有的自定义应用且日期在 2026-01-01 之后,请引导他们使用 Dev Dashboard 而非后台流程。
常见任务所需的权限范围:
- 商品 / 集合:
read_products,write_products - 库存:
read_inventory,write_inventory,read_locations - 订单:
read_orders,write_orders(若无read_all_orders,仅限最近 30 个) - 客户:
read_customers,write_customers - 草稿订单:
read_draft_orders,write_draft_orders - 发货:
read_fulfillments,write_fulfillments - 元字段 / 元对象:由匹配的资源权限范围覆盖
API 基础
- 端点:
https://$SHOPIFY_STORE_DOMAIN/admin/api/$SHOPIFY_API_VERSION/graphql.json - 认证头:
X-Shopify-Access-Token: $SHOPIFY_ACCESS_TOKEN(非Authorization: Bearer) - 方法: 始终为
POST,始终使用Content-Type: application/json,请求体为{"query": "...", "variables": {...}} - HTTP 200 不代表成功。 GraphQL 会在顶层
errors数组和每字段的userErrors中返回错误。务必检查两者。 - ID 为 GID 字符串:
gid://shopify/Product/10079467700516,gid://shopify/Variant/...,gid://shopify/Order/...。原样传递这些 ID——不要去除前缀。 - 速率限制: 通过查询成本计算(漏桶算法)。每个响应包含
extensions.cost,其中有requestedQueryCost,actualQueryCost,throttleStatus.{currentlyAvailable, maximumAvailable, restoreRate}。当currentlyAvailable低于下一次查询的成本时,请退避。标准店铺 = 100 点桶容量,50/秒恢复速率;Plus 店铺 = 1000/100。
基础 curl 模式(可复用):
shop_gql() {
local query="$1"
local variables="${2:-{}}"
curl -sS -X POST \
"https://${SHOPIFY_STORE_DOMAIN}/admin/api/${SHOPIFY_API_VERSION:-2026-01}/graphql.json" \
-H "Content-Type: application/json" \
-H "X-Shopify-Access-Token: ${SHOPIFY_ACCESS_TOKEN}" \
--data "$(jq -nc --arg q "$query" --argjson v "$variables" '{query: $q, variables: $v}')"
}
通过管道传递给 jq 以获得可读输出。-sS 保持错误可见但隐藏进度条。
发现
店铺信息 + 当前 API 版本
shop_gql '{ shop { name myshopifyDomain primaryDomain { url } currencyCode plan { displayName } } }' | jq
列出所有支持的 API 版本
shop_gql '{ publicApiVersions { handle supported } }' | jq '.data.publicApiVersions[] | select(.supported)'
商品
搜索商品(前 20 个匹配项)
shop_gql '
query($q: String!) {
products(first: 20, query: $q) {
edges { node { id title handle status totalInventory variants(first: 5) { edges { node { id sku price inventoryQuantity } } } } }
pageInfo { hasNextPage endCursor }
}
}' '{"q":"hoodie status:active"}' | jq
查询语法支持 title:、sku:、vendor:、product_type:、status:active、tag:、created_at:>2025-01-01。完整语法:https://shopify.dev/docs/api/usage/search-syntax
分页获取商品(游标)
shop_gql '
query($cursor: String) {
products(first: 100, after: $cursor) {
edges { cursor node { id handle } }
pageInfo { hasNextPage endCursor }
}
}' '{"cursor":null}'
# subsequent calls: pass the previous endCursor
获取包含变体和元字段的单个商品
shop_gql '
query($id: ID!) {
product(id: $id) {
id title handle descriptionHtml tags status
variants(first: 20) { edges { node { id sku price compareAtPrice inventoryQuantity selectedOptions { name value } } } }
metafields(first: 20) { edges { node { namespace key type value } } }
}
}' '{"id":"gid://shopify/Product/10079467700516"}' | jq
创建含一个变体的商品
shop_gql '
mutation($input: ProductCreateInput!) {
productCreate(product: $input) {
product { id handle }
userErrors { field message }
}
}' '{"input":{"title":"Test Hoodie","status":"DRAFT","vendor":"Hermes","productType":"Apparel","tags":["test"]}}'
在最近版本中,变体现在拥有自己的突变操作:
# Add variants after creating the product
shop_gql '
mutation($productId: ID!, $variants: [ProductVariantsBulkInput!]!) {
productVariantsBulkCreate(productId: $productId, variants: $variants) {
productVariants { id sku price }
userErrors { field message }
}
}' '{"productId":"gid://shopify/Product/...","variants":[{"optionValues":[{"optionName":"Size","name":"M"}],"price":"49.00","inventoryItem":{"sku":"HD-M","tracked":true}}]}'
更新价格 / SKU
shop_gql '
mutation($productId: ID!, $variants: [ProductVariantsBulkInput!]!) {
productVariantsBulkUpdate(productId: $productId, variants: $variants) {
productVariants { id sku price }
userErrors { field message }
}
}' '{"productId":"gid://shopify/Product/...","variants":[{"id":"gid://shopify/ProductVariant/...","price":"55.00"}]}'
订单
列出最近订单(默认最近 30 个,若无 read_all_orders)
shop_gql '
{
orders(first: 20, reverse: true, query: "financial_status:paid") {
edges { node {
id name createdAt displayFinancialStatus displayFulfillmentStatus
totalPriceSet { shopMoney { amount currencyCode } }
customer { id displayName email }
lineItems(first: 10) { edges { node { title quantity sku } } }
} }
}
}' | jq
有用的订单查询过滤器:financial_status:paid|pending|refunded, fulfillment_status:unfulfilled|fulfilled, created_at:>2025-01-01, tag:gift, email:foo@example.com。
获取包含收货地址的单个订单
shop_gql '
query($id: ID!) {
order(id: $id) {
id name email
shippingAddress { name address1 address2 city province country zip phone }
lineItems(first: 50) { edges { node { title quantity variant { sku } originalUnitPriceSet { shopMoney { amount currencyCode } } } } }
transactions { id kind status amountSet { shopMoney { amount currencyCode } } }
}
}' '{"id":"gid://shopify/Order/...."}' | jq
客户
# Search
shop_gql '
{
customers(first: 10, query: "email:*@example.com") {
edges { node { id email displayName numberOfOrders amountSpent { amount currencyCode } } }
}
}'
# Create
shop_gql '
mutation($input: CustomerInput!) {
customerCreate(input: $input) {
customer { id email }
userErrors { field message }
}
}' '{"input":{"email":"test@example.com","firstName":"Test","lastName":"User","tags":["api-created"]}}'
库存
库存存在于与变体关联的 库存项目 (inventory items) 上,数量按 地点 (location) 跟踪。
# Get inventory for a variant across all locations
shop_gql '
query($id: ID!) {
productVariant(id: $id) {
id sku
inventoryItem {
id tracked
inventoryLevels(first: 10) {
edges { node { location { id name } quantities(names: ["available","on_hand","committed"]) { name quantity } } }
}
}
}
}' '{"id":"gid://shopify/ProductVariant/..."}'
调整库存(增量)— 使用 inventoryAdjustQuantities:
shop_gql '
mutation($input: InventoryAdjustQuantitiesInput!) {
inventoryAdjustQuantities(input: $input) {
inventoryAdjustmentGroup { reason changes { name delta } }
userErrors { field message }
}
}' '{
"input": {
"reason": "correction",
"name": "available",
"changes": [{"delta": 5, "inventoryItemId": "gid://shopify/InventoryItem/...", "locationId": "gid://shopify/Location/..."}]
}
}'
设置绝对库存(非增量)— inventorySetQuantities:
shop_gql '
mutation($input: InventorySetQuantitiesInput!) {
inventorySetQuantities(input: $input) {
inventoryAdjustmentGroup { id }
userErrors { field message }
}
}' '{"input":{"reason":"correction","name":"available","ignoreCompareQuantity":true,"quantities":[{"inventoryItemId":"gid://shopify/InventoryItem/...","locationId":"gid://shopify/Location/...","quantity":100}]}}'
元字段与元对象
元字段将自定义数据附加到资源(商品、客户、订单、店铺)。
# Read
shop_gql '
query($id: ID!) {
product(id: $id) {
metafields(first: 10, namespace: "custom") {
edges { node { key type value } }
}
}
}' '{"id":"gid://shopify/Product/..."}'
# Write (works for any owner type)
shop_gql '
mutation($metafields: [MetafieldsSetInput!]!) {
metafieldsSet(metafields: $metafields) {
metafields { id key namespace }
userErrors { field message code }
}
}' '{"metafields":[{"ownerId":"gid://shopify/Product/...","namespace":"custom","key":"care_instructions","type":"multi_line_text_field","value":"Wash cold. Tumble dry low."}]}'
Storefront API(公开只读)
不同的端点,不同的令牌,用于面向客户的应用程序或 Hydrogen 风格的无头架构。请求头有所不同:
- 端点:
https://$SHOPIFY_STORE_DOMAIN/api/$SHOPIFY_API_VERSION/graphql.json - 认证头(公开):
X-Shopify-Storefront-Access-Token: <public token>— 可嵌入浏览器 - 认证头(私有):
Shopify-Storefront-Private-Token: <private token>— 仅限服务器端使用
curl -sS -X POST \
"https://${SHOPIFY_STORE_DOMAIN}/api/${SHOPIFY_API_VERSION:-2026-01}/graphql.json" \
-H "Content-Type: application/json" \
-H "X-Shopify-Storefront-Access-Token: ${SHOPIFY_STOREFRONT_TOKEN}" \
-d '{"query":"{ shop { name } products(first: 5) { edges { node { id title handle } } } }"}' | jq
批量操作
适用于超过速率限制允许的大规模数据导出(如完整商品目录、全年所有订单):
# 1. Start bulk query
shop_gql '
mutation {
bulkOperationRunQuery(query: """
{ products { edges { node { id title handle variants { edges { node { sku price } } } } } } }
""") {
bulkOperation { id status }
userErrors { field message }
}
}'
# 2. Poll status
shop_gql '{ currentBulkOperation { id status errorCode objectCount fileSize url partialDataUrl } }'
# 3. When status=COMPLETED, download the JSONL file
curl -sS "$URL" > products.jsonl
每行 JSONL 是一个节点,嵌套的连接关系作为单独的行发出,并带有 __parentId。如有需要,可在客户端重新组装。
Webhooks
订阅事件以避免轮询:
shop_gql '
mutation($topic: WebhookSubscriptionTopic!, $sub: WebhookSubscriptionInput!) {
webhookSubscriptionCreate(topic: $topic, webhookSubscription: $sub) {
webhookSubscription { id topic endpoint { __typename ... on WebhookHttpEndpoint { callbackUrl } } }
userErrors { field message }
}
}' '{"topic":"ORDERS_CREATE","sub":{"callbackUrl":"https://example.com/webhook","format":"JSON"}}'
使用应用的客户端密钥(而非访问令牌)验证传入 webhook 的 HMAC:
echo -n "$REQUEST_BODY" | openssl dgst -sha256 -hmac "$APP_SECRET" -binary | base64
# Compare to X-Shopify-Hmac-Sha256 header
常见陷阱
- REST 端点仍然存在但已冻结。 不要针对
/admin/api/.../products.json编写新的集成代码。请使用 GraphQL。 - 令牌格式检查。 Admin 令牌以
shpat_开头。Storefront 公开令牌以shpua_开头。如果你持有其中一种令牌却使用了错误的请求头,每个请求都会返回 401,且没有有用的错误正文。 - 有效令牌返回 403 = 缺少权限范围。 Shopify 返回
{"errors":[{"message":"Access denied for ..."}]}。请在应用中重新配置 Admin API 权限范围,然后重新安装以生成新令牌。 userErrors为空 ≠ 成功。 还需检查data.<mutation>.<resource>是否非空。某些失败情况两者均不会填充 — 请检查整个响应。- GID 与数字 ID。 旧版 REST 提供数字 ID;GraphQL 需要完整的 GID 字符串。转换方法:
gid://shopify/Product/<numeric>。 - 速率限制意外。 单个
products(first: 250)若包含深层嵌套,可能消耗 1000+ 点数,并在标准计划店铺上立即触发限流。应从窄范围开始,读取extensions.cost,再进行调整。 - 分页排序。
products(first: N, reverse: true)按id DESC排序,而非created_at。若需“最新优先”,请使用sortKey: CREATED_AT, reverse: true。 read_all_orders用于历史数据。 若无此权限,orders(...)会静默限制在 60 天窗口内。你不会收到错误,只是结果少于预期。对于拥有大量订单的 Shopify Plus 商家,请通过应用的受保护数据设置请求此权限范围。- 货币为字符串。 金额返回形式为
"49.00"而非49.0。若关心零填充,请勿盲目使用jq tonumber。 - 多币种 Money 字段 同时包含
shopMoney(店铺货币)和presentmentMoney(客户货币)。请始终一致地选择其一。
安全提示
Shopify 中的突变操作是真实生效的 — 它们会创建商品、处理退款、取消订单、发货履约。在执行 productDelete、orderCancel、refundCreate 或任何批量突变之前:明确说明变更内容、涉及哪家店铺,并与用户确认。除非用户拥有独立的开发店铺,否则不存在生产数据的暂存克隆环境。