featured post

Use Google Analytics in NetSuite for product tracking

A new article exists for Netsuite Google Analytics which is news than this article.

Getting Google Analytics to work with NetSuite reminds me of getting a river to flow uphill.  Is it not easy, at first seems impossible, but with a big enough sump-pump…it will work.

Here is a step-by-step tutorial to get Google Analytics (working in asynchronous mode) working with NetSuite.

Step 1:

This may seem obvious – but, log into NetSuite.
[asa]0470191074[/asa]

Step 2:

We have to setup NetSuite to handle some of the click action (forms and links) google uses to track visitors – so, to do this we need to add those in the Setup area.

Go to:  Setup -> Web Site -> Set up Website – > desired site -> Setup {tab}

Google Analytics in NetSuite - Step 2

click for a larger picture.

To the Click and Submit attributes we need to add these event handlers:

Analytics Click Attributes:
onclick=”_gaq.push(['_link', ' https://checkout.netsuite.com']); return false;”

Analytics Submit Attributes:
onsubmit=”_gaq.push(['_linkByPost', this]);”

Step 3:

Now we need to set up a tab for our analytics to live in.  Tabs in NetSuite are cool – they allow us to have editable code in one spot, but place the tag in many spots.  Very handy for often used variables and locations.

Go to: Setup -> Web Site -> Tags

If you have not created an analytics tag for this site – yet…click “Add New”, otherwise lets edit the site’s tag.

Here is the code for “Default Value” field.

	<script type="text/javascript">
		var _gaq = _gaq || [];
		 _gaq.push(
		['_setAccount', 'GOOGLE ASSIGNED CODE'],
		['_setDomainName', 'none'],
		['_setAllowLinker', true],
		['_trackPageview']
		);

		function cookieProx() {
			var ifrm = document.createElement("iframe");
                        var prox = 'https://checkout.netsuite.com/c.custnum/sitefolder/{file-from-step4}.html';
                        ifrm.style.display = "none";
			_gaq.push(function() {
				var tracker = _gaq._getAsyncTracker();
				ifrm.src = tracker._getLinkerUrl(prox)
				document.getElementById("innerwrapper").appendChild(ifrm);
			});
			return false;
		}

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

		var domain = "domain name without 'www'";
		try	{
			if(document.URL.indexOf(domain) != -1) {
				cookieProx();
			}
		} catch(e) {};

		try {googlePushOrder();} catch(e) {};
	</script>

This is code from a citricle article which they adapted from the Google help pages…good stuff.  We changed a few lines – using the “.src” attribute is better for IE then the other way…not 100% sure.  But it is working for us.

Step 4:

Now is when the ‘magic’ happens. Because we need to track cookie across domains – we have to have a way to set a cookie and have both our original domain and the checkout@netsuite domain read it. To do this we will actually load an iframe in the header of the page and then pass it. This will allow the access we need to maintain the information we want about the traffic source.

Go to: Documents -> Files -> File Cabinet -> Web Site Hosting Files -> Live Hosting Files -> sitefolder

Now we need to add our “cookie” file to the document center. Here is the contents of the file. You may notice this page has “old” google code on it, the synchronous type. I have no idea why, but if we use the asynchronous code here – the process fails and we loose the traffic information.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<title>ga iframe code for netsuite cookie by proxy</title>
</head>
<body>

<script type="text/javascript">
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>

<script type="text/javascript">
	var pageTracker = _gat._getTracker("GOOGLE ASSIGNED CODE");
	pageTracker._setDomainName("none");
	pageTracker._setAllowLinker(true);
	pageTracker._initData();
	pageTracker._trackPageview();
</script>

</body>
</html>

The important thing to remember in this step is to ensure the file name from Step 4 (this step) much match the file being called in Step 3.

Step 5:

We now need to add the code to the footer of the page.  We’ll use the tag we created earlier.

Go to: Setup -> Web Site -> Themes -> Body {tab}

Footer Template:
<Google Analytics Tag>

Again, this is the tag we created or modified in Step 3.

Step 6:

The final step is definitely the icing on the cake. This code will allow us to track transactions and the products purchased in said transaction. We will add this in the Setup area – the same one we modified in Step 2.  Instead of Setup, we’ll use the shopping tab.

Go to:  Setup -> Web Site -> Set up Website – > desired site -> Shopping {tab}

In the Order Confirmation Page section, the field name: Order Tracking Script HTML

