Skip to main content

Google Tag Manager Integration for Ecommerce

This page explains how to implement the Rokt SDK for Ecommerce using Google Tag Manager to deliver more relevant customer experiences at checkout. The SDK allows you to trigger and track these experiences (like displaying offers on confirmation pages) by firing on configured pages and passing user and transaction data back to Rokt for personalization and measurement.

You'll learn how to create variables in Google Tag Manager based on your data layer, and how to create tags to initialize the Rokt SDK and insert placements.

Understanding the data layer

The data layer should have been implemented on your web page by your developers.

A data layer is an object that contains all of the information that you want to share with Google Tag Manager (GTM). Information such as events or variables can be shared to Google Tag Manager via the data layer, and triggers can be set up in Google Tag Manager based on the values of variables (e.g., fire a remarketing tag when purchase_total > $100) or based on the specific events. Variable values can also be shared through to other tags (e.g., add purchase_total into the value field of a tag).

Refer to Google's GTM developer guide for comprehensive details on how the data layer works.

Example of a data layer:

window.dataLayer = window.dataLayer || []

window.dataLayer.push({
'email':'jenny.smith@rokt.com',
'user': {
'firstname' : 'Jenny',
'lastname' : 'Smith'
},
'ecommerce': {
'transaction': {
'amount' : '12.36'
}
},
'event':'gtm.transactionComplete'
});

Identify your variable names

Variables are set up in your GTM account and are matched to the data layer. Refer to the GTM developer guide for more details about variables.

The structure of your data layer on your page affects the data layer variable name in your GTM.

Example data layer script 1:

window.dataLayer.push({
'email':'jenny.smith@rokt.com'
});

Data layer variable name: email

Example data layer script 2:

window.dataLayer.push({
'user': {
'firstname' : 'Jenny'
}
});

Data layer variable name: user.firstname

Example data layer script 3:

window.dataLayer.push({
'ecommerce': {
'transaction': {
'amount' : '12.36'
}
}
});

Data layer variable name: ecommerce.transaction.amount

Create your variables in Google Tag Manager

  1. Log in to your Google Tag Manager container.
  2. Click Variables.
  3. Under User-defined variables, click New.
  4. Enter a name for your variable.
  5. Click Choose a variable type to begin setup...
  6. Under Page Variables select Data Layer Variable.
  7. Enter the Data Layer Variable Name. See the examples above to identify the variable name based on your data layer structure.
  8. Click Save.

Rokt suggests creating variables for the following attributes:

  • email
  • firstname
  • lastname
  • mobile
  • age
  • gender
  • billingaddress1
  • billingaddress2
  • confirmationref
  • billingzipcode
  • amount
  • paymenttype
  • ccbin
  • country
  • language
  • currency

Create your tags

You will need to create individual tags to handle each of the core functions of the Rokt SDK, including:

  • Initializing the Rokt SDK
  • Identifying your users
  • Logging page views
  • Inserting a placement

You must also configure specific triggers that define when these tags are executed, as described in the instructions for each tag below.

caution

For identify, page view, and insert placement tags, use distinct triggers that occur after initialization. Avoid assigning the exact same trigger to multiple Rokt tags to prevent them from executing simultaneously. The initialization script pushes a custom event roktInitComplete to the data layer when initialization completes. Use this event in triggers for subsequent Rokt tags.

Initialize the Rokt SDK

To create a tag to initialize the SDK:

  1. Log in to your Google Tag Manager Container, and click Tags in the left hand navigation.
  2. Click New and select Tag Configuration. Google Tag Manager
  3. Select Tag Configuration and under Custom, select Custom HTML Tag.
  4. Enter a descriptive name for your tag, like "Initialize Rokt".
  5. In the HTML entry field, paste in the following snippet:
<script type="text/javascript">

// Enter your Rokt API key
var API_KEY = "YOUR_API_KEY";

// If you configured a first-party domain, set it as the value of DOMAIN instead of the default apps.rokt-api domain
var ROKT_DOMAIN = "https://apps.rokt-api.com";


// Specify the data environment with isDevelopmentMode:
// Set isDevelopmentMode to true if you are still testing your integration.
// Set isDevelopmentMode to false if your integration is ready for production data.
var isDevelopmentMode = true;

// Set your SDK configuration settings
window.mParticle = {
config: {
isDevelopmentMode: isDevelopmentMode,
logLevel: isDevelopmentMode ? 'verbose' : 'warning',
// Set useCookieStorage to true if your site uses multiple sub-domain (ie. mysite.com & checkout.mysite.com). Default value is 'false'.
useCookieStorage: 'false',
// Identify the current user:
// If you have the user's email address at the time of initialization, include it in an object called `userIdentities` within `identifyRequest` as shown below. If not, you can remove the identityRequest object.
identifyRequest: {
userIdentities: {
// Make sure to replace the sample variable {email} with the variable you create to store your user's email
email: {{email}},
// Hashed email addresses should be passed into the `other` field
other: {{hashed-email}}
},
}
},
};

