Tracking checkout events in Shopify using Google Tag Manager

NOTE: This guide describes one method for uploading real-time conversion events. For all available methods, see Upload real-time conversion events. If you're uploading event data as part of the product catalog integration workflow, first complete Step 2: Upload product catalog data.

This guide is for customers of The Trade Desk who use Shopify and want to have conversion information from their Checkout or Thank You pages reported to The Trade Desk, for checkout or confirmation events, and are using Google Tag Manager.

Intended audience

This document serves two audiences:

These instructions are valid for both scenarios.

Implementation options

There are two implementation options:

The following sections provide details about the available options, give step-by-step instructions with script samples, and include reference information to help you.

URL mapping

URL mapping extends the universal pixel into the Shopify Checkout Extensibility funnel to track checkout and purchase events.

Here's what you need to know about the URL mapping option:

For more information, see Universal pixel.

Implementation overview

This procedure sets up two scripts: one that runs inside Shopify to collect checkout data, and one in Google Tag Manager that sends the checkout data to The Trade Desk.

The Trade Desk platform uses the page URL to identify whether the event that took place was a checkout or purchase event.

Prerequisites

To implement this solution, you'll need to have the following:

Access to The Trade Desk Platform
Your advertiser ID
Your GTM ID

Implementation steps

The instructions in the following sections use the Trade Desk Events SDK to implement URL mapping in Shopify. The steps are summarized in the following table.

Step Task Tool / Platform Notes
1 Create a universal pixel. The Trade Desk UI Copy the pixel ID for use in Step 4.
2 Prepare the GTM initialization code. Text editor Replace placeholder values with your GTM ID and map data variables in GTM.
3 Paste the GTM initialization code. Shopify UI Save the code in Shopify as a custom pixel.
4 Prepare the GTM tag script. Text editor Replace placeholder values with your advertiser ID and pixel ID.
5 Implement the tag script. Google Tag Manager In GTM, paste the script as a tag and create custom triggers.

Step 1: Create a universal pixel

NOTE: If you already have the universal pixel, there's no need to create one. Just get the ID of your existing pixel.

