Mechanic Get Mechanic
Task library

Generate a discount code when a certain product is purchased

This task watches for newly-paid orders, and if the configured product is purchased, sends the customer a discount code that's just for them. Optionally, configure the discounts to only apply to a certain collection of products, and to only last for a certain number of days.

Try this task

When it runs

  • Occurs whenever an order is paid
  • Occurs when a Mechanic action is performed

What you choose

  • Required product
  • Discount collection
  • Discount code prefix
Show 7 more
  • Discount fixed amount
  • Discount percentage
  • Discount applies to each line item individually
  • Discount lifetime in days
  • Discount can be used by anyone
  • Email subject
  • Email body

Documentation

This task watches for newly-paid orders, and if the configured product is purchased, sends the customer a discount code that's just for them. Optionally, configure the discounts to only apply to a certain collection of products, and to only last for a certain number of days.

If a customer purchases more than one qualified product, they will receive more than one email, each containing a unique discount code.

Options

  • Required product: The product that the customer must purchase, in order to qualify for the discount.
  • Discount collection (optional): The specific collection of products that the discount code should be good for.
  • Discount code prefix (optional): A small piece of text to add to the beginning of the generated discount code.
  • Discount fixed amount: The money value to be subtracted. If you choose this option, you cannot choose a discount percentage.
  • Discount percentage: The percentage to be subtracted (e.g. 15). If you choose this option, you cannot choose a fixed discount amount.
  • Discount applies to each line item individually: If enabled and if a collection ID is configured, the discount will apply to each item from the collection on the order. If disabled, the discount will only apply once per order. If no collection ID is configured, this setting will be overridden to apply once oer order.
  • Discount lifetime in days: How long the discount should be active.
  • Discount can be used by anyone: If enabled, the discount code can be used by anyone. If disabled, the discount code can only be used by the purchasing customer.
  • Email subject, body: The content to email to the customer. Use "DISCOUNT_CODE" as a placeholder for the generated discount code.
Task code and subscriptions

You can edit the Liquid code after installing this task. View on GitHub or ask a question in the Mechanic Slack community.

Subscriptions

shopify/orders/paid
mechanic/actions/perform
How task subscriptions work

Option types and flags

Task code

{% assign required_product_id = options.required_product__picker_product_required %}
{% assign discount_collection_id = options.discount_collection__picker_collection %}
{% assign discount_code_prefix = options.discount_code_prefix %}
{% assign discount_fixed_amount = options.discount_fixed_amount__number %}
{% assign discount_percentage = options.discount_percentage__number %}
{% assign discount_applies_to_each_line_item_individually = options.discount_applies_to_each_line_item_individually__boolean %}
{% assign discount_lifetime_in_days = options.discount_lifetime_in_days__number %}
{% assign discount_can_be_used_by_anyone = options.discount_can_be_used_by_anyone__boolean %}
{% assign email_subject = options.email_subject__required %}
{% assign email_body = options.email_body__multiline_required %}

{% if discount_percentage == blank and discount_fixed_amount == blank %}
  {% error "Please fill either the discount percentage or discount fixed amount." %}

{% elsif discount_percentage != blank and discount_fixed_amount != blank %}
  {% error "Please choose between the discount percentage and discount fixed amount - only one is permitted." %}
{% endif %}

