Google Analytics Ecommerce Tracking 3-Step Implementation Tutorial

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
12 years ago
The first part provides some additional information about the implementation itself. For the actual implementation tutorial skip it and go directly to "II. The 3-Step Implementation Tutorial", though I recommend you read the first part.

---------------------
I. Introduction
---------------------

Today, I had to implement Google Analytics Ecommerce Tracking for a client running nopCommerce 1.6.

I discovered that the implementation guides posted on this forum have some small errors, and most importantly, cause trouble(e.g. duplication and double counting) for stores that already have other Google Analytics code running on all their pages(e.g. Root.Master like my client); so I decided to share my implementation which avoids those problems:

From now on, I will use GA, to refer to Google Analytics throughout the tutorial.

Let's say you have put your GA asynchronous script block just before the closing </head> tag in your Root.Master file. Something like this:


<script type="text/javascript">

   var _gaq = _gaq || [];
   _gaq.push(
      ['_setAccount', 'UA-XXXXXXX-X'],
      ['_trackPageview']
      );

   (function()
   {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
   })();
    
</script>
</head>


If you have put it anywhere else, move it there for optimum performance per Google's recommendation, it will improve your page load times which is critical for all online stores. Also make sure you are using the Asynchronous version of the GA script, not the traditional one.

If your setup is like this and you have the GA tracking code running on all pages, you shouldn't render another GA script block on the CheckoutCompleted page for ecommerce tracking because that would unnecessarily slow down your page and cause duplicate data to be posted to GA. To avoid those issues, we have to build and dynamically inject our GA ecommerce tracking JavaScript code into the existing GA script block, and we will use a Literal ASP.NET Control to achieve that.


----------------------------------------------------
II. The 3-Step Implementation Tutorial
----------------------------------------------------

1. Insert this line into your existing GA script block just after the last _gaq.push method call:

<asp:Literal runat="server" ID="litGAEcommerceTracking" />


Now, your GA script block should look like this:


<script type="text/javascript">

   var _gaq = _gaq || [];
   _gaq.push(
      ['_setAccount', 'UA-XXXXXXX-X'],
      ['_trackPageview']
      );
<asp:Literal runat="server" ID="litGAEcommerceTracking" />
   (function()
   {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
   })();
    
</script>



2. Now open CheckoutCompleted.ascx.cs and paste this code into the class block:



protected override void OnPreRender(EventArgs e)
{
  if(SettingManager.GetSettingValueBoolean("GA.EcommerceTrackingEnabled"))
  {
    AddGAeCommerceTrackingToHead();
  }
  base.OnPreRender(e);
}

private void AddGAeCommerceTrackingToHead()
{
  Literal litGoogleAnalytics = (Literal)this.Page.Header.FindControl("litGAEcommerceTracking");
  litGoogleAnalytics.Text = BuildGATrackingScript();
}

// builds dynamic Google Analytics ecommerce tracking JavaScript using the completed order's details
private string BuildGATrackingScript()
{
  StringBuilder sb = new StringBuilder();

  Order lastOrder = LastCustomerOrder;
  if (lastOrder != null)
  {
    // transaction data
    string addTransComposite = "_gaq.push(['_addTrans', '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}']);";
    sb.AppendFormat(addTransComposite, lastOrder.OrderId, SettingManager.StoreName, lastOrder.OrderTotal.ToString("F2"), lastOrder.OrderTax.ToString("F2"), lastOrder.OrderShippingInclTax.ToString("F2"), lastOrder.BillingCity, lastOrder.BillingStateProvince, lastOrder.BillingCountry).AppendLine();

    // purchased items data
    string addItemComposite = "_gaq.push(['_addItem', '{0}', '{1}', '{2}', '{3}', '{4}', '{5}' ]);";
    foreach (OrderProductVariant item in lastOrder.OrderProductVariants)
    {
      sb.AppendFormat(addItemComposite, lastOrder.OrderId, item.ProductVariant.SKU, item.ProductVariant.FullProductName, string.Empty, item.UnitPriceInclTax.ToString("F2"), item.Quantity).AppendLine();
    }

    // send data to GA
    sb.AppendLine("_gaq.push(['_trackTrans']);");
  }
  return sb.ToString();
}

protected Order LastCustomerOrder
{
  get
  {
    return NopContext.Current.User.Orders.Count > 0 ? NopContext.Current.User.Orders[0] : null;
  }
}


Also, make sure all required namespaces are imported at the top of the class file:


using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement;
using NopSolutions.NopCommerce.BusinessLogic.Orders;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings;


3. After rebuilding nopCommerce, go to http://www.YOURSTOREADDRESS.com/administration/settings.aspx and add this setting:


Name: GA.EcommerceTrackingEnabled
Value: true


You're done.

~Saeb
12 years ago
Ecommerce tracking functionality will be available in the upcoming version 2.50 out of the box. Please see changeset b9e5b11bca3c
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.