## Optimizely Content Management System and Optimizely Customized Commerce
Google Analytics for Optimizely gives you instant access to analytics and trends within your working website context, allowing you to take immediate actions to improve conversions and optimize traffic.

### Requirements
No additional license fee.
An Optimizely Content Management System (CMS) or Optimizely Customized Commerce installation.
[Google Analytics license and account](🔗).
See [Add-ons platform compatibility](🔗) for package and version information.
### Install
Versions 7.5 and higher are [installed through NuGet](🔗).
Version 7 is installed and updated through one-click installation.
Lower versions are available as zip files for [download](🔗).
## Optimizely Campaign
### Requirements
[Google Analytics license and account](🔗).
An Optimizely Campaign client.
[Contact Optimizely](🔗) to set up the integration in Optimizely Campaign.
## Configure Google Analytics for Optimizely
This section describes how to set up Google Analytics for Optimizely to instantly connect to the tracked data. You can also set up the add-on so that editors and marketers can follow the statistics on the dashboard for the entire website and in edit view for each individual page.
You can choose between the built-in options **Classic Google Analytics** or **Google Universal Analytics** when configuring the add-on. You can also add a _**custom script**_ instead to support, for example, Google Tag Manager.
You have the following options to configure Google Analytics for Optimizely to analyze the statistics:
On the Google Analytics website by configuring your Google Analytics account.
In Optimizely admin view by configuring both the **Configure Tracking** and **Configure Analytics Gadget** tabs, and adding the gadget to the dashboard.
Note
Custom tracking scripts need to be tested in advance to verify that they work as intended.
### Get started
Get started with Google Analytics for Optimizely in the user interface as follows:
From the top menu, access Google Analytics for Optimizely by selecting **CMS** > **Admin** > **Config** > **Tool Settings** > **Google Analytics**. The summary shows status about your current tracking and gadget settings.
Set up tracking through the Google account and Tracking ID for your organization.
Already have an existing Google account. Use the Tracking ID for configuration in Optimizely CMS admin view.
Have no Google account. Create a Google account by registering your website at the [Google Analytics website](🔗). Follow the instructions on the website to generate the tracking code containing a Tracking ID. Use the Tracking ID for configuration in Optimizely CMS admin view.
### Configure tracking
#### Configure roles
The virtual roles **GoogleAnalyticsReaders** and **GoogleAnalyticsAdministrators** to authorize editors to the gadget and administrators to the admin view, are added to the website context (in the InitializationModules). These roles are mapped as follows:
You can exclude a group from the map of these roles by changing the options in **EPiServerFramework.config** \> **episerver.framework** > **virtualRoles** > **providers**.
Note
You must manually declare these required roles and assign them to the approriate accounts for websites (such as QuickSilver) with a claims security provider (such as Federated Identity or AspNet Identity).
#### Add tracking on your website
On the **Configure Tracking** tab, you can control which tracking information about your visitors is sent to Google Analytics.

