Google Analytics Source

Compatible models

Shopping stage completeness
Cart abandonment
Customers LTV
Churning users
Product recommendations
Customers segmentation
Next order value

MorphL makes it easy to import data from Google Analytics.

A common use case is predicting your website's visitors behaviour using this data, for example predicting when a visitor will add a product to the shopping cart.

This tutorial uses the Google Analytics admin panel, Google Developer Console and (optionally) Google Tag Manager to:

  • Create custom dimensions
  • Use Google Tag Manager or modify your Google Analytics tracker to add values to custom dimensions
  • Enable Google Analytics Reporting API v4
  • Create Google Analytics Reporting API v4 credentials

Prerequisites

Google Analytics website tracking ID

The Google Analytics source requires a Google account and website tracking ID. See the Google Set Up Analytics Tracking doc for instructions to create an ID.

Enhanced Ecommerce

The enhanced ecommerce plug-in for analytics.js enables the measurement of user interactions with products on ecommerce websites across the user's shopping experience, including: product impressions, product clicks, viewing product details, adding a product to a shopping cart, initiating the checkout process, transactions, and refunds. See the Enhanced Ecommerce doc for instructions.

(Recommended) Google Tag Manager

Google Tag Manager features close integration with Google Analytics. See the Deploy Google Analytics with Tag Manager doc for instructions.

Introduction

Google Analytics includes a series of reports, for example viewing a total of users and sessions from a particular date interval.

The free version of the Google Analytics Reporting API v4 doesn't export any client ids from the User Explorer report. However, it is possible to make these available by creating custom dimensions. This allows the analytics API to export data at the Client ID or Session level, instead of returning only aggregated data.

There are four distinct levels of aggregation that exist in Google Analytics but are not exposed via the API:

  • Hit timestamp - You can't query for the exact timestamp of a Google Analytics hit via the API. Hits include page views or custom events.

  • Session ID - Hits are grouped together into sessions. However, using the API alone, you will not be able to easily identify if two distinct hits belong to the same session.

  • Client ID - Sessions are bunched under a Client ID. Every instance of the _ga cookie gets a unique Client ID, which is how the Google Analytics backend knows that the same "User" has visited the site multiple times. In practice, the ClientID represents an anonymous visitor (browser). This Client ID is not exposed in any dimension you can query via the API.

  • User ID - The User ID feature in Universal Analytics groups together hits, sessions and Client IDs. It is the highest possible level of abstraction and aggregation available in Google Analytics.

MorphL ML Models use data at the Client ID and Session ID level. Please see below the steps required for setting up client ID and session ID tracking in Google Analytics and creating API credentials for the Google Analytics Reporting API (v4).

Create Google Analytics source

Create Custom Dimensions

From the Google Analytics admin panel, go to the Admin section. In the Property section, go to Custom Definitions > Custom Dimensions. Add the following dimensions:

  • ClientID with the User scope
  • SessionID with the Session scope
  • (Optional) UserID with the User scope. This custom dimension should be used only when connecting MorphL to other platforms, such as Shopify, Magento or WooCommerce.
a) Client ID

From the Custom Definitions section, go to the Custom Dimensions section and click the +New Custom Dimension button. Add the name "ClientID" and choose the User scope.

Google Analytics Client ID
b) Session ID

From the Custom Definitions section, go to the Custom Dimensions section and click the +New Custom Dimension button. Add the name "SessionID" and choose the Session scope.

Google Analytics Session ID
c) (Optional) User ID

From the Custom Definitions section, go to the Custom Dimensions section and click the +New Custom Dimension button. Add the name "UserID" and choose the User scope.

Google Analytics User ID

After adding all dimensions, your table will look similar to the below one.

Google Analytics Custom Dimensions

Set up client ID and session ID tracking

Please choose one of the options below - a) loading via Google Tag Manager or b) modifying the Google Analytics script.

Loading via Google Tag Manager

Go to the Google Tag Manager admin panel and follow the steps below. You can read more about using customTask to access tracker values in this tutorial.

a) Client ID

From the Variables section, go to the User-Defined Variables section and click the New button. Add the name "Set Client ID in Dimension 1" and choose the Custom JavaScript variable type.

Insert the code below and save it:

function() {
    // Modify customDimensionIndex to match the index number you want to send the data to
    var customDimensionIndex = 1;
    return function(model) {
        model.set('dimension' + customDimensionIndex, 'GA' + String(model.get('clientId')));
    }
}
Client ID
b) Session ID

From the Variables section, go to the User-Defined Variables section and click the New button. Add the name "Random Session ID" and choose the Custom JavaScript variable type.

Insert the code below and save it:

