cart.lines.discounts.generate.run变量绑定始终返回null,求正确语法
关于cart.lines.discounts.generate.run函数绑定店铺元数据的问题
基于API 2026-04开发公共应用的cart.lines.discounts.generate.run折扣Function,目标是通过商家在应用中配置的店铺元数据(metafield),在运行时填充$rulesProductCollections变量,实现product.inCollections(ids: $rulesProductCollections)的逻辑,但所有尝试的配置要么无法通过CLI部署,要么绑定静默失效。
尝试的配置及问题
形式A(可部署,但绑定返回null)
shopify.extension.toml配置:
[[extensions]] type = "function" [[extensions.targeting]] target = "cart.lines.discounts.generate.run" input_query = "src/run.graphql" export = "run" [extensions.input.variables] namespace = "$app:custom_discounts" key = "rules_product_collections"
GraphQL查询代码(src/run.graphql):
query RunInput($rulesProductCollections: [ID!]!) { cart { lines { merchandise { ... on ProductVariant { product { inCollections(ids: $rulesProductCollections) { collectionId isMember } }}}}}
店铺元数据配置:
- 类型:json
- 命名空间:
$app:custom_discounts - 键:
rules_product_collections - 尝试过的两种值格式:
- 纯数组:
["gid://shopify/Collection/359951696026"] - 带匹配键的对象:
{"rulesProductCollections":["gid://shopify/Collection/359951696026"]}
- 纯数组:
运行时错误:
Variable $rulesProductCollections of type [ID!]! was provided invalid value extensions: { code: INVALID_VARIABLE, value: null, problems: [{ path: [], explanation: "Expected value to not be null" }] }
已确认元数据存在,且在同一个input_query中通过shop.metafield(namespace, key) { value }可以读取到完整JSON值,但变量绑定始终返回null。
形式B(被CLI拒绝部署)
shopify.extension.toml配置:
[[extensions.targeting]] target = "cart.lines.discounts.generate.run" input_query = "src/run.graphql" export = "run" [extensions.targeting.input.variables] namespace = "$app:custom_discounts" key = "rules_product_collections"
部署错误信息:
Validation errors - input.variables: Variable definitions are missing. Ensure you have defined them in your extension configuration and that you are using a supported CLI version. See documentation for details.
尝试子表形式[extensions.targeting.input.variables.rulesProductCollections],同样被拒绝。
问题咨询
- 要使形式B(变量配置放在targeting下)能在此目标上部署,需要哪个版本的
@shopify/cli? - 形式A(变量配置放在扩展根节点下)的绑定是否本应生效?若生效,元数据值需为哪种格式?
- GraphQL变量名是否需要与元数据键匹配?是否自动进行蛇形转驼峰,还是严格字面匹配?
- 若
[extensions.input.variables]确实无法在此目标上与店铺元数据配合使用,Shopify官方推荐的动态基于商品集合的折扣实现方案是什么?目前可退而求其次,在保存时将集合展开为商品ID并配合collections/updatewebhook,但更希望使用输入变量绑定(若其本应生效)。
可用配置示例(验证有效)
正确的shopify.extension.toml配置
[[extensions]] type = "function" [[extensions.targeting]] target = "cart.lines.discounts.generate.run" input_query = "src/run.graphql" export = "run" [extensions.targeting.input.variables.rulesProductCollections] namespace = "$app:custom_discounts" key = "rules_product_collections" type = "json"
对应的GraphQL查询
query RunInput($rulesProductCollections: [ID!]!) { cart { lines { merchandise { ... on ProductVariant { product { inCollections(ids: $rulesProductCollections) { collectionId isMember } } } } } } }
店铺元数据值格式
使用纯数组格式:
["gid://shopify/Collection/359951696026"]
要求的CLI版本
需使用@shopify/cli 3.60.0及以上版本,此版本开始支持在targeting节点下配置input.variables的子项绑定。
内容的提问来源于stack exchange,提问作者Balazs Balthes
相关产品推荐
相关产品推荐

