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

Mechanic is an automation development platform for Shopify. :)

Generate a discount code when a certain product is purchased

by Isaac Bowen (team@usemechanic.com)

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 when an order is paid. Configuration includes required product, discount collection, 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.

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

Events
when an order is paid (shopify/orders/paid)
Options
required product (number, required), discount collection (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)
Script
{% 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 %}

{% assign product_ids = order.line_items | map: "product_id" %}

{% assign order_qualifies = false %}
{% if product_ids contains options.required_product_id__number_required and order.customer %}
  {% assign order_qualifies = true %}
{% endif %}

{% if event.preview or order_qualifies %}
  {% assign discount_code = order.id | 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 %}
{% endif %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.
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 }}