Integrating Snipcart with Google Analytics Ecommerce Tracking

One question that is frequently asked is how to integrate Snipcart with third party analytics software such as Google Analytics.

We have a very powerful feature that is not yet documented but will soon be: it is our Javascript API. This feature allows you to interact with the cart and bind to some events. For example, you can hook to an event that will raise when an order is completed.

By using this, it is very easy to integrate Snipcart with any third party analytics. In this post, I will show you how to push the order details to Google Analytics Ecommerce Tracking.

Binding to Snipcart order.completed event

First of all, I will explain how you can bind to the event that will be raised when an order is completed.

Please note that all the code snippets above MUST be included AFTER snipcart.js file.

If you don't care about going through this step by step and just want to see some code then click here.

The public method we will use is bind, this method allows you to hook on some events that Snipcart will trigger. The event that we need for this particular case is order.completed.

Snipcart.execute("bind", "order.completed", function(order) {
  console.log(order);
});

So, if you include this code, when an order is completed on your website, it will log the order details in the console. Not very useful you will say, but it is helpful to understand how it works.

The order data that you will receive in the callback function is the following:

{
  "token": "7e8145e6-fde3-4f88-98d3-13795e1cd8f4",
  "grandTotal": 1000.00,
  "billingAddress": {
    "address1": "4885 1ere Avenue",
    "address2": "",
    "city": "Québec",
    "companyname": "Snipcart",
    "country": "CA",
    "email": "geeks@snipcart.com",
    "name": "Charles Ouellet",
    "phone": "",
    "postalcode", "G1H2T5",
    "province": "QC"
  },
  "shippingAddress": {
    "address1": "4885 1ere Avenue",
    "address2": "",
    "city": "Québec",
    "companyname": "Snipcart",
    "country": "CA",
    "name": "Charles Ouellet",
    "phone": "",
    "postalcode", "G1H2T5",
    "province": "QC"
  },
  "items": [{
    "id": "BACON",
    "name": "Bacon",
    "price": 10.00,
    "quantity": 2,
    "uniqueId": "da67adb4-e989-4c4f-809c-5d2573ab3d4e"
  },
  ...],
  "taxes": [{
    "amount": 0.05,
    "name": "TPS",
    "taxRate": 0.05,
    "numberForInvoice": "TAX_TPS"
  },
  ...]
}

Pushing data to Google Analytics

With all this information, it will be very easy to push everything needed by Google Analytics.

The first step will be to add Google Analytics to your website. You may already have it included, if so just skip this step.

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

(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);
})();

Then we will bind to the Snipcart order.completed event as explained earlier in this post.

Snipcart.execute("bind", "order.completed", function(order) {
});

We are now ready to push the data to Google Analytics. We will start by pushing the transaction by using _addTrans.

// We have to compute taxes total.
var taxes = 0;
for (var i = 0; i < order.taxes.length; i++) {
  taxes += order.taxes[i].amount;
}

_gaq.push(['_addTrans',
  order.token, // This is the unique ID of the transaction
  'Your store name' // Replace by your store name
  order.grandTotal,
  taxes, // We use the value that we computed before
  order.shippingFees,
  order.billingAddress.city,
  order.billingAddress.province,
  order.billingAddress.country]);

The next step is to push all the items in the order.

for (var y = 0; y < order.items.length; y++) {
  _gaq.push(['_addItem',
    order.token, // It must matches the value that you used in _addTrans
    order.items[y].id,
    order.items[y].name,
    '', // This is the product variation, you can use it if your product has custom fields. 
    order.items[y].price,
    order.items[y].quantity]);
}

If your product has custom fields, you may want to define the product variation. Imagine that your product is a t-shirt and the color is the variation you want to push to Google. The product is like the following:

<a href="#" class="snipcart-add-item"
  data-item-id="TSHIRT"
  data-item-name="T-Shirt"
  data-item-url="/"
  data-item-custom1-name="Color"
  data-item-custom1-options="Red|Blue|Green">Buy it</a>

On the object that you will receive in the callback of the order.completed event, each item in the items array has a method named getCustomFieldValue that helps you retrieve the actual value of the custom field. It takes the name of the custom field as a parameter, in our case it is Color.

for (var y = 0; y < order.items.length; y++) {
  _gaq.push(['_addItem',
    order.token, // It must matches the value that you used in _addTrans
    order.items[y].id,
    order.items[y].name,
    order.items[y].getCustomFieldValue('Color'), // This is the product variation, you can use it if your product has custom fields. 
    order.items[y].price,
    order.items[y].quantity]);
}

The final step is to push the transaction to Google Analytics.

gaq.push(['_trackTrans']);

In conclusion, the complete code should look like this:

<script type="text/javascript">
  
  // You may already have Google Analytics bootstrapped, if so you can skip these few lines
  // Google Analytics bootstrapping
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);

  (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);
  })();
  // End of Google Analytics bootstrapping
  
  Snipcart.execute("bind", "order.completed", function(order) {
    // We have to compute taxes total.
    var taxes = 0;
    for (var i = 0; i < order.taxes.length; i++) {
      taxes += order.taxes[i].amount;
    }
    
    // Now we push the transaction to Google Analytics
    _gaq.push(['_addTrans',
      order.token, // This is the unique ID of the transaction
      'Your store name' // Replace by your store name
      order.grandTotal,
      taxes, // We use the value we computed before
      order.shippingFees,
      order.billingAddress.city,
      order.billingAddress.province,
      order.billingAddress.country]);
    
    // We push every items
    for (var y = 0; y < order.items.length; y++) {
      _gaq.push(['_addItem',
        order.token, // It must matches the value that you used in _addTrans
        order.items[y].id,
        order.items[y].name,
        '',
        order.items[y].price,
        order.items[y].quantity]);
    }
    
    _gaq.push(['_trackTrans']);
  });
</script>

We know that there are a lot of other analytics tools, and I think this post might give you a good idea of how to deal with them, but if you want more informations about one in particular, feel free to drop us a line at geeks@snipcart.com and we will be happy to help and maybe write another post about it.

Suggested posts: