Tag online orders by their ?ref= referral codes, with Mechanic.

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

Tag online orders by their ?ref= referral codes

Have your traffic sources refer customers using ?ref=referral-code-here URLs (using the query parameter of your choice), then use this task to automatically tag each customer's order according to the referral value they arrived with. Optionally, tag the customer as well.

Runs Occurs whenever an order is created. Configuration includes query parameter name, cart attribute name, tag customer with parameter value, and only tag the customer for their first order.

15-day free trial – unlimited tasks

Documentation

Have your traffic sources refer customers using ?ref=referral-code-here URLs (using the query parameter of your choice), then use this task to automatically tag each customer's order according to the referral value they arrived with. Optionally, tag the customer as well.

This task adds JavaScript to your storefront, which adds referral parameters (using the query parameter of your choice) to the customer's cart (using the cart attribute name of your choice). (Referral values are saved in a browser cookie for one year.) When the corresponding order is created, this task copies the cart attribute over to the order's tags. Optionally, select to have the value applied to the customer as a tag as well.

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/create
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
query parameter name (required), cart attribute name (required), tag customer with parameter value (boolean), only tag the customer for their first order (boolean)
Code
{% comment %}
  An opinion about option order

  {{ options.query_parameter_name__required }}
  {{ options.cart_attribute_name__required }}
  {{ options.tag_customer_with_parameter_value__boolean }}
  {{ options.only_tag_the_customer_for_their_first_order__boolean }}
{% endcomment %}

{% if event.preview %}
  {% assign order = hash %}
  {% assign order["admin_graphql_api_id"] = "gid://shopify/Order/1234567890" %}
  {% assign order["note_attributes"] = hash %}
  {% assign order["note_attributes"][options.cart_attribute_name__required] = "ABC123" %}
  {% assign order["customer"] = hash %}
  {% assign order["customer"]["admin_graphql_api_id"] = "gid://shopify/Customer/1234567890" %}
{% endif %}

{% assign value = order.note_attributes[options.cart_attribute_name__required] %}
{% if value == blank %}
  {% log message: "This order did not have the specified cart attribute - nothing to do.", attributes: order.note_attributes %}
{% else %}
  {% assign order_tags = order.tags | split: ", " %}
  {% unless order_tags contains value %}
    {% action "shopify" %}
      mutation {
        tagsAdd(
          id: {{ order.admin_graphql_api_id | json }}
          tags: {{ value | json }}
        ) {
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}
  {% endunless %}
{% endif %}

{% if options.tag_customer_with_parameter_value__boolean %}
  {% assign customer_qualifies = true %}

  {% assign customer_tags = order.customer.tags | split: ", " %}
  {% if customer_tags contains value %}
    {% assign customer_qualifies = false %}
  {% endif %}

  {% if options.only_tag_the_customer_for_their_first_order__boolean %}
    {% comment %}
      We go the long way about this, because (a) in a test store,
      Shopify is not incrementing customer.orders_count, and (b)
      it does not seem like the order reliably exists for retrieval
      the instant it is placed. This way, we can mark the customer
      as qualified if there are no orders, or if there is an order
      and this is it.
    {% endcomment %}

    {% capture query %}
      query {
        customer(id: {{ order.customer.admin_graphql_api_id | json }}) {
          tags
          orders(first: 1) {
            pageInfo {
              hasNextPage
            }
            edges {
              node {
                id
              }
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% if event.preview %}
      {% capture result_json %}
        {
          "data": {
            "customer": {
              "tags": [],
              "orders": {
                "pageInfo": {
                  "hasNextPage": false
                },
                "edges": [
                  {
                    "node": {
                      "id": {{ order.admin_graphql_api_id | json }}
                    }
                  }
                ]
              }
            }
          }
        }
      {% endcapture %}

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

    {% if result.data.customer.orders.pageInfo.hasNextPage %}
      {% assign customer_qualifies = false %}
    {% elsif result.data.customer.orders.edges != empty and result.data.customer.orders.edges.first.node.id != order.admin_graphql_api_id %}
      {% assign customer_qualifies = false %}
    {% endif %}
  {% endif %}

  {% if customer_qualifies and value != blank %}
    {% action "shopify" %}
      mutation {
        tagsAdd(
          id: {{ order.customer.admin_graphql_api_id | json }}
          tags: {{ value | json }}
        ) {
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}
  {% endif %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more
Online store JavaScript
// https://gist.github.com/bronson/6707533
var cookie = function(name, value, ms) {
    if(arguments.length < 2) {
        // read cookie
        var cookies = document.cookie.split(';')
        for(var i=0; i < cookies.length; i++) {
            var c = cookies[i].replace(/^\s+/, '')
            if(c.indexOf(name+'=') == 0) {
                return decodeURIComponent(c.substring(name.length+1).split('+').join(' '))    
            }
        }
        return null
    }

    // write cookie
    var date = new Date()
    date.setTime(date.getTime()+ms)
    document.cookie = name+"=" + encodeURIComponent(value) + (ms ? ";expires="+date.toGMTString() : '') + ";path=/"
}

var parameterName = {{ options.query_parameter_name__required | json }};

var valueKeyval = window.location.search.split(/[?&]/).filter(function (keyval) {
  return keyval.slice(0, parameterName.length) === parameterName;
})[0];

var valueFromCookie = cookie(parameterName);

if (valueFromCookie || valueKeyval) {
  var value = valueFromCookie || decodeURIComponent(valueKeyval.split('=')[1]);

  if (!valueFromCookie) {
    cookie(parameterName, value, 1000*60*60*24*365);
  }

  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/cart/update.json', true);

  //Send the proper header information along with the request
  xhr.setRequestHeader('Content-Type', 'application/json');

  var attributes = {};
  attributes[{{ options.cart_attribute_name__required | json }}] = value;
  xhr.send(JSON.stringify({ attributes: attributes }));
}
When this task is installed, this code is loaded into the online storefront using a ScriptTag.
Defaults
Query parameter name
ref
Cart attribute name
Referral code