// Load the SDK
(function(e) { window.mParticle = window.mParticle || {}; window.mParticle.EventType = { Unknown: 0, Navigation: 1, Location: 2, Search: 3, Transaction: 4, UserContent: 5, UserPreference: 6, Social: 7, Other: 8, Media: 9 }; window.mParticle.eCommerce = { Cart: {} }; window.mParticle.Identity = {}; window.mParticle.Rokt = {}; window.mParticle.config = window.mParticle.config || {}; window.mParticle.config.rq = []; window.mParticle.config.snippetVersion = 2.6; window.mParticle.ready = function(e) { window.mParticle.config.rq.push(e); }; ["endSession", "logError", "logBaseEvent", "logEvent", "logForm", "logLink", "logPageView", "setSessionAttribute", "setAppName", "setAppVersion", "setOptOut", "setPosition", "startNewSession", "startTrackingLocation", "stopTrackingLocation"].forEach(function(e) { window.mParticle[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift(e); window.mParticle.config.rq.push(t); }; }); ["setCurrencyCode", "logCheckout"].forEach(function(e) { window.mParticle.eCommerce[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("eCommerce." + e); window.mParticle.config.rq.push(t); }; }); ["identify", "login", "logout", "modify"].forEach(function(e) { window.mParticle.Identity[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("Identity." + e); window.mParticle.config.rq.push(t); }; }); ["selectPlacements","hashAttributes","setExtensionData"].forEach(function(e) { window.mParticle.Rokt[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("Rokt." + e); window.mParticle.config.rq.push(t); }; }); var t = window.mParticle.config.isDevelopmentMode ? 1 : 0, n = "?env=" + t, a = window.mParticle.config.dataPlan; if (a) { var o = a.planId, r = a.planVersion; o && (r && (r < 1 || r > 1e3) && (r = null), n += "&plan_id=" + o + (r ? "&plan_version=" + r : "")); } var i = window.mParticle.config.versions, s = []; i && Object.keys(i).forEach(function(e) { s.push(e + "=" + i[e]); }); var c = document.createElement("script"); c.type = "text/javascript"; c.async = !0; window.ROKT_DOMAIN = ROKT_DOMAIN || 'https://apps.rokt-api.com'; mParticle.config.domain = ROKT_DOMAIN.split('//')[1]; c.src = ROKT_DOMAIN + "/js/v2/" + e + "/app.js" + n + "&" + s.join("&"); var l = document.getElementsByTagName("script")[0]; l.parentNode.insertBefore(c, l); })(API_KEY);

window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ event: 'roktInitComplete' });
</script>
note

The initialization script pushes a custom event roktInitComplete to the data layer when initialization completes. Use this event in triggers for subsequent Rokt custom tags.

  1. Enter your configuration settings:
    • Replace YOUR_API_KEY with the API key provided to you by your Rokt account manager.
    • If you are ready to use your tag for production data, set isDevelopmentMode to false. Leave this set to true if you are still testing your tag.
    • Make sure email is set to the variable you created to store your user's unhashed email address. In the example snippet above, the variable name is {email}.
  2. In the Triggering menu, click the + button to configure a trigger or select one from the options available.
  3. Select All Pages to ensure the initialization tag fires on all pages, and add any exceptions if necessary.
  4. Click Save.

Identify the User

You should also create a tag that identifies the current user to Rokt. Make sure to include this tag in your site so it is fired as soon as the user provides their email address.

  1. Click Tags in the left hand navigation from your Google Tag Manager Container.
  2. Click New and select Tag Configuration. Under Custom, select Custom HTML Tag.
  3. Enter a descriptive name for your tag, like "Identify User".
  4. In the HTML entry field, paste in the following snippet:
<script type="text/javascript">

window.mParticle.ready(
function() {
var identifyRequest = {
userIdentities: {
// If you're using a raw, un-hashed email, pass it into the `email` field
email: {{email}},

// If you're integrating hashed email, pass it into the `other` field instead
other: {{hashed-email}}
}
};
mParticle.Identity.identify(identifyRequest);
}
);

window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ event: 'roktIdSyncComplete' });

</script>
  1. If you are sending the user's raw, unhashed email address to Rokt, set the key as email. If you are sending the hashed email address, set the key as other. Make sure to replace the example variable names ({{user.email}} and {{user.hashed-email}}) with the data layer variables you created to store your user's email address.

  2. Configure a trigger to fire this tag as soon as the user provides their email address. The trigger you use will depend on your specific integration, but (as an example), you could create a trigger that fires the tag when a user provides an email address via a form submission:

    • From Trigger Configuration, select Form Submission Email.
    • Click into the trigger to reach the Trigger Configuration page, then click the edit icon.
    • Under This trigger fires on, select Some Forms.
    • Select the data layer variable you created to store your user's email address.
    • For the condition, select matches RegEx and enter the regular expression .+@.+\..+.

    Google Tag Manager

caution

The exact trigger configuration you use for the identify user tag will depend on your integration. Additionally, ensure the initialization tag fires before the identify tag. If you have questions about how best to implement this tag so that your users are successfully identified before logging events, speak to your Rokt account manager.

note