<script type="text/javascript">
	function googlePushOrder() {
		try {
			if (document.URL.indexOf("thanks") != -1) {
				var orderid		= "<%=getCurrentAttribute('confirmation','ordernumber')%>";
				var sitename	= "<%=getCurrentAttribute('site','name')%>";
				var subtotal	= "<%=getCurrentAttribute('confirmation','subtotal')%>";
				var tax				= "<%=getCurrentAttribute('confirmation','tax')%>";
				var shipping	= "<%=getCurrentAttribute('confirmation','shipping')%>";
				var category	= "<%=getCurrentAttribute('site','name')%>";

				var city		= "";
				var state		= "";
				var country	= "";
				try {
					var str			= "<%=getCurrentAttribute('customer','defaultaddress')%>";
					var lastBr	= str.lastIndexOf("<br>");
					var firstBr	= str.lastIndexOf("<br>",lastBr - 1);
					var country	= str.substring(lastBr+4,str.length);
					var splitUp	= str.substring(firstBr+4,lastBr);
					var split2	= splitUp.split(" ");
					var city 		= split2[0];
					var state 	= split2[1];
				} catch(e) {}

				_gaq.push(['_addTrans',orderid,sitename,subtotal,tax,shipping,city,state,country]);

				var rows = document.getElementById("ordersummary_total").parentNode.rows;

				for (var i = 0; i < rows.length; i++) {
					try {
						var skuName		= rows[i].cells[0].innerHTML;
						var qty				= rows[i].cells[1].innerHTML;
						var prodName	= rows[i].cells[2].innerHTML;
						var price			= rows[i].cells[4].innerHTML;

						price					= price.replace(",","");

						if (price.indexOf("$") != -1) {
							price = price.replace("$", "");
							_gaq.push(['_addItem',orderid,skuName,prodName,sitename,price,qty]);
						}
					} catch(e) {}
				}
				_gaq.push(['_trackTrans']);
			}
		} catch (e) {}
	}
</script>
Google Analytics in Netsuite - Step 6

click picture for larger version.

You may need to add more  code here for additional tracking.  (Adwords, Bing, whatever) – and sometimes you run into the classic html/scripting error message from NetSuite – if this happens try to consolidate one of the scripts and it usually fixes the error.

Please notice the code which is in the for loop in the middle “rows[i].cells[0].innerHTML”. This looping through the table on the confirmation screen to grab all the code needed to send the products to track. THIS WILL MOST LIKELY NEED TO BE CHANGED.

It works off a zero based array. The easy way to accomplish this is to save the HTML of an already completed transaction. Then paste the code into a local HTML page, and parse the table locally so you are not guessing at which one is the one.

If you are having problems getting the correct row/product to show up in the stats – save a sample of your confirmation page as HTML and work on it offline.  It will keep you from having to test the live form over and over with a real credit card.

Other Notes:

[asa]0470191074[/asa]If your Google Analytics is set to block out traffic coming from you and/or your IP address.  make sure to un-filter this prior to testing and re-filter it after testing is complete.  This is just something we ran into when trying to test.

Good luck and please drop me a note if you have trouble.

Discussion

5 Responses to “Use Google Analytics in NetSuite for product tracking”

  1. Hey Tom,
    Nice post!
    Could you go into a little more detail with regard to the last bit about parsing “the table locally so you are not guessing at which one is the one?”

    I am guessing you mean that it needs to be modified because your example table structure may not be the same as the project’s table structure. But what are the rules for modifying it to fit your particulars?

    ~Tim

    (Put some adwords ads on yr site so I can click all over ‘em. :-))

    Posted by Tim | September 1, 2011, 6:25 pm
  2. Each site in Netsuite is set-up differently. You can choose to include any number of items in your shopping cart’s table.

    But – this is important, because when you try to grab the correct cell to record for Google Analytics you use the array number. So you need to count the cell to figure out which cell’s data gets sent with the record.

    Make sense?

    Posted by tom.altman | September 6, 2011, 10:06 am
  3. Yes, I was able to figure that part out after I left the comment for you. It’s going row by row and counting through the cells in the row: 0, 1, 2, 4 and grabbing the contents.

    I also had to add the product name into the cart display, because we just had the sku being displayed. GA wants to know the product name.

    In your step 3 there’s a little typo, I think. There’s an ` on line 4 in front of the word Google.

    Also, after this page, I looked round at some of the other parts of your site, and I want to wish you best of luck. You seem like a great guy.

    I appreciate very much the work you have done here. It enabled me to take care of this puzzling problem and our business will benefit from the ROI measurement we can get now.

    Posted by Tim | September 7, 2011, 9:53 am
  4. I Think there is a fix for having to use the old code and the cookie issue. Netsuite now has a checkbox in Analytics section that says “Enable Google Analytics Integration” which is described as such:

    Check this box to pass Google tracking cookies from shopping to checkout. This along with the fields on the Analytics subtab are required for cross-domain analytics tracking to integrate NetSuite with your Google Analytics account.
    Clear this box if Google Analytics Integration interferes with a custom solution you have already implemented for cross-domain tracking.

    This may allow you to just paste your tracking code into the section, which is recommended for any website due to accuracy of tracking as its the first thing that gets hi.

    Posted by Alexander Conroy | October 12, 2012, 11:34 am
  5. They do Alex – but my experience has been it doesn’t work very well.

    We are currently testing a new version of the above…we will complete that testing in a bout a week and then I can put the latest version we are using up.

    Thanks for the comment.

    Posted by tom | October 12, 2012, 12:40 pm

Post a comment