Skip to content

Instantly share code, notes, and snippets.

@candelatech
Created Apr 22, 2020
Embed
What would you like to do?
Shopify Gift With Purchase
Variant_ids = [18334016901, 17782905285 ]
Product_ids = [5782681861, 5620148101 ]
Prices = [2450, 500 ]
Triggers = [15000, 2500 ]
def gwp(product_id, variant_id, product_price, activation_total)
should_trigger_gift = false
#first, add up all the line items' prices
total = Money.new(cents:0)
Input.cart.line_items.each do |line_item|
found = false;
for var_id in Variant_ids
if line_item.variant.id == var_id
found = true;
end
end
next if found
total = total + line_item.line_price
end
#should we should trigger the gift?
if total > Money.new(cents:activation_total)
should_trigger_gift = true
else
should_trigger_gift = false
end
if should_trigger_gift
Input.cart.line_items.each do |line_item|
product = line_item.variant.product
next if product.gift_card?
next unless product.id == product_id
line_price = line_item.line_price
line_discount = Money.new(cents:product_price)
new_line_price = line_price - line_discount
line_item.change_line_price( new_line_price , message: "1x Free Gift!")
break
end
else
Input.cart.line_items.each do |line_item|
product = line_item.variant.product
next if product.gift_card?
next unless product.id == product_id
line_price = line_item.line_price
regular_price = Money.new(cents:product_price)
new_line_price = regular_price * line_item.quantity
line_item.change_line_price( new_line_price , message: "1x Free Gift!")
break
end
end
Output.cart = Input.cart
end
#apply product one
gwp(Product_ids[0],Variant_ids[0],Prices[0],Triggers[0])
#apply product two
gwp(Product_ids[1],Variant_ids[1],Prices[1],Triggers[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment