d
Topic
Posts:
6
Last edited May 28, 2015

Better gift card handling in email templates [problem and solution] This post is outdated

This is the sample code for including gift card information in the "order confirmation" email template:
https://docs.shopify.com/manual/your-store/gift-cards/personalize-email-notification#order-confirmation-email

<p>Shipping: {{ shipping_price | money_with_currency }}</p>
{% endif %}
{% assign gift_card_applied = false %}
{% assign gift_card_amount = 0 %}
{% for transaction in transactions %}
  {% if transaction.gateway  == 'gift_card' %}
    {% assign gift_card_applied = true %}
    {% assign gift_card_amount = gift_card_amount | plus: transaction.amount %}
  {% endif %}
{% endfor %}
{% if gift_card_amount > 0 %}
<p>Gift cards: {{ gift_card_amount | times: -1 | money_with_currency }}</p>
{% endif %}
<p>Total: {{ total_price | minus: gift_card_amount | money_with_currency }}</p>

However, that code does not account for errors in mixed payment situations because it doesn't distinguish between successful and failed transactions.

For example, if I pay for a $30 product with a $25 gift card and $5 by credit card, and I make a mistake with my credit card number and then fix it and pay successfuly, the email, using the code above, will double-count the gift card amount because in a mixed payment scenario, when the credit card fails, shopify also refunds the gift cards before trying again. This is counted as a 'transaction' so the gift card amount will be wrong.

The following code fixes this problem:

<p>Shipping: {{ shipping_price | money }} - {{ shipping_method.title }}</p>
{% assign gift_card_amount = 0 %}
{% assign last_failure_id = 1 %}
{% for transaction in transactions %}
	{% if transaction.status == 'failure' %}
		{% assign last_failure_id = transaction.id %}
		{% assign gift_card_amount = 0 %}
	{% endif %}
  {% if transaction.gateway  == 'gift_card' and transaction.kind == 'sale' and transaction.status == 'success' and transaction.id >= last_failure_id %}
    {% assign gift_card_amount = gift_card_amount | plus: transaction.amount %}
  {% endif %}
{% endfor %}
{% if gift_card_amount > 0 %}
	<p>Gift cards: {{ gift_card_amount | times: -1 | money }}</p>
{% endif %}
<p>Total: {{ total_price | minus: gift_card_amount | money_with_currency }}</p>