Generate a discount code when a certain product is purchased, with Mechanic.

Mechanic is a development and ecommerce automation platform for Shopify. :)

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.

Runs Occurs whenever an order is paid and Occurs when a Mechanic action is performed. Configuration includes required product id, discount collection id, discount code prefix, discount fixed amount, discount percentage, discount applies to each line item individually, discount lifetime in days, discount can be used by anyone, email subject, and email body.

15-day free trial – unlimited tasks

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 ID: The ID of the product that the customer must purchase, in order to qualify for the discount. (Learn how to find the product ID.)
  • Discount collection ID (optional): The ID of a specific collection of products that the discount code should be good for. (Learn how to find the collection ID.)
  • 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.

Developer details

Mechanic is designed to benefit everybody: merchants, customers, developers, agencies, Shopifolks, everybody.

That’s why we make it easy to configure automation without code, why we make it easy to tweak the underlying code once tasks are installed, and why we publish it all here for everyone to learn from.

(By the way, have you seen our documentation? Have you joined the Slack community?)

Open source
View on GitHub to contribute to this task
Subscriptions
shopify/orders/paid
mechanic/actions/perform
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
required product id (number, required), discount collection id (number), discount code prefix, discount fixed amount (number), discount percentage (number), discount applies to each line item individually (boolean), discount lifetime in days (number), discount can be used by anyone (boolean), email subject (required), email body (multiline, required)
Code
{% assign required_product_id = options.required_product_id__number_required %}
{% assign discount_collection_id = options.discount_collection_id__number %}
{% 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 discount_collection_id != blank %}
  {% assign discount_collection_id = discount_collection_id | prepend: "gid://shopify/Collection/" %}
{% endif %}

{% if event.topic == "shopify/orders/paid" %}
  {% if event.preview %}
    {% capture order_json %}
      {
        "email": "customer@example.com",
        "customer": {
          "id": 1234567890
        },
        "line_items": [
          {
            "id": 1234567890,
            "product_id": {{ required_product_id }},
            "quantity": 1
          }
        ]
      }
    {% endcapture %}

    {% assign order = order_json | parse_json %}
  {% endif %}

  {% 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 %}

  {% assign customer_id = order.customer.id | prepend: "gid://shopify/Customer/" %}

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

  {% for line_item in order.line_items %}
    {% if line_item.product_id != required_product_id %}
      {% continue %}
    {% endif %}

    {% for n in (1..line_item.quantity) %}
      {% assign discount_code = line_item.id | append: n | split: "" | reverse | join: "" | slice: 0, 4 | append: order.order_number | 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: 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" %}
    {
      "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 %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more
Defaults
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 }}