Sharing Google analytics script for ecommerce

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
13 年 前
Hello,

Here is my implementation, any suggest would be appreciated. It works the same on http and https.

1 - Create a new user control in modules named WebCommerceAnalyticsControl.ascx

2 - Rename the file WebCommerceAnalyticsControl.ascx with WebCommerceAnalytics.ascx, just to respect namming convention of nop commerce, but don't propagate renaming to the class name

3 - Make WebCommerceAnalyticsControl class derives from BaseNopUserControl like this
public partial class WebCommerceAnalyticsControl : BaseNopUserControl


4 - Open the WebCommerceAnalytics.ascx.cs file and paste this code inside the class block
protected override void Render(HtmlTextWriter output)
{
    if (SettingManager.GetSettingValueBoolean("Analytics.GoogleEnabled"))
    {
        CultureInfo usCulture = new CultureInfo("en-US");
        StringBuilder sb = new StringBuilder();
                
        sb.AppendLine("<script type=\"text/javascript\">");
        sb.AppendLine("var _gaq = _gaq || [];");
        sb.AppendFormat("_gaq.push(['_setAccount', '{0}']);", SettingManager.GetSettingValue("Analytics.GoogleId"));
        sb.AppendLine();
        sb.AppendLine("_gaq.push(['_trackPageview']);");
        sb.AppendFormat("_gaq.push(['_addTrans', '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}']);", CurrentOrder.OrderId, "extensions-hair.com", CurrentOrder.OrderTotal.ToString("0.00", usCulture), CurrentOrder.OrderTax.ToString("0.00", usCulture), CurrentOrder.OrderShippingInclTax.ToString("0.00", usCulture), CurrentOrder.BillingCity, CurrentOrder.BillingStateProvince, CurrentOrder.BillingCountry);
        sb.AppendLine();
        foreach (var item in CurrentOrder.OrderProductVariants)
        {
            string categ = "";
            try {categ = item.ProductVariant.Product.ProductCategories[0].Category.Name;}catch (Exception){}

            sb.AppendFormat("_gaq.push(['_addItem', '{0}', '{1}', '{2}', '{3}', '{4}', '{5}' ]);", item.OrderId, item.ProductVariant.SKU, item.ProductVariant.FullProductName, categ, item.UnitPriceInclTax.ToString("0.00", usCulture), item.Quantity);
            sb.AppendLine();
        }
        sb.AppendLine("_gaq.push(['_trackTrans']);");
        sb.AppendLine("(function() { ");
        sb.AppendLine("var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;");
        sb.AppendLine("ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';");
        sb.AppendLine("var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);");
        sb.AppendLine("})();");
        sb.AppendLine("</script>");
                
        output.Write(sb.ToString());
    }
}

Order currentOrder = null;
public Order CurrentOrder
{
    get
    {
        if (currentOrder == null)
        {
            var orderCollection = NopContext.Current.User.Orders;
            if (orderCollection.Count == 0)
            {
                Response.Redirect(CommonHelper.GetStoreLocation());
            }
            else
            {
                currentOrder = orderCollection[0];
            }
        }
        return currentOrder;
    }
}


5 - Compile and insert you new user control at the bottom of CheckoutCompleted.ascx

<%@ Register TagPrefix="nopCommerce" TagName="WebCommerceAnalytics" Src="~/Modules/WebCommerceAnalytics.ascx" %>


and then

<nopCommerce:WebCommerceAnalytics ID="ctrlWebCommerceAnalytics" runat="server" />

6 - Ckeck your settings to have
Analytics.GoogleId = !your id from google!
Analytics.GoogleEnabled = true


Hope it helps!

Regards,
Nicolas
13 年 前
Excellent work, just what I needed :)
13 年 前
What if you need other cultures then 'en-US'?


And with option 3:
- Make WebCommerceAnalyticsControl class derives from BaseNopUserControl like this
public partial class WebCommerceAnalyticsControl : BaseNopUserControl

do you mean the public class of WebCommercAnalytics.ascx.cs or somewhere else?

also you need to add a few 'using system.x' items to the .cs:
using System.Text;
using System.Globalization;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings;
using NopSolutions.NopCommerce.Common.Utils;
sing NopSolutions.NopCommerce.BusinessLogic.Orders;



I added it also to the Category.aspx page to test it but it does not show up. Only the analytics script from NC160 itself.
anyway. Is there something wrong with the google analytics script from NC160 itself. What is the reason you created your own. Am I missing something crucial?
13 年 前
CultureInfo usCulture = new CultureInfo("en-US") is just to format numeric values according to google documentation.
My site is french, and it works perfectly!

