Shopify Ruby脚本错误排查:折扣码要求未满足(空购物车)
解决Shopify脚本「discount code requirements not met (empty cart)」错误
我开发了一款Shopify Ruby脚本,用于阻止促销码应用到带sale标签的商品上,功能符合预期,但总是出现第一行错误提示「discount code requirements not met (empty cart)」,求解决办法。
脚本代码如下:
# ================================ Customizable Settings ================================ # ================================================================ # Define the tag for products where discounts are not allowed. # ================================================================ SALE_TAGS = ['sale', 'Sale'] # Tags used to identify sale products REJECTION_MESSAGE = "Discount codes can't be used with Sale products" # ================================ Script Code (do not edit) ================================ # ================================================================ # ProductSelector # Finds matching products by the entered criteria. # ================================================================ class ProductSelector def initialize(tags) @tags = tags.map(&:downcase) end def match?(line_item) product_tags = line_item.variant.product.tags.map(&:downcase) (@tags & product_tags).any? end end # ================================================================ # DisableDiscountCodesForProductsCampaign # If any matching items are in the cart, the discount code is rejected. # ================================================================ class DisableDiscountCodesForProductsCampaign def initialize(tags, message) @product_selector = ProductSelector.new(tags) @rejection_message = message end def run(cart) return if cart.discount_code.nil? if cart.line_items.any? { |line_item| @product_selector.match?(line_item) } cart.discount_code.reject(message: @rejection_message) end end end # ================================================================ # Campaign Execution # ================================================================ campaign = DisableDiscountCodesForProductsCampaign.new(SALE_TAGS, REJECTION_MESSAGE) campaign.run(Input.cart) Output.cart = Input.cart
错误提示截图:
问题原因
这个错误是因为脚本在购物车为空时仍会触发折扣码校验逻辑,Shopify系统默认会抛出「empty cart」的错误提示,而你的脚本没有处理购物车为空的场景。
修复方案
修改DisableDiscountCodesForProductsCampaign类中的run方法,在开头新增购物车为空的判断,直接返回即可:
def run(cart) # 新增:购物车为空时直接返回,避免触发系统默认错误 return if cart.line_items.empty? return if cart.discount_code.nil? if cart.line_items.any? { |line_item| @product_selector.match?(line_item) } cart.discount_code.reject(message: @rejection_message) end end
额外优化建议
- 你的
SALE_TAGS里同时写了sale和Sale,但代码中已经通过map(&:downcase)统一转为小写,所以可以简化成SALE_TAGS = ['sale'],减少冗余。 - 测试时覆盖三类场景:空购物车使用折扣码、购物车仅含促销商品使用折扣码、购物车无促销商品使用折扣码,确保所有场景逻辑正常。
内容的提问来源于stack exchange,提问作者WadeB
相关产品推荐
相关产品推荐

