How to Track Ecommerce Transactions with Google Analytics

Google Analytics is an amazing tool. Many developers add page tracking code, but Analytics also allows you to monitor JavaScript/Ajax events and promotional campaigns such as email newsletters. In this article, we’ll look at tracking your shopping transactions.

Why Track Transactions in Google Analytics?

Your ecommerce system can provide detailed transaction statistics, but you can’t necessarily relate them to page views or other factors. For example, was an increase in sales caused by SEO improvements, a successful email campaign, advertising or seasonal variations?

Recording all transactions in Google Analytics provides a richer set of customer and product reports. With this information, you can assess the success of campaigns and concentrate on those which lead to increased ROI.

Ecommerce Tracking Basics

In most cases, a shop visitor will add items to a cart, proceed to the checkout, perhaps register, pay an amount, and be shown a receipt page. The full details of the transaction must be passed to Google Analytics at the “receipt” page stage.

Transaction data is normally stored in your back-end systems or passed back by the payment gateway. You need to pass this information to the analytics script. In other words, you’ll use a server-side language such as PHP to obtain the data and write JavaScript directly to the resulting HTML page.

Enable Ecommerce Tracking

By default, Google Analytics disables ecommerce reports, so you must choose “Yes, an E-commerce Site” on the edit profile screen (click Edit at the top-right of the Profile Settings page).

Transaction-tracking Code

There are five distinct parts to the ecommerce tracking code.

1. Set the account and track the page
The standard Google Analytics tracking code must be implemented, i.e.


var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']); // your GA ID
_gaq.push(['_trackPageview']);            // track the page view

2. Add transaction details
The next code block provides information about the transaction. It must include the following data in this order:

  • the order ID (required)
  • the store or affiliate name (required, but can be an empty string)
  • the total amount (required)
  • the tax amount
  • the shipping charge
  • the buyer’s city
  • the buyer’s state, county or province
  • the buyer’s country

Note that numeric amounts must be specified in JavaScript notation, i.e. no thousand separators and a period (.) for the decimal point.

For example:


_gaq.push(['_addTrans',
	'1234',       // order ID
	'SitePoint',  // store
	'19.99',      // total
	'1.50',       // tax
	'3.00',       // shipping
	'Chicago',    // city
	'Illinois',   // state
	'USA'         // country
]);

3. Add individual products
A code block is required for all products purchased within the transaction. The data is required in the following order:

  • the order ID (must be the same as the transaction)
  • the product code or SKU
  • the product name
  • the category or a variation, e.g. large size
  • the unit price
  • the quantity

_gaq.push(['_addItem',
	'1234',          // order ID
	'css123',        // SKU/code
	'CSS Live',      // product name
	'Online Course', // category or variation
	'9.99',          // unit price
	'1'              // quantity
]);

4. Submit the transaction
The last instruction submits all transaction data to Google Analytics:


_gaq.push(['_trackTrans']);

5. Load the Google Analytics script
Finally, we must remember to load the Analytics script. The asynchronous syntax is recommended:


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

Putting It All Together

Your final ‘receipt’ page will look something like this:


<!DOCTYPE html>
<html lang="en">
<head>
<title>Thank you for your order</title>
</head>
<body>
<p>Thank you for your order. Your details have been sent to customer@email.com.</p>

<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-12345-6']);
_gaq.push(['_trackPageview']);

// transaction details
_gaq.push(['_addTrans',
	'1234',
	'SitePoint',
	'109.99',
	'10.00',
	'0.00',
	'Chicago',
	'Illinois',
	'USA'
]);

// item 1
_gaq.push(['_addItem',
	'1234',
	'css123',
	'CSS Live',
	'Online Course',
	'9.99',
	'1'
]);

// item 2
_gaq.push(['_addItem',
	'1234',
	'cb999',
	'Donation for Craig's excellent blog post',
	'Well-deserved bonus!',
	'100',
	'1'
]);

// track transaction
_gaq.push(['_trackTrans']);

// load Analytics
(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>
</body>
</html>

Within a few hours, you’ll be able to view buying statistics in the Ecommerce section of the Google Analytics panel. You will also find further ‘Ecommerce’ tabs on other reports.

Are you tracking ecommerce transactions in Google Analytics? Have you found it useful?

note:Want more?

If you want to read more from Craig, subscribe to our weekly tech geek newsletter, Tech Times.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • John Henson

    Keep in mind that, in most cases, the code in #1 and #5 will already part of a page to which you are adding Ecommerce Tracking.

    This is because this is the standard GA code that should be on Every Page of the site.

    There is no need to duplicate those pieces of code.

    Additionally, if there has been any customization to the Standard Tracking code, adding an additional set of non-customized code from #1 could sometimes result in GA losing track of visitor sessions and not correctly attributing revenue to the correct visitor acquisition channel.

    • millerb7

      I’m interested in #2 and #3. Can you elaborate on that some if you know by chance? Is this code that can be automatically generated or do you need to write this code for each and every item on your site? Then it’s auto-populated depending on what they add in the cart and checkout with?

      • http://www.optimalworks.net/ Craig Buckler

        You need to pass the details of the transaction and every product purchased. In most cases, this means your server side code must ‘write’ JavaScript code with the required information.

        You only need to include the purchased items during the sale — not every product in your shop.

    • S L

      Hi John: This is totally right. I actually have a site with the Standard Tracking code looking like #1 close together with a #5 that is duplicated with the #1 and #5 of my GA Ecommerce Tracking. And on top of that I have added a line of code for tracking between subdomain to my Standard Tracking and like you said it’s not correctly attributing revenue to the correct referrer (saying everything comes “direct”). What should I do for the eCommerce tracking to take into account my customized standard tracking?!

  • millerb7

    So you have to pre-make the javascript code for each and every item you are selling? I suppose I am a tad confused.

    • http://www.optimalworks.net/ Craig Buckler

      You ‘make’ the JavaScript on the “thank you” page shown immediately after a successful transaction. The ‘_addItem’ method is run for every item purchased within that transaction.

      That is different to other Analytics methods and it’s not something you need or want to do very often.

      • millerb7

        I appreciate your help. I have just read sitepoints javascript books, so I will delve into the matter more.

  • hyderalis

    I don’t understand the add item. We have thousands of items so should we create an _addItem() section for each different item, or SKU, in the transaction.

    Please reply

    • http://www.optimalworks.net/ ceeb

      You’re only running _addItem for every product an individual has purchased.

      So, if you’re selling widget1, widget2 … widget9999 and Bob comes along and buys widget42 and widget57, you call _addItem twice — once for widget42 and once for widget57.

  • pardalsalcap

    Hi, I have a question. Imagine the following 2 cases:

    First

    1. Visitors fills the basket
    2. Visitors pays (at Paypal or any Visa method)
    3. Throught IPN website closes the order
    4. Visitors goes to the “thanks you page” where you track the GA trans.

    Second

    1. Visitors fills the basket
    2. Visitor pays (in Paypal or any Visa method)
    3. Throught IPN website closes the order
    4. Visitor does NOT return to the site, so he does get the “thank you page”, so we do not get the transaction tracked intro GA.

    Any idea about how to solve it?

    • http://www.optimalworks.net/ Craig Buckler

      If the visitor does not return to your site, that transaction cannot be tracked. The “thank you” page must appear but, in most cases, you can force a redirect from the payment system.