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. 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.

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. 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. If you choose this option, you cannot choose a fixed discount amount.
  • Discount applies to each line item individually: If enabled, the discount will apply to each item ordered. If disabled, the discount will only apply once per 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
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
{% comment %}
  Options order:

  {{ options.required_product_id__number_required }}
  {{ options.discount_collection_id__number }}
  {{ options.discount_code_prefix }}
  {{ options.discount_fixed_amount__number }}
  {{ options.discount_percentage__number }}
  {{ options.discount_applies_to_each_line_item_individually__boolean }}
  {{ options.discount_lifetime_in_days__number }}
  {{ options.discount_can_be_used_by_anyone__boolean }}
  {{ options.email_subject__required }}
  {{ options.email_body__multiline_required }}
{% endcomment %}

{% if options.discount_percentage__number == blank and options.discount_fixed_amount__number == blank %}
  {% error "Please fill either the discount percentage or discount fixed amount." %}
{% elsif options.discount_percentage__number != blank and options.discount_fixed_amount__number != blank %}
  {% error "Please choose between the discount percentage and discount fixed amount - only one is permitted." %}
{% endif %}

{% if event.preview %}
  {% capture order_json %}
    {
      "email": "customer@example.com",
      "customer": {
        "admin_graphql_api_id": "gid://shopify/Customer/1234567890"
      },
      "line_items": [
        {
          "id": 1234567890,
          "product_id": {{ options.required_product_id__number_required | json }},
          "quantity": 1
        }
      ]
    }
  {% endcapture %}

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

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

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

  {% if order.email == blank %}
    {% log "This order has no email address. Skipping" %}
    {% 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: options.discount_code_prefix %}

    {% assign email_subject = options.email_subject__required | replace: 'DISCOUNT_CODE', discount_code %}
    {% assign email_body = options.email_body__multiline_required | replace: 'DISCOUNT_CODE', discount_code %}

    {% action "email" %}
      {
        "to": {{ order.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 %}

    {% action "shopify" %}
      mutation {
        priceRuleCreate(
          priceRule: {
            allocationMethod: {% if options.discount_applies_to_each_line_item_individually__boolean %}EACH{% else %}ACROSS{% endif %}
            customerSelection: {
              {% if options.discount_can_be_used_by_anyone__boolean %}
                forAllCustomers: true
              {% else %}
                customerIdsToAdd: [
                  {{ order.customer.admin_graphql_api_id | json }}
                ]
              {% endif %}
            }
            itemEntitlements: {
              {% if options.discount_collection_id__number != blank %}
                collectionIds: [
                  {{ shop.collections[options.discount_collection_id__number].admin_graphql_api_id | json }}
                ]
              {% else %}
                targetAllLineItems: true
              {% endif %}
            }
            target: LINE_ITEM
            title: {{ discount_code | json }}
            validityPeriod: {
              start: {{ "now" | date: "%FT%T%:z" | json }}

              {% if options.discount_lifetime_in_days__number != blank %}
                {% assign validity_days_s = 60 | times: 60 | times: 24 | times: options.discount_lifetime_in_days__number %}
                end: {{ "now" | date: "%s" | plus: validity_days_s | date: "%FT%T%:z" | json }}
              {% endif %}
            }
            value: {
              {% if options.discount_percentage__number != blank %}
                percentageValue: {{ options.discount_percentage__number | abs | times: -1 | json }}
              {% endif %}

              {% if options.discount_fixed_amount__number != blank %}
                fixedAmountValue: {{ options.discount_fixed_amount__number | abs | times: -1 | append: "" | json }}
              {% endif %}
            }
          }
          priceRuleDiscountCode: {
            code: {{ discount_code | json }}
          }
        ) {
          priceRule {
            id
            allocationMethod
            endsAt
            target
            summary
          }
          priceRuleUserErrors {
            code
            field
            message
          }
          priceRuleDiscountCode {
            code
            id
          }
        }
      }
    {% endaction %}
  {% endfor %}
{% endfor %}
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 }}