Email customers a unique discount code, two weeks after order fulfillment, with Mechanic.

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

Email customers a unique discount code, two weeks after order fulfillment

This task generates a brand new discount code (copying configuration from another code, of your choice), and emails it to the customer, after waiting a configurable number of days after order fulfillment.

Runs Occurs whenever an order is fulfilled, with a 14 day delay. Configuration includes days to wait after order fulfillment, source discount code for cloning, override source with this discount validitity period in days, new discount code prefix, email subject, email body, and email bcc.

15-day free trial – unlimited tasks

Documentation

This task generates a brand new discount code (copying configuration from another code, of your choice), and emails it to the customer, after waiting a configurable number of days after order fulfillment.

Configure this task by first creating a discount code in your store, representative of the discount configuration you'd like this task to use. Provide the task with this source discount's code – when it runs, the task will clone this discount's configuration, using a new and unique discount name.

Configure with a number of days to wait after fulfillment, or remove this value completely to have the discount generated and sent immediately upon fulfillment.

Use the text "DISCOUNT_CODE" to have the generated discount code inserted into your email to the customer, in either the subject or body.

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/fulfilled{% if options.days_to_wait_after_order_fulfillment__number != blank %}+{{ options.days_to_wait_after_order_fulfillment__number }}.days{% endif %}
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
days to wait after order fulfillment (number), source discount code for cloning (required), override source with this discount validitity period in days (number), new discount code prefix, email subject (required), email body (required, multiline), email bcc (email)
Code
{% comment %}
  An opinion about option order:

  {{ options.days_to_wait_after_order_fulfillment__number }}
  {{ options.source_discount_code_for_cloning__required }}
  {{ options.override_source_with_this_discount_validitity_period_in_days__number }}
  {{ options.new_discount_code_prefix }}
  {{ options.email_subject__required }}
  {{ options.email_body__required_multiline }}
  {{ options.email_bcc__email }}
{% endcomment %}

{% unless event.preview %}
  {% assign order = order.reload %}
{% endunless %}

