Trigger a script using a discount code

Highlighted
Shopify Expert
1 0 0

Hello, 

I'm trying to find a way to only run a script when a specific discount coded is added. 

My code applies the discount to the specific products it should be but I need a way to activate it so we can track through a marketing campaign. 

discounted_product = 1234567890
discounted_product2 = 0987654321
products_needed = [1234567890, 0987654321]
products_seen = []

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  products_seen << product.id if products_needed.include?(product.id)
end

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  next unless product.id == discounted_product
  line_item.change_line_price(line_item.line_price * 0.80, message: "20% Discount") if products_seen.uniq.sort == products_needed.uniq.sort
end

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  next unless product.id == discounted_product2
  line_item.change_line_price(line_item.line_price * 0.80, message: "20% Discount") if products_seen.uniq.sort == products_needed.uniq.sort
end

Output.cart = Input.cart

I spoke to a solutions partner at Shopify and they suggested using the following code, I can't figure out the best way to integrate it. 

# Valid discount code is Vip-freeshipping
# Change values below as needed.

discountCode = 'Vip-freeshipping' 
discountMessage = 'My Sale'
discountAmount = 0.90

# ======================================

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  next if product.gift_card?
  next unless Input.cart.discount_code
  line_item.change_line_price(line_item.line_price * discountAmount, message: discountMessage) if Input.cart.discount_code.code == discountCode
end

Output.cart = Input.cart

Any help would be appreciated.

Charles

0 Likes