Configure the tracking of your website as follows and save the settings:
Select the **Configure Tracking** tab.
Select one of the following about what you want to track:
**Share tracking ID for all sites** means that you track all websites using the same Tracking ID . All websites in an enterprise installation will use the same Tracking ID.
**Use a unique tracking ID for each site** means that you track each website specifically by using an unique Tracking ID for each website in an enterprise installation. You need to configure Tracking ID and settings on each site’s tab.
In **Tracking ID**, connect your Tracking ID to your website (you can find it under your Google Analytics settings page). The Tracking ID has the format UA-#####-#.
In **Script options**, select one of the following tracking methods:
**Google Classic Analytics** will generate snippets that uses the classic syntax corresponds to the ga.js library. You cannot modify the generated tracking script added to the pages header with this option.
**Google Universal Analytics** will generate snippets that uses the universal syntax corresponds to the analytics.js library. You cannot modify the generated tracking script added to the pages header with this option.
**Custom Tracking Script** will generate a custom tracking script code. Selecting this option will open a text area to enter the custom tracking script code. The custom script can include a {id} “tracking ID place holder” to be replaced by the value entered in the Tracking ID option. Example: `
<script source="ga.js?id={id}" ></script>
` will add the custom script to pages header, for example, `<script source="ga.js?id=UA-52745929-1" ></script>
`.
On the **Domains** tab, select one of the following options (to see how these options are generated in code, refer to [Customize tracking and e-commerce](🔗)):
**A single domain** – Track a single domain with the Tracking ID.
**One domain with multiple subdomains** – Track one domain with multiple subdomains with the Tracking ID.
**Multiple top-level domains** – Track multiple domains with the same Tracking ID.
On the **Roles** tab, select one of the following options:
**Track selected roles** – Renders tracking only for users in the selected roles.
**Track everything except for selected roles** – Renders tracking for all visits except for visits by users with the selected roles.
On the **Links & Downloads** tab, select one or several of the following options:
**Track clicks on external links** – Tracks clicks on external links. All links with a link “http” or “https” that is not the same domain are considered to be external links. By selecting Track clicks on external links as page views you can track external links and convert them to virtual links as page views on the site, starting with “/external/”.
**Track clicks on e-mail links** – Tracks clicks on e-mail links (containing mailto tags).
**Track clicks on download links** – Tracks clicks on file download links with the extensions defined in the pipe-separated list (|). The list of extensions is not case sensitive.
On the **Users & Interaction** tab, select one or several of the following options:
**Track logins** – Tracks logins on the website as an event.
**Track visitor groups** – Tracks users who match a visitor group as an event. To make this work, the **Statistics** check box needs to be selected for the visitor groups on your website.
**Track form postings** – Tracks form postings as an event (XForms).
**Track authors** – Tracks a user creating a page as a custom property.
Note
Do not mix **Ecommerce** and **Enhanced Ecommerce** tracking on your pages. If you want to track e-commerce events, make sure your UA account has Ecommerce tracking enabled.
### Connect the gadget to Google Analytics
You can view the analytics on the dashboard by connecting the gadget to Google Analytics as follows:
Select the **Configure Analytics Gadget** tab.
Connect the Optimizely website with Google Analytics by clicking the **Log in** button.
Select which user groups that are allowed to access the analytics.
In **Google Analytics Authentication**, log in to the Google Analytics account with valid login credentials for your organization.
Save the settings.
Add the gadget to the dashboard and/or in the CMS edit view.
## Customize tracking
The Google Analytics for Optimizely contains built-in metrics, but you also can develop custom metrics through attributes and code. This topic describes how to extend the Google Analytics for Optimizely add-on and what data to track, integrated with a Optimizely CMS website and Optimizely Commerce, using both Google services standard Ecommerce and Enhanced Ecommerce tracking.
Note
If you intend to extend the add-on through the APIs, you need to install it from the NuGet feed into Visual Studio.
### Technical overview
From a technical perspective, the Google Analytics for Optimizely Add-on is responsible for querying the Google Analytics REST API to present data in the dashboard and page-specific gadget in edit view and to render the tracking JavaScript to the pages on the site.
The **metric factory** aggregates metrics and define lists and graphs in the gadget.
The **gadget data repository** combines metrics to build Google queries.
The **Optimizely query helper** provides access to Google API authenticated with Optimizely.
Google data is built up through tracking script on the website. The GData API is the Google C# client API to query analytics data. Google data can be queried directly using **Google API. Optimizely** is reusing authentication data.
#### Code generated from admin view
When configuring the domains to track in admin view, the following code is generated:
**A single domain** – Track a single domain with the Tracking ID. No **setDomainName** command is rendered to tracking code.
**One domain with multiple subdomains** – Track one domain with multiple subdomains with the Tracking ID. The **setDomainName** command is rendered with stripped-first-domain-segment of current **Request.Url.Authority**, if the remaining part after it has been stripped still is a valid domain authority.
A page view (to a.epi.com, b.epi.com, c.epi.com) is set up as shown in the following example: `
_gaq.push(['_setDomainName', epi.com']);
`A page view (to a.epi.com:8080, b.epi.com:8080, c.epi.com:8080) is set up as shown in the following example: `
_gaq.push(['_setDomainName', epi.com:8080']);
`A page view (to a.demo.epi.com, b.demo.epi.com, c.demo.epi.com) is set up as shown in the following example: `
_gaq.push(['_setDomainName', demo.epi.com']);
`An unchanged page view (to epi.com) is set up as shown in the following example: `
_gaq.push(['_setDomainName', epi.com']);
`
**Multiple top-level domains** – Track multiple domains with the same Tracking ID.
A page view (to epi.com, epi.net, epi.org) is set up accordingly as shown in the following example: `
_gaq.push(['_setDomainName', epi.com']); _gaq.push(['_setDomainName',epi.net]); _gaq.push(['_setDomainName', epi.org]);
`
### Customize tracking with ClientResourceRegister
The Optimizely Google Analytics add-on uses a `ClientResourceRegister
` class to add the necessary Google Analytics JavaScript to the header of the page. If you use MVC, make sure you have the following code somewhere in your head tag:
`@Html.RequiredClientResources(EPiServer.Framework.Web.RenderingTags.Header)
`
If you do not use the `RequiredClientResources
` registration, you need to render the script yourself, see **Rendering the script manually**.
You can extend the generated script by adding `AnalyticsInteraction
` objects or using a class implementing the `IPluginScript
` class registered with the service locator.
`AnalyticsInteraction
` is a class that allows registering Google Analytics events and actions. The interactions are typically page specific and there are Extension methods on the **HttpContext** and **HttpContextBase** classes to help you add them. Example:
`HttpContext.AddAnalyticsEvent("button", "click", "nav buttons", 4, clearWhenContextChanged: true);
`
This renders the following script:
`ga('send', 'event', 'button', 'click', 'nav buttons', 4);
`
With an `IPluginScript
` class, you can also add custom JavaScript to all pages from one place, see example in [Setting the currency](🔗).
In summary, the add-on will render something like this (for Universal Analytics Tracking):