{% if event.preview != true and order.email == blank %}
  {% log "This order has no email address. Skipping. :)" %}
{% else %}
  {% assign source_discount_code = options.source_discount_code_for_cloning__required %}

  {% assign new_discount_code = order.id | split: "" | reverse | join: "" | slice: 0, 4 | append: order.order_number | base64 | replace: "=", "" | upcase | prepend: options.new_discount_code_prefix %}

  {% capture query %}
    query {
      codeDiscountNodeByCode(code: {{ source_discount_code | json }}) {
        id
        codeDiscount {
          __typename
          ... on DiscountCodeBasic {
            title
            usageLimit
            codeCount
            startsAt
            endsAt
            appliesOncePerCustomer
            summary
            minimumRequirement {
              __typename
              ... on DiscountMinimumQuantity {
                greaterThanOrEqualToQuantity
              }
              ... on DiscountMinimumSubtotal {
                greaterThanOrEqualToSubtotal {
                  amount
                  currencyCode
                }
              }
            }
            customerGets {
              items {
                __typename
                ... on AllDiscountItems {
                  allItems
                }
                ... on DiscountProducts {
                  productVariants(first: 250) {
                    edges {
                      node {
                        id
                      }
                    }
                  }
                  products(first: 250) {
                    edges {
                      node {
                        id
                      }
                    }
                  }
                }
                ... on DiscountCollections {
                  collections(first: 250) {
                    edges {
                      node {
                        id
                      }
                    }
                  }
                }
              }
              value {
                __typename
                ... on DiscountAmount {
                  amount {
                    amount
                    currencyCode
                  }
                  appliesOnEachItem
                }
                ... on DiscountOnQuantity {
                  effect {
                    ... on DiscountPercentage {
                      percentage
                    }
                  }
                  quantity {
                    quantity
                  }
                }
                ... on DiscountPercentage {
                  percentage
                }
              }
            }
            customerSelection {
              __typename
              ... on DiscountCustomers {
                customers {
                  id
                }
              }
              ... on DiscountCustomerAll {
                allCustomers
              }
              ... on DiscountCustomerSegments {
                segments {
                  id
                }
              }
            }
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "codeDiscountNodeByCode": {
            "id": "gid://shopify/DiscountCodeNode/1234567890",
            "codeDiscount": {
              "__typename": "DiscountCodeBasic",
              "title": "DISCOUNT",
              "usageLimit": 1,
              "codeCount": 1,
              "startsAt": "2019-11-04T20:06:44Z",
              "endsAt": "2019-11-13T04:59:59Z",
              "appliesOncePerCustomer": true,
              "summary": "50% off No shipping • Minimum purchase of $5.00 • For Isaac Bowen • One use per customer",
              "minimumRequirement": {
                "__typename": "DiscountMinimumSubtotal",
                "greaterThanOrEqualToSubtotal": {
                  "amount": "5.0",
                  "currencyCode": "USD"
                }
              },
              "customerGets": {
                "items": {
                  "__typename": "DiscountProducts",
                  "productVariants": {
                    "edges": []
                  },
                  "products": {
                    "edges": [
                      {
                        "node": {
                          "id": "gid://shopify/Product/1234567890"
                        }
                      }
                    ]
                  }
                },
                "value": {
                  "__typename": "DiscountPercentage",
                  "percentage": 0.5
                }
              },
              "customerSelection": {
                "__typename": "DiscountCustomers",
                "customers": [
                  {
                    "id": "gid://shopify/Customer/1234567890"
                  }
                ]
              }
            }
          }
        }
      }
    {% endcapture %}

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

  {% assign discountNode = result.data.codeDiscountNodeByCode.codeDiscount %}

  {% log discount_summary: discountNode.summary %}

  {% if discountNode == nil %}
    {% error "Source discount was missing. Check your task configuration, and ensure that a discount exists with the configured code." %}
  {% elsif discountNode.__typename != "DiscountCodeBasic" %}
    {% error "This task only supports basic discounts. It does not support free shipping, or buy-one-get-one." %}
  {% else %}
    {% action "shopify" %}
      mutation {
        discountCodeBasicCreate(
          basicCodeDiscount: {
            title: {{ new_discount_code | json }}
            code: {{ new_discount_code | json }}
            {% if options.override_source_with_this_discount_validitity_period_in_days__number != blank %}
              startsAt: {{ "now" | date: "%FT%TZ", tz: "UTC" | json }}
              {% assign interval = 86400 | times: options.override_source_with_this_discount_validitity_period_in_days__number %}
              endsAt: {{ "now" | date: "%s" | plus: interval | date: "%FT%TZ", tz: "UTC" | json }}
            {% else %}
              startsAt: {{ discountNode.startsAt | json }}
              endsAt: {{ discountNode.endsAt | json }}
            {% endif %}
            usageLimit: {{ discountNode.usageLimit | json }}
            appliesOncePerCustomer: {{ discountNode.appliesOncePerCustomer | json }}
            {% if discountNode.minimumRequirement.__typename == "DiscountMinimumQuantity" %}
              minimumRequirement: {
                quantity: 0
              }
            {% elsif discountNode.minimumRequirement.__typename == "DiscountMinimumSubtotal" %}
              minimumRequirement: {
                subtotal: {
                  greaterThanOrEqualToSubtotal: {{ discountNode.minimumRequirement.greaterThanOrEqualToSubtotal.amount | json }}
                }
              }
            {% endif %}
            customerGets: {
              items: {
                {% if discountNode.customerGets.items.__typename == "AllDiscountItems" %}
                  all: {{ discountNode.customerGets.items.allItems | json }}
                {% elsif discountNode.customerGets.items.__typename == "DiscountProducts" %}
                  products: {
                    productsToAdd: {{ discountNode.customerGets.items.products.edges | map: "node" | map: "id" | json }}
                    productVariantsToAdd: {{ discountNode.customerGets.items.productVariants.edges | map: "node" | map: "id" | json }}
                  }
                {% elsif discountNode.customerGets.items.__typename == "DiscountCollections" %}
                  collections: {
                    add: {{ discountNode.customerGets.items.collections.edges | map: "node" | map: "id" | json }}
                  }
                {% endif %}
              }
              value: {
                {% if discountNode.customerGets.value.__typename == "DiscountAmount" %}
                  discountAmount: {
                    amount: {{ discountNode.customerGets.value.amount.amount | json }}
                    appliesOnEachItem: {{ discountNode.customerGets.value.appliesOnEachItem | json }}
                  }
                {% elsif discountNode.customerGets.value.__typename == "DiscountOnQuantity" %}
                  discountOnQuantity: {
                    quantity: {{ discountNode.customerGets.value.quantity.quantity | json }}
                    effect: {
                      percentage: {{ discountNode.customerGets.value.effect.percentage | json }}
                    }
                  }
                {% elsif discountNode.customerGets.value.__typename == "DiscountPercentage" %}
                  percentage: {{ discountNode.customerGets.value.percentage | json }}
                {% endif %}
              }
            }
            customerSelection: {
              {% if discountNode.customerSelection.__typename == "DiscountCustomers" %}
                customers: {
                  add: {{ discountNode.customerSelection.customers | map: "id" | json }}
                }
              {% elsif discountNode.customerSelection.__typename == "DiscountCustomerAll" %}
                all: {{ discountNode.customerSelection.allCustomers | json }}
              {% elsif discountNode.customerSelection.__typename == "DiscountCustomerSegments" %}
                customerSegments: {
                  add: {{ discountNode.customerSelection.segments | map: "id" | json }}
                }
              {% endif %}
            }
          }
        ) {
          codeDiscountNode {
            id
            codeDiscount {
              ... on DiscountCodeBasic {
                summary
              }
            }
          }
          userErrors {
            code
            field
            message
          }
        }
      }
    {% endaction %}

    {% action "email" %}
      {
        "to": {{ order.email | json }},
        "subject": {{ options.email_subject__required | replace: "DISCOUNT_CODE", new_discount_code  | json }},
        "body": {{ options.email_body__required_multiline | replace: "DISCOUNT_CODE", new_discount_code | newline_to_br | json }},
        "reply_to": {{ shop.customer_email | json }},
        "from_display_name": {{ shop.name | json }},
        "bcc": {{ options.email_bcc__email | json }}
      }
    {% endaction %}
  {% endif %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more
Defaults
Days to wait after order fulfillment
14
Email subject
Thanks for your order! We've attached your discount. :)
Email body
Hello {{ order.customer.first_name | default: "there" }},

Thanks for your order ({{ order.name }})! You can use the discount code DISCOUNT_CODE on your  next order.

Cheers,
{{ shop.name }}