Google Analytics 360 Destination
MorphL makes it easy to send predictions to Google Analytics 360.
A common use case is predicting your website's visitors behaviour using Google Analytics 360 data, for example predicting when a visitor will add a product to the shopping cart.
This tutorial uses the Google Analytics 360 admin panel and other tools to:
- Create a custom dimension
- Generate a token for authenticating to the MorphL API
- Create a script for retrieving predictions and save them in your custom dimension
Prerequisites
Google Analytics 360 data source
This integration requires that your models use the Google Analytics 360 data source.
(Recommended) Google Tag Manager 360
Google Tag Manager 360 features close integration with Google Analytics 360. See the Google Tag Manager 360 doc for more details.
Sending predictions to a website or web app
Once predictions are available through the MorphL API, they can be consumed in a website or web application. The steps for integrating with the API are:
Generate authentication token
Using the API key and API secret created in the MorphL Dashboard, call the /authorize endpoint to generate an access token.
As a requirement for protecting the API credentials, the authentication request must be implemented in the backend.
Add custom dimension in Google Analytics 360
For tracking predictions associated with a Client ID, we use a custom dimension. This must be created from the Google Analytics 360 admin panel:

Create script for retrieving predictions
The predictions are retrieved from the MorphL API by sending the client id as a parameter. The client id is retrieved from the _ga cookie, which is set by the Google Analytics 360 tracking script.
Please see below a script that calls the MorphL API to retrieve predictions for the Shopping Stage Completeness ML model and processes the response:
function MorphlPredictions() {
var JSObject = this;
this.apiUrl =
"https://service.morphlapis.com/predictions/<account>/shopping_stage/get";
this.accessToken = "<jwt_token>";
this.cookieName = "morphl_shoppingstage";
this.gaCustomDimension = "<dimensionX>";
/**
* Initialize API call
*/
this.init = function() {
// Check if we already have a prediction in the browser cookie
var predictedShoppingStage = JSObject.getCookie(
JSObject.cookieName
);
if (predictedShoppingStage !== "") {
return;
}
// Make call to get prediction from the API
JSObject.getAPIPrediction();
};
/**
* Get a browser cookie
*
* @param string cname = The cookie name
* @return string = The cookie value or an empty string ("") if the cookie doesn't exist
*/
this.getCookie = function(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
};
/**
* Set a browser cookie
*
* @param string cname = The cookie name
* @param string cvalue = The cookie value
* @param string exhours = The expiration interval, in hours
*/
this.setCookie = function(cname, cvalue, exhours) {
var d = new Date();
d.setTime(d.getTime() + Number(exhours) * 60 * 60 * 1000);
var expires = "expires=" + d.toUTCString();
document.cookie =
cname +
"=" +
encodeURIComponent(cvalue) +
";" +
expires +
";path=/; secure";
};
/**
* Get the client id from the Google Analytics 360 cookie.
*/
this.getGoogleAnalyticsClientId = function() {
var gaCookie = JSObject.getCookie("_ga");
if (gaCookie === "") {
return null;
}
// Parse the _ga cookie value to the right format.
var lastElements = gaCookie.split(".").slice(-2);
if (lastElements.length == 2) {
return lastElements.join(".");
}
return null;
};
/**
* Interogate Morphl API and get the value of the prediction for the client ID.
*/
this.getAPIPrediction = function() {
// Set up our HTTP request
var xhr = new XMLHttpRequest();
// Setup our listener to process completed requests
xhr.onload = function() {
// Set a default value for the shopping stage
var shoppingStage = "n/a";
// Process response data
if (xhr.status == 200 || xhr.status == 404) {
// This will run when the request is successful
var morphlRes = JSON.parse(xhr.response);
// Validate the response received from the API
// Check if the client id has a valid prediction
if (
morphlRes &&
morphlRes.status &&
Number(morphlRes.status) == 1 &&
typeof morphlRes.shopping_stage === "number"
) {
// Get the shopping stage with the highest probability
var nextShoppingStage = Number(
morphlRes.shopping_stage
);
shoppingStage =
nextShoppingStage >= 0.5
? "add_to_cart"
: "all_visits";
}
// Set a cookie with the Morphl prediction value
JSObject.setCookie(JSObject.cookieName, shoppingStage, 2);
// Set the custom dimension with the prediction value
ga("set", JSObject.gaCustomDimension, shoppingStage);
// Send custom event
ga("send", "event", {
eventCategory: "morphlPrediction",
eventAction: "setPrediction"
});
}
};
var clientId = JSObject.getGoogleAnalyticsClientId();
if (clientId !== null) {
// Create and send the GET request
// The first argument is the post type (GET, POST, PUT, DELETE, etc.)
// The second argument is the endpoint URL
xhr.open(
"GET",
String(JSObject.apiUrl) +
"?client_id=" +
String(clientId)
);
xhr.setRequestHeader("Authorization", JSObject.accessToken);
xhr.send();
}
};
}
var morphlPredictions = new MorphlPredictions();
morphlPredictions.init();
Overview
The anatomy of the sample script is as follows:
- It assumes your activated ML models use Google Analytics 360 as a data source. For more details, see the Google Analytics 360 data source guide.
- It doesn't include authentication and assumes that a valid access token was already generated. This token should be set in the accessToken property.
- The value of the prediction is saved in the custom dimension created at Step 2 and in a cookie, identified by the cookieName property.
Parameters
The script parameters are:
- <account> represents your unique account number, which can be retrieved from the MorphL Dashboard.
- <jwt_token> is the JWT returned by the /authorize endpoint.
- <dimensionX> is the Google Analytics 360 custom dimension that will store the prediction value. Ex. Replace <dimensionX> with dimension3 (angular brackets are not required).
Add script from GTM or website source
The script can be loaded in a website using Google Tag Manager or it can be added as a custom script directly in the source of your website. Follow this guide to include it from GTM.
(Further development) Personalize user experience based on prediction values
After the above script has been added to your website, you can use the prediction values and personalize your users' experience - for example displaying different call-to-action pop-ups and messages depending on their probability to add a product to the shopping cart or their predicted LTV.
(Optional) Segment users in the Google Analytics 360 dashboard
Once the custom dimension has been defined and the predictions script has been added, users can be segmented in the Google Analytics 360 dashboard.
Creating a segment in Google Analytics 360
In the below image, you can see an example of creating a custom segment for users with a probability greater than 50% (0.5). For the Shopping Stage Completeness ML model, this probability represents how likely is a user to add a product to the shopping cart, start checkout or finalize a transaction.
Since we want these probabilities to have a Session scope, we can't use a custom metric (custom metrics can have only product or hit scope). The custom dimension uses a string format, so we must add multiple conditions to target all the values greater than 0.5.

Advanced targeting when using multiple ML models
In addition to being used individually, MorphL models can be combined for more advanced segmentation and targeting:

The above diagram outlines segments delimited by two models: Shopping Stage Completeness and Cart Abandonment. In this example:
- Hot means users that have a high probability of starting the add to cart > checkout process and a low probability of cart abandonment.
- Promising means users that have a high probability of starting the add to cart > checkout process and a high probability of cart abandonment.
For example, you can choose to target Promising users with discounts, free shipping, gifts, etc. by remarketing them or sending them personalized email notifications.
In Google Analytics 360, the above segments are defined as:
HOT users segment

Promising users segment

Another example would be creating personalized discount offers. By using the CLTV model, you are able to predict the value of a user's future orders and adjust a discount or voucher value accordingly. This prediction can be used in conjunction with the Shopping Stage Completeness value, for example by targeting mid-tier users who haven't yet made the purchase decision.
Please see the destinations catalog for more examples of using predictions.