To create the universal pixel, follow these steps:

  1. Log in to The Trade Desk platform.

  2. On the left, choose Libraries > Advertiser Data and click the Universal Pixels tab.

  3. In the Universal Pixels tab, create the following URL mappings:

    URL Mapping Type Pattern
    Checkout Custom */checkouts/*/en-us
    Purchase Contains thank-you

    NOTE: The checkout pattern is based on the US English locale (en-us). If the client's store uses a different locale, contact your Technical Account Manageronfirm the correct pattern.

  4. Copy the universal pixel ID and save it for use in Step 4: Prepare the GTM tag script.

    For details, see Create a Universal Pixel in the Knowledge Portal.

Step 2: Prepare the GTM URL mapping initialization code

You must first customize the GTM initialization code and implement it in Shopify, which captures checkout event data and pushes it to the GTM data layer. Then, implement the tag script in GTM.

The script uses the following preconfigured data layer keys:

IMPORTANT: These names are preconfigured: do not rename them. You'll create matching Data layer variables in GTM in Step 4: Prepare the GTM tag script.

To customize the GTM initialization code, follow these steps:

  1. Make a copy of the code.

  2. Update the GTM-XXXXXXX_PLACEHOLDER placeholder with your own GTM ID.

  3. (Optional) If you want to track additional dynamic values, add the data layer variable keys that represent the optional parameters TD1 through TD9, as applicable, below the lines for TTD_OrderTotal, TTD_Currency, and TTD_OrderId in the GTM initialization code. TD10 is also a dynamic parameter, but the script uses it.

    NOTE: To track these values, you must add them in the script as well as in the GTM initialization code. See Step 4: Prepare the GTM tag script.

    For assistance with configuring dynamic parameters, if needed, ask your Technical Account Manager.

// TTD URL Mapping - GTM Initialization Script in Shopify 
// Initialize GTM data layer
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

// Initialize GTM tag
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXX_PLACEHOLDER');

// Google Consent Mode v2
gtag('consent', 'update', {
  'ad_storage': 'granted',
  'analytics_storage': 'granted',
  'ad_user_data': 'granted',
  'ad_personalization': 'granted',
});

// Checkout Started
analytics.subscribe('checkout_started', function(event) {
  window.dataLayer.push({
    event: 'startcheckout',
    TTD_ReferrerUrl: event.context.document.location.href,
    TTD_OrderTotal: event.data?.checkout?.totalPrice?.amount,
    TTD_Currency: event.data?.checkout?.currencyCode
  });
});

// Checkout Completed (Purchase)
analytics.subscribe('checkout_completed', function(event) {
  window.dataLayer.push({
    event: 'purchase',
    TTD_ReferrerUrl: event.context.document.location.href,
    TTD_OrderTotal: event.data?.checkout?.totalPrice?.amount,
    TTD_Currency: event.data?.checkout?.currencyCode,
    TTD_OrderId: event.data?.checkout?.order?.id
  });
});

Step 3: Paste the GTM initialization code in Shopify

The code that you paste into Shopify in this step later pushes the event name to the data layer for each subscription event.

In the Shopify UI, paste the GTM initialization code:

  1. Go to Admin > Settings > Customer events.

  2. Click Add Custom Pixel.

  3. Paste the Google Tag Manager code and save.

NOTE: Shopify handles consent checking for custom pixels automatically: Customer events > Customer privacy. However, these steps help verify that the permission settings are configured appropriately for your store's requirements.

Step 4: Prepare the GTM tag script

The tag script runs in Google Tag Manager and sends the checkout event data captured by the initialization code to The Trade Desk.

This script includes some generic placeholder values. To prepare the script for your own implementation, you'll need to customize it with your own advertiser ID and universal pixel ID. Follow these steps:

  1. Make a copy of the script.

  2. Replace the following placeholders with your own values:

    • ADVERTISER_ID_PLACEHOLDER: Use your own advertiser ID.
    • UPIXEL_ID_PLACEHOLDER: Use the universal pixel ID that you copied from the platform UI in Step 1: Create a universal pixel.
  3. In GTM, go to Variables > User-Defined Variables > New > Data Layer Variable and create a data layer variable for each of the following keys.
    IMPORTANT: Your key names must exactly match the keys pushed by the initialization script. Use the following names:

    • TTD_ReferrerUrl
    • TTD_OrderTotal
    • TTD_Currency
    • TTD_OrderId

    NOTE: The double curly brackets in the tag script (for example, {{TTD_ReferrerUrl}}) are required by GTM to reference these variables.

    For details about adding data layer variables, see Create user-defined variables for the dataLayer object in the Knowledge Portal or refer to the Google Tag Manager documentation.

  4. (Optional) If you want to track additional dynamic values, add the data layer variables that represent the optional parameters TD1 through TD9, as applicable, before the line for TD10 in the script. TD10 is also a dynamic parameter, but the script uses it.

    NOTE: To track these values, you must add them in the GTM initialization code as well as in the script.

    For assistance with configuring dynamic parameters, if needed, ask your Technical Account Manager.

// The Trade Desk URL Mapping - GTM Tag Script 
<script type="text/javascript">
(function () {
  var script = document.createElement('script');
  script.src = 'https://js.adsrvr.org/up_loader.3.0.0.js';
  document.head.appendChild(script);

  window.ttdConversionEventsLayer = window.ttdConversionEventsLayer || [];
  function ttdConversionEvents() {
    window.ttdConversionEventsLayer.push(arguments);
  }

  script.onerror = function () {
    console.error('TTD: Failed to load SDK from', script.src);
  };

  script.onload = function () {
    ttdConversionEvents("init", {
      advertiserId: "ADVERTISER_ID_PLACEHOLDER",
      pixelIds: ["UPIXEL_ID_PLACEHOLDER"]
    });

    // Single conversion event (fires on GTM trigger match)
    ttdConversionEvents("event", {
      referrer_url: {{TTD_ReferrerUrl}},
      value: {{TTD_OrderTotal}},
      currency: {{TTD_Currency}},
      order_id: {{TTD_OrderId}},
      td10: "TTDxShopifyIntegration"
    });
  };
})();
</script>

Step 5: Implement the tag script in GTM

In Google Tag Manager, implement the script:

  1. Paste the script as a tag.

  2. Go to Triggers, and create two custom event triggers so that the tag is only fired during the checkout funnel:

    1. Click the + icon to add a trigger.

    2. For the trigger type, select Custom Event.

    3. Specify the following values for the first trigger:

      • Trigger name: TTD - startcheckout
      • Event name: startcheckout
    4. Create a second trigger with the following values:

      • Trigger name: TTD - purchase
      • Event name: purchase

    NOTE: The trigger name is a label for your reference in GTM. The event name must match exactly what the initialization script pushes, including case since these are case sensitive.

    For details, see Triggers in the Google Tag Manager help.

Event tracking

Here's what you need to know about event tracking:

Implementation overview

This procedure sets up two scripts: one that runs inside Shopify to collect checkout data including product-level details, and one in GTM that sends that data to The Trade Desk.

Unlike URL mapping, this option is triggered by Shopify checkout events rather than URL changes, and captures richer data such as SKUs, quantities, and prices for each item in the order.

This implementation uses GTM data layer variables. In Google Tag Manager, you can use data layer variables to capture event data from Shopify, such as order ID, currency, and price. For details, see Subscribe to customer events and push to GTM’s data layer in the Shopify documentation.

Prerequisites

To implement this solution, you'll need to have the following:

Access to The Trade Desk Platform
Parent event tracker ID (collected in Step 2)
Your GTM ID
Your merchant ID

If you don't have a merchant ID, contact your Technical Account Manager, who will generate one and send it to you. When you have a merchant ID, a new tab becomes available in the platform UI: in Libraries > Advertiser Data, the new tab is Events Tracking.

Implementation steps

IMPORTANT: This integration is intended to serve the full checkout experience (checkout and confirmation pages). It includes additional functionality applicable only to those pages. For other pages, use the standard universal pixel implementation: for details, see Universal pixel.

The instructions in the following sections use the Trade Desk Events SDK to implement event tracking in Shopify. The steps are summarized in the following table.

Step Task Tool / Platform Notes
1 Set up events tracking. The Trade Desk UI Copy the Tracker ID and Merchant ID for use in Step 4.
2 Prepare the GTM initialization code. Text editor Replace placeholder values with your GTM ID and map data variables and data variable keys in GTM.
3 Paste the GTM initialization code. Shopify UI Save the code in Shopify as a custom pixel.
4 Prepare the script. Text editor Replace placeholder values for your advertiser ID and pixel ID.
5 Implement the script. Google Tag Manager In GTM, paste the script as a tag and create custom triggers.

Step 1: Set up events tracking

In the platform UI, set up event tracking:

  1. On the left, choose Libraries > Advertiser Data and click the Events tracking tab.

    There are various data columns such as Name, Tracker ID, and Merchant ID. Copy the Tracker ID and Merchant ID and save them for use in Step 4.

  2. In the Events Tracking tab, create the following events:

    • startcheckout
    • purchase

Step 2: Prepare the GTM event tracking initialization code

You must first implement the GTM initialization code in Shopify, which captures checkout event data including item-level details and pushes it to the GTM data layer. Then, implement the tag script in GTM.

The code uses the following preconfigured data variable keys:

IMPORTANT: These names are preconfigured: do not rename them. You'll create matching Data layer variables in GTM in Step 4: Prepare the script.

To customize the GTM initialization code, follow these steps:

  1. Make a copy of the code.

  2. Update the GTM-XXXXXXX_PLACEHOLDER placeholder with your own GTM ID.

  3. (Optional) If you want to track additional dynamic values, add the data layer variable keys that represent the optional parameters TD1 through TD9, as applicable, in the GTM initialization code.

    NOTE: To track these values, you must add them in the script as well as in the GTM initialization code. See Step 4: Prepare the script.

    For assistance with configuring dynamic parameters, if needed, ask your Technical Account Manager.

// TTD Events Tracking - GTM Initialization Script in Shopify 
// Initialize GTM data layer
window.dataLayer = window.dataLayer || [];
function gtag() {
  dataLayer.push(arguments);
}

// Initialize GTM tag
(function (w, d, s, l, i) {
  w[l] = w[l] || [];
  w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });
  var f = d.getElementsByTagName(s)[0],
      j = d.createElement(s),
      dl = l != 'dataLayer' ? '&l=' + l : '';
  j.async = true;
  j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
  f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-XXXXXXX_PLACEHOLDER');

// Google Consent Mode v2
gtag('consent', 'update', {
  'ad_storage': 'granted',
  'analytics_storage': 'granted',
  'ad_user_data': 'granted',
  'ad_personalization': 'granted',
});

// Checkout Started
analytics.subscribe('checkout_started', function (event) {
  window.dataLayer.push({
    event: 'startcheckout',
    TTD_ReferrerUrl: event.context.document.location.href,
    TTD_OrderTotal: event.data?.checkout?.totalPrice?.amount,
    TTD_Currency: event.data?.checkout?.currencyCode,
    TTD_Items: event.data?.checkout?.lineItems ?? []
  });
});

// Purchase
analytics.subscribe('checkout_completed', function (event) {
  window.dataLayer.push({
    event: 'purchase',
    TTD_ReferrerUrl: event.context.document.location.href,
    TTD_OrderTotal: event.data?.checkout?.totalPrice?.amount,
    TTD_Currency: event.data?.checkout?.currencyCode,
    TTD_OrderId: event.data?.checkout?.order?.id,
    TTD_Items: event.data?.checkout?.lineItems ?? []
  });
});

Step 3: Paste the GTM initialization code in Shopify

In the Shopify UI, paste the GTM initialization code:

  1. Go to Admin > Settings > Customer events.

  2. Click Add Custom Pixel.

  3. Paste the Google Tag Manager code and save.

NOTE: Shopify handles consent checking for custom pixels automatically: Customer events > Customer privacy. However, these steps help verify that the permission settings are configured appropriately for your store's requirements.

Step 4: Prepare the script

The tag script runs in GTM and sends the checkout event data captured by the initialization code, including item-level details, to The Trade Desk.

This script includes some generic placeholder values. To prepare the script for your own implementation, you'll need to customize it with your merchant ID and parent event tracker ID. Follow these steps:

  1. Make a copy of the script.

  2. Replace the following placeholders with your own values:

    • MERCHANT_ID_PLACEHOLDER: use your own merchant ID.
    • PARENT_EVENT_TRACKER_ID_PLACEHOLDER: use your own parent event tracker ID (Tracker ID column in the platform UI).
  3. (Optional) If you want to track additional dynamic values, add the data layer variables that represent the optional parameters TD1 through TD9, as applicable, below the lines for TTD_OrderTotal, TTD_Currency, and TTD_OrderId in the script. TD10 is also a dynamic parameter, but the script uses it.

    NOTE: To track these values, you must add them in the GTM initialization code as well as in the script. See Step 2: Prepare the GTM event tracking initialization code.

    For assistance with configuring dynamic parameters, if needed, ask your Technical Account Manager.

// The Trade Desk Event Tracking - GTM Tag Script 
<script type="text/javascript">
(function () {
  var script = document.createElement('script');
  script.src = 'https://js.adsrvr.org/up_loader.3.0.0.js';
  document.head.appendChild(script);

  window.ttdConversionEventsLayer = window.ttdConversionEventsLayer || [];
  function ttdConversionEvents() {
    window.ttdConversionEventsLayer.push(arguments);
  }

  script.onerror = function () {
    console.error('TTD: Failed to load SDK from', script.src);
  };

  script.onload = function () {
    ttdConversionEvents("init", {
      merchantId: "MERCHANT_ID_PLACEHOLDER",
      pixelIds: ["PARENT_EVENT_TRACKER_ID_PLACEHOLDER"]
    });

    function mapItems(items) {
      if (!items || !items.map) return [];
      return items.map(function (item) {
        var variant = (item && item.variant) || {};
        var product = (variant && variant.product) || {};
        var price = (variant && variant.price) || {};
        return {
          item_code: variant.sku || null,
          name: product.title || null,
          qty: item.quantity || null,
          price: price.amount || null,
          cat: product.type || null
        };
      });
    }

    var gtmEvent = {{Event}};

    if (gtmEvent === 'startcheckout') {
      ttdConversionEvents("event", {
        referrer_url: {{TTD_ReferrerUrl}},
        event_name: "startcheckout",
        value: {{TTD_OrderTotal}},
        currency: {{TTD_Currency}},
        items: mapItems({{TTD_Items}}),
        td10: "TTDxShopifyIntegration"
      });

    } else if (gtmEvent === 'purchase') {
      ttdConversionEvents("event", {
        referrer_url: {{TTD_ReferrerUrl}},
        event_name: "purchase",
        value: {{TTD_OrderTotal}},
        currency: {{TTD_Currency}},
        order_id: {{TTD_OrderId}},
        items: mapItems({{TTD_Items}}),
        td10: "TTDxShopifyIntegration"
      });
    }
  };
})();
</script>

Step 5: Implement the script in GTM

Implement the script:

  1. In Google Tag Manager, go to > Tags > New > Custom HTML.

  2. Paste the script as a tag.

  3. Go to Triggers, and create two custom event triggers so that the tag is only fired during the checkout funnel:

    1. Click the + icon to add a trigger.

    2. For the trigger type, select Custom Event.

    3. Specify the following values for the first trigger:

      • Trigger name: TTD - startcheckout
      • Event name: startcheckout
    4. Create a second trigger with the following values:

      • Trigger name: TTD - purchase
      • Event name: purchase

    NOTE: The trigger name is a label for your reference in GTM. The event name must match exactly what the initialization script pushes, including case since these are case sensitive.

    For details, see Triggers in the Google Tag Manager help.

    The code that you pasted into Shopify in Step 3 pushes the event name to the data layer for each subscription event.

Next steps

If you uploaded event data only for measurement, your integration is complete.

If you uploaded event data as part of a product catalog integration, the next step is to activate the data through your product catalog. To share access, continue to Step 4. Manage product catalog access. You can also create product lists to build audiences and measure sales performance.

Reference information

This section contains reference information to support the procedures in this document. It includes:

Shopify sandbox features

In Shopify, pixels are always implemented in the Shopify sandbox, which is a secure, isolated environment that allows you to run scripts without affecting the rest of your online store. For details, see Sandbox environment for pixels in the Shopify documentation.

The Checkout Extensibility feature runs in the Shopify sandbox environment.

Here's what you need to know about the Shopify sandbox:

Data layer variables

Data layer variables are a core concept of Google Tag Manager. They allow access to information that's stored in the Data Layer, which is a JavaScript object on a website.

In the context of Google Tag Manager and Shopify, a data layer variable is a placeholder that's used, in scenarios such as tracking and analytics, to capture pieces of event data from your Shopify store, such as order ID, currency, and price. The Google Tag Manager procedures in this document that relate to Google Tag Manager use data layer variables to capture this event data.

For details, see:

Optional dynamic parameters

You can track one or more of the additional dynamic parameters, TD1 through TD9, with any of these procedures. TD10 is also a dynamic parameter, but the script uses it.

To implement dynamic parameters in Google Tag Manager, add them to the GTM initialization code, and also to the custom script. In the GTM initialization code, add them in the section below window.dataLayer.push: this sends the dynamic parameter values to GTM, so that they are available in GTM. Then, in the script, add the lines so that GTM can pick up and send those values.

For details, see Dynamic parameters. For additional assistance, if needed, ask your Technical Account Manager.