{% if event.topic == "shopify/orders/paid" %}
  {% comment %}
    -- get order data
  {% endcomment %}

  {% capture query %}
    query {
      order(id: {{ order.admin_graphql_api_id | json }}) {
        id
        name
        email
        customer {
          id
        }
        lineItems(first: 250) {
          nodes {
            id
            currentQuantity
            product {
              id
            }
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "order": {
            "id": "gid://shopify/Order/1234567890",
            "name": "#PREVIEW",
            "email": "sample@example.com",
            "customer": {
              "id": "gid://shopify/Customer/1234567890",
              "displayName": "Test Customer04"
            },
            "lineItems": {
              "nodes": [
                {
                  "id": "gid://shopify/LineItem/1234567890",
                  "currentQuantity": 1,
                  "product": {
                    "id": {{ required_product_id | json }}
                  }
                }
              ]
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = result_json | parse_json %}
  {% endif %}

  {% assign order = result.data.order %}

  {% if order.customer == blank %}
    {% log "This order has no related customer. Skipping" %}
    {% break %}
  {% endif %}

  {% if order.email == blank %}
    {% log "This order has no email address. Skipping" %}
    {% break %}
  {% endif %}

  {% comment %}
    -- create a discount code for each quantity of matching line items
  {% endcomment %}

  {% for line_item in order.lineItems.nodes %}
    {% if line_item.product.id != required_product_id %}
      {% continue %}
    {% endif %}

    {% for n in (1..line_item.currentQuantity) %}
      {% assign discount_code
        = line_item.id
        | append: n
        | split: ""
        | reverse
        | join: ""
        | slice: 0, 4
        | append: order.name
        | base64
        | replace: "=", ""
        | upcase
        | prepend: discount_code_prefix
      %}

      {% action "shopify" %}
        mutation {
          discountCodeBasicCreate(
            basicCodeDiscount: {
              code: {{ discount_code | json }}
              customerSelection: {
                {% if discount_can_be_used_by_anyone %}
                  all: true
                {% else %}
                  customers: {
                    add: {{ array | push: order.customer.id | json }}
                  }
                {% endif %}
              }
              title: {{ discount_code | json }}
              startsAt: {{ "now" | date: "%FT%T%:z" | json }}
              {% if discount_lifetime_in_days != blank %}
                {% assign validity_days_s = 60 | times: 60 | times: 24 | times: discount_lifetime_in_days %}
                endsAt: {{ "now" | date: "%s" | plus: validity_days_s | date: "%FT%T%:z" | json }}
              {% endif %}
              customerGets: {
                items: {
                  {% if discount_collection_id != blank %}
                    collections: {
                      add: {{ array | push: discount_collection_id | json }}
                    }
                  {% else %}
                    all: true
                  {% endif %}
                }
                value: {
                  {% if discount_percentage != blank %}
                    percentage: {{ discount_percentage | abs | divided_by: 100.0 | json }}
                  {% else %}
                    discountAmount: {
                      amount: {{ discount_fixed_amount | abs | times: 1.0 | json }}
                      {% if discount_collection_id != blank %}
                        appliesOnEachItem: {{ discount_applies_to_each_line_item_individually }}
                      {% else %}
                        appliesOnEachItem: false
                      {% endif %}
                    }
                  {% endif %}
                }
              }
            }
          ) {
            codeDiscountNode {
              id
              codeDiscount {
                ... on DiscountCodeBasic {
                  codes(first: 1) {
                    nodes {
                      id
                      code
                    }
                  }
                  endsAt
                  summary
                }
              }
            }
            userErrors {
              code
              extraInfo
              field
              message
            }
          }
        }
      {% endaction %}
    {% endfor %}
  {% endfor %}

{% elsif event.topic == "mechanic/actions/perform" %}
  {% comment %}
    -- only process a successful discountCodeBasicCreate shopify action; the Error reporter task should be used to respond to failures
  {% endcomment %}

  {% unless action.type == "shopify" and action.run.ok == true %}
    {% break %}
  {% endunless %}

  {% comment %}
    -- send a customer email for the created discount code
  {% endcomment %}

  {% assign discount_code = action.run.result.data.discountCodeBasicCreate.codeDiscountNode.codeDiscount.codes.nodes.first.code %}

  {% assign email_subject = email_subject | replace: 'DISCOUNT_CODE', discount_code %}
  {% assign email_body = email_body | replace: 'DISCOUNT_CODE', discount_code %}

  {% action "email", __perform_event: false %}
    {
      "to": {{ event.parent.data.email | json }},
      "subject": {{ email_subject | strip | json }},
      "body": {{ email_body | strip | newline_to_br | json }},
      "reply_to": {{ shop.customer_email | json }},
      "from_display_name": {{ shop.name | json }}
    }
  {% endaction %}
{% endif %}
Mechanic Liquid reference

Default option values

Discount percentage
50
Discount applies to each line item individually
true
Discount lifetime in days
365
Email subject
Thanks for your purchase! Your discount code is DISCOUNT_CODE.
Email body
Thanks for your purchase! Here's your discount code: <b>DISCOUNT_CODE</b>

<a href="https://{{ shop.domain }}/">Start shopping now!</a>

Thanks,
{{ shop.name }}