Google Analytics Source

Compatible models

Shopping stage completeness
Cart abandonment
Customers LTV
Churning users
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.

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 Google Analytics 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. Optionally, we apply User IDs to identify logged in users across devices. Please see below the steps required for setting up custom dimenions in Google Analytics and creating API credentials for the Google Analytics Reporting API (v4).

Choose setup mode

MorphL offers two setup options for connecting Google Analytics:

  • Automatic setup. Requires both read and management permissions for Google Analytics. It automatically creates custom dimensions in your Google Analytics admin panel.

  • Manual (advanced) setup. Requires only read permissions for Google Analytics.

Connect Google Analytics source
Automatic setup In development

The automatic setup mode requires authenticating with the MorphL AI Google application with the following permissions:

Follow the steps below to connect Google Analytics.

  1. Log in to your MorphL account.
  2. From the left side menu, go to Data Sources.
  3. Select Google Analytics and press the Authenticate button.
    Dashboard - Activate Google Analytics
  4. You will be prompted to authenticate with your Google account and allow the permissions listed above.
  5. After you are redirected to the MorphL Dashboard, you can choose a Google Analytics account, property and view.
    Dashboard - Choose account, property and view
  6. At the next step, the Client ID and Session ID custom dimensions will automatically be created in the Google Analytics property you have chosen at the previous step. You can also enable the User ID dimension.

    In addition, a service account email address with Read & Analyze permissions will be added in the Google Analytics > Property User Management section of the same property.
    Dashboard - Enable dimensions
    In Google Analytics, your custom dimensions will look like this:
    Dashboard - Custom dimensions in Google Analytics
  7. At the 3rd step, you will be required to add values to the custom dimensions. The MorphL dashboard will provide detailed instructions for the platform of your choice. For example, if you choose Shopify, you will need to copy & paste a script in your Shopify admin panel.
    Dashboard - Add script
  8. Press the Finalize setup button to save and activate your data source.

Manage Google Analytics custom dimensions and Reporting API credentials
Manual setup

The manual (advanced) setup mode 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

The manual setup mode requires only the View your Google Analytics data scope.

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.
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" 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 "Set 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) (Optional) User ID

This variable is optional and should be used only when enabling the User ID custom dimension. From the Variables section, go to the User-Defined Variables section and click the New button. Add variable with the Data Layer Variable type and "Set User ID" title. Set Data Layer Variable Name to "UserID" and save it.

Add the following script in the source of your website and modify it to include users ids from your CMS.

<script>dataLayer.push({'UserID': '## Replace with User ID from your CMS ##'});</script>
d) Update Universal 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).

  • Check Enable overriding settings in this tag.
  • In the More Settings > Fields to Set section, set cookieDomain to auto and add a new field with the customTaskClientId name and Set Client ID value.
  • From More Settings > Custom Dimensions > Add Custom Dimension section, set the Index corresponding to your Session ID custom dimension and Dimension Value to Set Session ID.
  • (Optional) From More Settings > Custom Dimensions > Add Custom Dimension section, set the Index corresponding to your User ID custom dimension and Dimension Value to Set User ID.
Google Analytics Tag
Google Analytics Tag Trigger

Using Google Analytics script (gtag.js)

If the Google Analytics tracker is include directly in the source of your website, you can add the custom dimensions values by modifying the existing code.

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, dimension2 and (optionally) dimension3 with the actual dimensions indexes created at Step 1.

You can read more about adding the Client ID to a custom dimension with gtag.js.

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-Y"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    gtag('js', new Date());

    // Maps 'dimension1' to client id, 'dimension2' to session id and 'dimension3' to user id.
    gtag("config", "UA-XXXXXXXX-Y", {
        custom_map: {
            dimension1: "clientId",
            dimension2: "sessionId",
            dimension3: "userId", // Remove this line if you're not using the UserID custom dimension 
        }
    });

    // Sends an event that sets the dimensions
    gtag("event", "morphl_set_dimensions", {
        sessionId: new Date().getTime() + "." + Math.random().toString(36).substring(5)

        // Remove following line if you're not using the UserID custom dimension
        userId: '## Replace with User ID from your CMS ##'
    });
</script>

Using Google Analytics script (old version)

The gtag.js library is the recommended tag for new Google Analytics implementations. However, there may be cases where you would prefer to use analytics.js (e.g., your site already makes use of analytics.js).

In this case, 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, dimension2 and (optionally) dimension3 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));

    // Remove following line if you're not using the UserID custom dimension
    ga('set', 'dimension3', '## Replace with User ID from your CMS ##');
});
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. Click on Google Analytics and select the manual setup option.
    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