The identify script pushes a custom event called roktIdSyncComplete to the data layer after a successful identify call. You can use this event to trigger subsequent tags.

Log Page Views

You should log page views as soon as each page in the user's transaction journey is loaded. To create a tag to log a page view:

  1. Click Tags in the left hand navigation from your Google Tag Manager Container.
  2. Click New and select Tag Configuration. Under Custom, select Custom HTML Tag.
  3. Enter a descriptive name for your tag, like "Log Page View".
  4. In the HTML entry field, paste in the following snippet:

<script type="text/javascript">

// Wait for the SDK to be fully loaded before logging the event
window.mParticle.ready(function() {
mParticle.logPageView(
// Event name: "page view" identifies the type of event being logged
"page view",
{
// Capture the last segment of the URL path as the screen name,
// e.g., "/products/shoes" → "shoes". Defaults to "home" if the path is empty.
"screen_name": location.pathname.split("/").filter(Boolean).pop() || "home",

// Record the full URL of the current page (including protocol, path, query, and hash)
"url": window.location.toString(),

// Capture the URL of the page that referred the user to this one,
// if available. This helps track user navigation between pages or sites.
"referring-page": document.referrer
}
);
});

</script>

The logPageView method takes two arguments:

Page Name: a string for the name of the page being loaded

Custom Attributes: an object of key/value pairs containing information about the page

The page name field should be set to a generic page name. For example, an ecommerce website could have hundreds of product detail pages. To log these correctly, you should use a generic name (e.g. "Product Detail Page") and then log the url and other attributes of the page as attributes.

  1. Configure a trigger so that this tag is fired on every page in the conversion funnel (after the initialization tag).
note

It is recommended to either combine the initialization & log page view into one tag that fires on all pages or use the roktInitComplete custom event trigger on all pages.

caution

The exact trigger configuration you use for the log page views tag will depend on your integration. Additionally, ensure the initialization tag fires before the log page views tag. If you have questions about how best to implement this tag so that your pages are logged correctly, speak to your Rokt account manager.

Insert a Placement

In addition to creating a tag to initialize the ROKT SDK, Rokt ecommerce integrations also require a tag to insert placements.

  1. Click Tags in the left hand navigation from your Google Tag Manager Container.
  2. Click New and select Tag Configuration. Under Custom, select Custom HTML Tag.
  3. Enter a descriptive name for your tag, like "Insert Placement".
  4. In the HTML entry field, paste in the following snippet:
<script type="text/javascript">

window.mParticle.ready(
function() {
var selection = window.mParticle.Rokt.selectPlacements({
identifier: "yourPageIdentifier",
attributes: {
"email": {email},
"firstname": {user.firstname},
"lastname": {user.lastname},
"mobile": {user.mobile},
"age": {user.age},
"gender": {user.gender},
"billingaddress1": {user.billingaddress1},
"billingaddress2": {user.billingaddress2},
"confirmationref": {ecommerce.transaction.confirmationref},
"billingzipcode": {ecommerce.transaction.billingzipcode},
"amount": {ecommerce.transaction.amount}, // Decimal transaction amount e.g. 300.5
"paymenttype": {ecommerce.transaction.paymenttype}, // E.g. Gift card | Chase, Visa
"ccbin": {ecommerce.transaction.ccbin}, // Credit card bin e.g. 372888
"country": {ecommerce.transaction.country}, // ISO Alpha-2 Country Code
"language": {ecommerce.transaction.language}, // ISO 639-1 2 letter lanugage code
"currency": {ecommerce.transaction.currency}, // Transaction currency e.g. USD
// You can also pass extra attributes relevant to the transaction here
// For a full list of attributes, see https://docs.rokt.com/developers/integration-guides/rokt-ads/web-sdk/attributes#core-attributes
shippingtype: {ecommerce.transaction.shippingtype}
}
});
}
);

</script>
  1. Set each attribute you want to forward to Rokt in your selectPlacements call with the variable you created based on your site's data layer.

  2. To configure when the tag is triggered, select Triggering.

  3. Click the + button to add a new trigger.

  4. Click Trigger Configuration. The next steps vary depending on whether your site is a multipage application (MPA) or a single page application (SPA):

    • Trigger configuration for multipage applications

      1. Select Custom Event from the list.
      2. Enter roktInitComplete as the event name. If the user is not known until the insert placement event, use roktIdSyncComplete as the event name instead of roktInitComplete.
      3. Change the trigger firing rules to Some Custom Events.
      4. Enter the URL parameter(s) that identify each unique page where the tag should fire. For example, if your confirmation page is example.com/cart/payment/confirmation the identifying parameter can be any of cart, payment, or confirmation.

      Google Tag Manager

      note

      If the user is not known until the conversion event, use the Custom Event roktIdSyncComplete as the event trigger.

    • Trigger configuration for single page applications

      1. Select History Change from the list.
      2. Change the trigger firing rules to Some History Changes.
      3. Enter the URL parameter that identifies the page where the tag should fire. For example, if your confirmation page is example.com/cart/payment/shipping the identifying parameter can be any of cart, payment, or shipping.
  5. Click Save.

Was this article helpful?