### Override the script generation with custom tracking

The class responsible for rendering the script to the page is the `GASyntax
` class, which has support for the following:
Google Analytics Classic tracking mode
Google Analytics Universal tracking mode
A completely custom mode
If you are starting implementing tracking from the beginning, you should select to use the Google Analytics Universal mode. If you have an existing Google Analytics account that cannot be upgraded, you should go with the Classic mode.
You do not have to change to custom mode to extend the Classic or Universal modes, you can add your own script using `AnalyticsInteractions
`. If the selected renderer does not fulfil the need, but the mode does (Classic or Universal), you can register your own implementation using the Service Locator:
`context.Container.Configure(c => c.For<UniversalSyntax>().Use<MyCustomUASyntax>());
`
### Render the script manually
In case you need more control over the script rendering you can get the script code directly using one of the extension methods in the `EPiServer.GoogleAnalytics.Helpers.Extensions
` class.
Use `public static string GetAnalyticsTrackingScript(this PageBase page, HttpContext context)
`
This returns the Google Analytics script based on the configured syntax (Classic or Universal Analytics).
You can also build the following script:
Note
If you render the script manually, and still have the `
RequiredClientResource
` registration for `Header
`, use the “Custom Tracking Script” setting for the add-on, or you will get two tracking scripts on your page.
## Customize e-commerce tracking
With the Google Analytics Universal Tracking, you have the following options for tracking e-commerce actions and data:
**[Ecommerce Web Tracking](🔗)** (standard)
**[Enhanced Ecommerce Web Tracking](🔗)**
The Enhanced Ecommerce tracking option is the most feature rich, and if you do not have any existing Ecommerce tracking implemented, you should use the Enhanced Ecommerce tracking.
You should not use both Ecommerce tracking and Enhanced Ecommerce tracking at the same time.
In contrast to tracking page views, all e-commerce tracking require more data to be sent. Because Optimizely Customized Commerce implementations vary, and there is no standard cart or checkout page, the Google Analytics for Optimizely add-on cannot add e-commerce tracking script automatically to the page. It will help you generate the correct script, but you will have to add it to the relevant pages in your solution.
### Track a product detail view
The [Google Analytics documentation](🔗) shows in the following example how the script should look:
The script above includes the Enhanced Ecommerce plugin `(ga('require', 'ec');)
`, prepares the data, indicate what action it is tracking and sends that in addition to the page view itself in one go to the Google Analytics servers.
With the Google Analytics add-on, each script line is an `AnalyticsInteraction
`, and you can add these using `HttpContext
` and `HttpContextBase
` extension methods. In the following code, the `addProduct
` activity is populated using a dictionary that holds the required values and added using the `AddAnalyticsCustom
` extension method.
Call it from your controller (or Web Form) as follows:
`TrackProductDetail(HttpContext.Current, "P12345", "Android Warhol T-Shirt", "Apparel", "Google", "black", 0);
`
The “true” parameter in the call to `AddAnalyticsCustom
` tells the script generator to remove the interaction after the script has been generated for the request. If you set it to false, the interaction is added to the session, and rendered on subsequent requests to all pages. You should put global settings into a `IPluginScript
` class instead, as the order of the interactions will be hard to predict across page requests.
The project is using a custom `IPluginScript
` that registers `ga('require', 'ec');
` for all requests, which is included on pages just after the `ga('create', 'UA-XXXXX-Y');
` call. You do not have to generate these script lines from your controller code, see [Setting the currency](🔗).
The last step is to send it all off, and since that will be done using the standard page view command, you do not have to include that the script, the add-on will always end the script block with the `ga("send", "pageview");
` command.
### Track the checkout
A checkout process typically ends with a “Thank you” page. This is a good place to track purchases with Google Analytics. If the checkout ends with a redirect to that page, it can retrieve the order number and track it using an extension method on `HttpContext
` as shown in the example below.
This example renders script using the Ecommerce, not the Enhanced Ecommerce syntax. If you configured your account to use Enhanced Ecommerce syntax, go to the Tracking the checkout using Enhanced Ecommerce syntax section.
These examples are referring to the Optimizely Customized Commerce Sample templates.
In the Optimizely Customized Commerce sample website, the following happens after the checkout has been done:
Logged customers are redirected to the **Order** administration page.
Anonymous customers are redirected to the **CheckoutConfirmationStep** page.
The following example is for the anonymous use case, which is redirected to the **CheckoutConfirmationStep** page (you should add the example code for logged in users in _Order.aspx_ and _Order.aspx.cs_).
Example of tracking using server code:
Edit the _CheckoutConfirmationStep.aspx.cs_ file.
Add the following string directive on the top of file:
`
using EPiServer.GoogleAnalytics.Commerce.Helpers;
`Add the following code to **Page\_Load**:
<!----->
Build the project, perform a purchase, and you should start seeing transaction data in Google Analytics reports.
The `
AddAnalyticsTransaction
` method detects which Google Analytics tracking mode that is being used, and will render the correct script for both Classic and Universal Analytics using the Ecommerce plugin.
Note
You do not have to add the `
ga('require', 'ecommerce');
` script, as this will be automatically by the `EPiServer.GoogleAnalytics.Commerce
` assembly through the `CommercePluginScript
` class.
### Track the checkout using the Enhanced Ecommerce syntax
The following example uses the **Enhanced Ecommerce** library for Google Analytics and the examples below refer to the Optimizely Commerce sample templates.
First create a new `
IPluginScript
` class to render the `ga('require', 'ec');
` script before any other custom Google Analytics script on the page.Register the class with the Service Locator to override the default behavior from the `
CommercePluginScript
` class and add `ga('require', 'ecommerce');
` (which refers to the regular Ecommerce plugin and not the Enhanced Ecommerce plugin). Register the class with the Service Locator as follows:To make it easier to add the tracking to the page, add a helper class that knows how to render the correct Enhanced Ecommerce syntax as follows:
Use the new tracking methods in the **EPiServer.Commerce.Sample** template by calling `
TrackTransaction
` in _CheckoutConfirmationStep.aspx.cs_ as follows:
### Set the currency
If you run a multi-market website supporting different currencies for your customers, you need to track the products and transactions using the correct currency. Your Google Analytics account will have one default currency (USD if you have not changed it), and all tracking that do not specify the currency will use the default currency.
This is no problem if all your purchases are in the same currency, you can change the currency setting in the Google Analytics admin interface at any time. However, if you sell the same product in two different markets, and do not specify the currency, the Google Analytics reports for revenue will be wrong.
Setting the currency for a transaction is easy with Universal Tracking, and you can do this for all requests by using the currency for the current market. The easiest way is to create an `IPluginScript
` class that adds the currency.
The following example shows how to set currency based on the current market for the visitor, and also adds a “require” for the Enhanced Ecommerce plugin script:
Before the class above is used, you need to register the class as the `IPluginScript
` implementation to be used by the website:
This adds the following script lines after the initial tracking script:
`ga('require', 'ec');
`
`ga('set', '&cu', 'USD');
`
If you support several currencies for a single market, you may want to set the currency as an `AnalyticsInteraction
` on the page where you track Ecommerce related activities.
See also [Google Analytics documentation](🔗) about tracking currencies.