Derives from BaseNopUserControl in WebCommerceAnalytics.ascx

For the last question, this script is used to track google analytics conversion. The original WebAnalytics.ascx control just track you navigation, but you need a special script to say that customer has bought something. It will give you more stats in analytics web site, under ecommerce section.
13 年 前
Aha! Thanks for the explanation.

However. I have looked at the source code when processing order and i can't find the script. I got no errors with the rebuild so codewise everything seems to looks ok. But looks like the whole section is not included into the CheckoutCompleted.ascx page. All I can find is the original analytics script.  I even added some remark text to the sb.appendline output but not found it when searching through html source in browser.
13 年 前
Did you check Analytics.GoogleEnabled parameter?
13 年 前
Yes I did. The NC analytics script is showing up though.
I also have added the Google ID below that and altered the NC google js to use my GID.

I even added it to  the default.aspx, just to see if the script is showing up.

I rebuild the Nopcommerstore and the rebuild the solution.

This is how the webCommerceAnalytics.ascx.cs file source looks like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings;
using NopSolutions.NopCommerce.BusinessLogic.Content.Topics;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using System.ComponentModel;
using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement;
using NopSolutions.NopCommerce.BusinessLogic.Orders;


namespace NopSolutions.NopCommerce.Web.Modules
{
    public partial class WebCommerceAnalyticsControl : BaseNopUserControl
    {
        protected override void Render(HtmlTextWriter output)
        {
            if (SettingManager.GetSettingValueBoolean("Analytics.GoogleEnabled"))
            {
                CultureInfo usCulture = new CultureInfo("en-US");
                StringBuilder sb = new StringBuilder();

               // ## ADDED TO SEE IF CODE IS AVAILABLE ##
               //  sb.AppendLine("<h1>GOOGLE ANALYTICS CODE HERE</h1>");
              // ## END

                sb.AppendLine("<script type=\"text/javascript\">");
                sb.AppendLine("var _gaq = _gaq || [];");
                sb.AppendFormat("_gaq.push(['_setAccount', '{0}']);", SettingManager.GetSettingValue("Analytics.GoogleId"));
                sb.AppendLine();
                sb.AppendLine("_gaq.push(['_trackPageview']);");
                sb.AppendFormat("_gaq.push(['_addTrans', '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}']);", CurrentOrder.OrderId, "extensions-hair.com", CurrentOrder.OrderTotal.ToString("0.00", usCulture), CurrentOrder.OrderTax.ToString("0.00", usCulture), CurrentOrder.OrderShippingInclTax.ToString("0.00", usCulture), CurrentOrder.BillingCity, CurrentOrder.BillingStateProvince, CurrentOrder.BillingCountry);
                sb.AppendLine();
                foreach (var item in CurrentOrder.OrderProductVariants)
                {
                    string categ = "";
                    try { categ = item.ProductVariant.Product.ProductCategories[0].Category.Name; }
                    catch (Exception) { }

                    sb.AppendFormat("_gaq.push(['_addItem', '{0}', '{1}', '{2}', '{3}', '{4}', '{5}' ]);", item.OrderId, item.ProductVariant.SKU, item.ProductVariant.FullProductName, categ, item.UnitPriceInclTax.ToString("0.00", usCulture), item.Quantity);
                    sb.AppendLine();
                }
                sb.AppendLine("_gaq.push(['_trackTrans']);");
                sb.AppendLine("(function() { ");
                sb.AppendLine("var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;");
                sb.AppendLine("ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';");
                sb.AppendLine("var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);");
                sb.AppendLine("})();");
                sb.AppendLine("</script>");

                output.Write(sb.ToString());
            }
        }

        
        Order currentOrder = null;
        public Order CurrentOrder
        {
            get
            {
                if (currentOrder == null)
                {
                    var orderCollection = NopContext.Current.User.Orders;
                    if (orderCollection.Count == 0)
                    {
                        Response.Redirect(CommonHelper.GetStoreLocation());
                    }
                    else
                    {
                        currentOrder = orderCollection[0];
                    }
                }
                return currentOrder;
            }
        }

    }
}
13 年 前
Ok! never mind got it working. Some 'idiot' in our team reseted the settings.  Aarggh!

People can copy the above code to make the page. It is working 100%;
13 年 前
I have some problem to insert the code in nopcommerce 1.20 . :(
13 年 前
Thanks -- I've added this! Will report the results.

I've seen other people using "Funnel" code to track how customers add things to their cart and actually checkout -- or conversion trackers -- I need to read more carefully is this similar or just a record of what was purchased?
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.