function() {
    return new Date().getTime() + '.' + Math.random().toString(36).substring(5);
}

This will create a random session ID.

Session ID
c) Google Analytics Custom Variable

From the Variables section, go to the User-Defined Variables section and click the New button. Add the name GASettings and choose the Google Analytics Settings variable type.

Set the Tracking ID value as your view ID from Google Analytics (should be something like UI-xxxxx-01) and set the Cookie Domain to auto.

Google Analytics Settings
d) Google Analytics Tag

It's time to put everything together. From the Tags section, create a new Universal Analytics tag or modify your existing Universal Analytics tag (you must have a single tag of this type).

Set the Google Analytics Settings to your custom GASettings variable and check the Enable overriding settings in this tag checkbox.

In the More Settings > Fields to Set section, set cookieDomain to auto and add a customTask field with the value of your Set Client ID in Dimension 1 custom variable.

In the More Settings > Custom Dimensions section, set index 2 with your Random Session ID custom variable.

Set the Trigger field to "All Pages".

Google Analytics Tag
Google Analytics Tag Trigger

Modifying the Google Analytics Tag

We recommend loading Google Analytics through Google Tag Manager, as described in the section above. However, if you decide to use the Google Analytics tracker instead, please follow the steps below.

Copy the following script and replace the view id (should be something like UI-xxxxx-01) to the one corresponding to your website. Also, replace dimension1 and dimension2 with the actual dimensions indexes created at Step 1. This script should be placed right before the closing <body> tag in the page:

(function (i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date();
    a = s.createElement(o), m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-XXXXXXXX-Y', 'auto'); // replace UA-XXXXXXXX-Y with your view id
ga(function (tracker) {
    ga('set', 'dimension1', 'GA' + String(tracker.get('clientId')));
    ga('set', 'dimension2', new Date().getTime() + '.' + Math.random().toString(36).substring(5));
});
ga('send', 'pageview');

(Only for Shopify merchants) Loading via the Shopify admin panel

From your Shopify admin panel, go to the Online Store > Preferences > Google Analytics section. Add the code below in the Additional Google Analytics JavaScript field. Make sure to replace dimension1, dimension2 and dimension3 with the actual dimensions indexes created at Step 1:

ga(function(tracker) {
    var clientId = "GA" + String(tracker.get("clientId"));
    ga("set", "dimension1", clientId);

    ga("set", "dimension2", new Date().getTime() + "." + Math.random().toString(36).substring(5));

    if (__st["cid"]) {
        ga("set", "dimension3", "shopify" + String(__st["cid"]));
    }
});

The code above will also link Shopify customers to their Google Analytics data when they authenticate. This enables you to associate predictions with Shopify customers and personalize your Shopify theme and marketing campaigns via our Shopify integration.

Create Google Analytics Reporting API credentials

The last part includes creating API credentials that can be used to authenticate to the Google Analytics Reporting API and access the data. The setup is done from the Google Developer Console.

Create Google Project and enable Google Analytics Reporting API

Click the button to the right of the logo. A window will open and you can press the "+" button to create a new project.

Create Project

From the Dashboard section, click the +ENABLE APIS AND SERVICES button.

Enable Reporting API 1

Search for Google Analytics Reporting API and enable it.

Enable Reporting API 2

At this point, we have enabled the API, but we also need to create credentials so we can access the data.

Create API credentials

Going back to the main page of the Google Developers console, go to the Credentials tab and click the Manage service accounts link. This will go to the IAM & Admin console, where you can click the +CREATE SERVICE ACCOUNT button. This will open the Create Service Account dialog. Add a name and select the Role or Project > Viewer.

Check the Furnish a new private key checkbox and choose the JSON format. After saving the form, a JSON file with the API credentials will be downloaded.

Create Service Account

Allow Access to Google Analytics Data

Now the Google project and API credentials are created, but we need one more step to allow read access for the service account to Google Analytics.

From Google Analytics, go to the Admin section. From the Account section, select User Management. Use the same email address that was added in the previous step (Service account ID). Uncheck Notify new users by email, uncheck Edit from the Permissions section below and save the new user.

Add Service Id

Add data source in the MorphL dashboard

  1. Log in to your MorphL account.
  2. From the left side menu, go to Data Sources.
  3. Select Google Analytics and activate it.
    Dashboard - Activate Google Analytics
  4. Enter the Google Analytics view id and select your custom dimensions for Client ID, Session ID and (optional) User ID.
    Dashboard - Add view id and custom dimensions
  5. Upload your Google Analytics Reporting API service account.
    Dashboard - Upload service account
  6. Verify your settings. If they are correct, the data source will be marked as Active and can be used for training models.
    Dashboard - Verify settings