Organize and Share your Electronics the way you want. Sign-Up for a free account now. It takes only 30 seconds!

Google Analytics server side ecommerce tracking

Google Analytics server side ecommerce tracking

A recurring issue we have on several of the ecommerce websites we manage is the Google Analytics Ecommerce Tracking system which often fails to save the customer’s order into the analytics account when the customers have completed their purchases.

This can be caused by the customer having ad blocking software installed or not returning to the online shop and viewing the order confirmation page which contains the Google tracking code.

Google have a server side system called Google Analytics Measurement Protocol API which allows you to post direct requests to the analytics servers to log events such as page views or other tracked events.

I found a basic C# wrapper for the Google Analytics Measurement Protocol API on github https://gist.github.com/0liver/11229128 and modified the code to allow me to track the items ordered in addition to the customers order as shown below.

I hope this code is useful for anyone trying to track ecommerce purchases using the Google Analytics Measurement Protocol API systems.

 try
        {

            var request = (HttpWebRequest)WebRequest.Create("http://www.google-analytics.com/collect");
            request.Method = "POST";
            request.KeepAlive = false;
            // the request body we want to send

            int x = 1;
            var postData = new Dictionary<string, string>
                           {
                               { "v", "1" },
                               { "tid", "UA-000000000" }, // Replace with your Google tracking account number
                               { "cid", "555" },

                               { "dh","yourdomainname.com" },
                               { "dp", "http://cdn.electronicsinfoline.com/callback.aspx" },
                               { "dt", "Payment Complete" },

                              { "ti", "PP0001"}, // Transaction ID. Required.
                               { "ta", "Yoursitename" }, // Affiliation.
                               { "tr", 99.99" }, // Revenue.
                               { "tt", "0" }, // Tax.
                               { "ts", "5.99" }, // Shipping.
                               { "pa", "purchase" }, // purchase.

                           };
			// loop over ordered items to add to stats
            foreach (DataRow row in ds.Tables["ShopOrderDetails"].Rows)
            {
                postData.Add("pr" + x.ToString() + "id", Convert.ToString(row["ProductRef"]));
                postData.Add("pr" + x.ToString() + "nm", Convert.ToString(row["ProductName"]));
                postData.Add("pr" + x.ToString() + "ca", "CategoryName");
                postData.Add("pr" + x.ToString() + "br", "BrandName");
                postData.Add("pr" + x.ToString() + "va", "");
                postData.Add("pr" + x.ToString() + "ps", x.ToString());

                x++;
            }
            //  

            var postDataString = postData
                .Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
                                                             HttpUtility.UrlEncode(next.Value)))
                .TrimEnd('&');

            // set the Content-Length header to the correct value
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataString);

            // write the request body to the request
            using (var writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(postDataString);
            }

            try
            {
                var webResponse = (HttpWebResponse)request.GetResponse();
                // Response.Write(webResponse.StatusCode);
                if (webResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new HttpException((int)webResponse.StatusCode,
                                            "Google Analytics tracking did not return OK 200");

                }
                webResponse.Close();
            }
            catch (Exception ex)
            {
                DoLog(ex.ToString());
            }
        }
        catch (Exception ex)
        {
            DoLog(ex.ToString());
           
        }

 

More Articles to Read

Single-Sided USB Charger
Single-Sided USB Charger
A FPGA controlled RGB LED MATRIX for Incredible Effects – the Hardware
A FPGA controlled RGB LED MATRIX for Incredible Effects – the Hardware
Using Nanotimers to Reduce IoT System Power Consumption by an Order of Magnitude
Using Nanotimers to Reduce IoT System Power Consumption by an Order of Magnitude
Replace a microwave’s beeping with the Windows XP startup sound
Replace a microwave’s beeping with the Windows XP startup sound
A DIY Laser Scanning Microscope
A DIY Laser Scanning Microscope
Reverse-engineering the surprisingly advanced ALU of the 8008 microprocessor
Reverse-engineering the surprisingly advanced ALU of the 8008 microprocessor
ESP8266 LED lighting: QuinLED v2.6 PCB
ESP8266 LED lighting: QuinLED v2.6 PCB
Switching LVDS Graphics in a Laptop Computer
Switching LVDS Graphics in a Laptop Computer
Teleknitting: TV-based string art
Teleknitting: TV-based string art
DIY Bubble Machine
DIY Bubble Machine
Start your day with Nerf target practice!
Start your day with Nerf target practice!
Teardown of a Peaktech 6225A
Teardown of a Peaktech 6225A

Top




Shares