A Guide To E-Commerce Conversion Tracking Using Google Tag Manager

A Guide To E-Commerce Conversion Tracking Using Google Tag Manager

by Pier-Yves C Valade / Monday, 27 January 2014 / Published in Measure & Optimize, PPC & Advertising

So, I came up with this fantastic idea to setup the script management of one of the clients I manage with Google Tag Manager, which is quite a fantastic idea for normal tags like Google Analytics, Remarketing tags and so on.

But then came the fun part: Conversion tracking with the GTM isn’t exactly what I expected; what I thought was Plug & Play came out to be just not compatible. The original Google Analytics e-Commerce tracking snippet doesn’t seem to speak the magical language of the Google Tag Manager wizard, which disappointed me quite a bit. Needless to say I went on a fantastic journey trying to decode the oh-so-simple-and-elaborate Google documentation relating to e-Commerce tracking with the Google Tag Manager. After achieving what was told to me like impossible by some of my peers, I thought I would setup a guide to e-Commerce Tracking using Google Tag Manager just in case someone else would be looking to go the same route.

If you are not familiar with what the Google Tag Manager is all about, it’s pretty simple. The Google Tag Manager is a snippet manager where you can manage where and when you show these snippets on pages using triggers. Sounds fun? Read on.

DISCLAIMER: Although these steps have proven to give good results for my clients, everything presented here must be seen as a proof of concept and may harm your Magento installation if things go wrong in some way. Therefore, the author, Pier-Yves C Valade, and Ludis Media discharge themselves from anything that could happen to any website by following the steps described in this article. The employment of a Magento specialist is highly recommended.

Setting Up The Google Tag Manager Account

If you don’t already have your Google Tag Manager account setup and ready, go on and create one. I recommend you take a look at this step-by-step guide from Big Daylight so that you can setup everything properly.

Make sure to put the Google Tag Manager snippet right after the opening of the <body> tag so that everything works as it is supposed to. Here’s what it looks like once on your page:

<html>
    <head>
        [...]
    </head>
    <body>
        <!-- Google Tag Manager -->
        <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXX"
        height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
        <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','GTM-XXXXX');</script>
        <!-- End Google Tag Manager -->

        [...]

Adding the Google Tag Manager Snippet to your Magento Installation

Here’s a way to update your Magento install in order to make the GTM pop right in place. Simply make your way to this file and make it look exactly the same as this and save. Beware that this will remove any classic Google Analytics tag that would’ve been present.

gtm-magento-ga-phtml-screenshot

Once it’s done, make your way in the Magento Admin Backend to System -> Configuration -> Sales -> Google API and expand the Google Analytics section. Make sure to Enable the feature and add your Google Tag Manager container ID to the Account Number field. Hit save and you should have your GTM tag up and running on all your pages.

google-analytics-magento-admin-panel

Make sure to do the other steps below BEFORE making this change. Otherwise, this change will result in Google Analytics data loss during the process.

Creating The Google Analytics Conversion Tag

Once you have your Google Analytics tag setup in GTM, what you will want to do is create another Google Analytics tag, made for transaction tracking this time, that will be able to see the data we will be serving it. Make sure to set the track type to “Transaction” instead of “Page View”!

google-tag-manager-transactions-configuration

Once this tag is setup, we will need to trigger it on the right thank you page.

Triggering The Google Analytics Conversion Tag

Triggering the tag we just created is quite easy, just click on the right on the button to add a triggering rule.

google-tag-manager-trigger-button

Once you get to the popup, the next step is to name the rule to something like “Transaction Thank You Page” and make it trigger only on the url containing the exact path to your thank you page, let’s say “/checkout/success”. Make sure to also add an event listener to “gtm.dom”, a built-in event that triggers once the page is fully loaded, so that you also fetch everything coming after the Google Tag Manager’s script.

google-tag-manager-triggering-rule-popup

Then, save both the rule and the tag and publish your container.

Adding The dataLayer Object Magic To The Thank You Page

Now, you should have everything properly setup on the Google Tag Manager’s side. It is time to compute the transaction data and serve it to your freshly made tag.

Maybe you are already familiar to the _gaq object and the _trackTrans method which is the old method of when you weren’t using Google Tag Manager. It looks quite the same but it is named dataLayer instead of _gaq. You can also use the datalayer.push() method with it, but that’s another topic.

There’s many ways to fill and use the dataLayer object but here’s what mine looks like with the required variables filled in and how I managed to get to it with the Magento backend.

The Magento PHP code underneath

File: /app/code/local/Mage/GoogleAnalytics/Block/Ga.php
<?php
    protected function _getOrdersTrackingCode(){
        $orderIds = $this->getOrderIds();
        if (empty($orderIds) || !is_array($orderIds)) {
            return;
        }
        $collection = Mage::getResourceModel('sales/order_collection')
            ->addFieldToFilter('entity_id', array('in' => $orderIds))
        ;

        $aOrders = array();
        foreach ($collection as $order) {
            $objOrder = new stdClass();
            $objOrder->transactionId = $order->getIncrementId();
            $objOrder->transactionAffiliation = Mage::app()->getStore()->getFrontendName();
            $objOrder->transactionTotal = $order->getBaseGrandTotal();
            $objOrder->transactionTax = $order->getBaseTaxAmount();
            $objOrder->transactionShipping = $order->getBaseShippingAmount();

            $aItems = array();
            foreach ($order->getAllVisibleItems() as $item) {
                $objItem = array();
                $objItem['sku'] = $item->getSku();
                $objItem['name'] = $item->getName();
                $objItem['category'] = null; //todo
                $objItem['price'] = $item->getBasePrice();
                $objItem['quantity'] = $item->getQtyOrdered();
                $aItems[] = (object) $objItem;
            }

            $objOrder->transactionProducts = $aItems;
            $aOrders[] = $objOrder;
        }

        $strToReturn = '';
        foreach($aOrders as $objFinalOrder){
            $strToReturn .= sprintf('dataLayer.push(%s);', json_encode($objFinalOrder));
        }

        return $strToReturn;
    }
?>

The HTML page dataLayer output

<script>
    dataLayer.push({
        'transactionId': '1234',
        'transactionAffiliation': 'Acme Clothing',
        'transactionTotal': 11.99,
        'transactionTax': 1.29,
        'transactionShipping': 5,
        'transactionProducts': [{
            'sku': 'DD44',
            'name': 'T-Shirt',
            'category': 'Apparel',
            'price': 11.99,
            'quantity': 1
        },{
            'sku': 'AA1243544',
            'name': 'Socks',
            'category': 'Apparel',
            'price': 9.99,
            'quantity': 2
        }]
    });
</script>

Allowing some time to testing

Once you manage to setup everything right, the next thing you will need to do is test things up! The last thing you would like to do is stop tracking data in you Google Analytics eCommerce profile. So, go on and make a test purchase or wait until you have some purchases you know you can check if they got through the whole process. If everything works as planned, you should have data flowing through in the next 24 hours.

ecommerce-tracking-google-analytics-dashboard

So, it’s as simple as that! Now, go on and enjoy the magic of the dataLayer!

The following two tabs change content below.
Pier-Yves C Valade, Ludis Media
I'm currently an SEO, PPC and Analytics specialist here at Ludis Media! Always looking for new challenges, I am a leader who’s not afraid of anything! I am in constant improvement in all facets of my life and aims at every moment to excel. I am an excellent communicator and also have an open mind. On a more personal side, I am fond of scotch, cars, bikes and great food! I love Hans!

77 Responses to “A Guide To E-Commerce Conversion Tracking Using Google Tag Manager”

  1. Sam Sam says : Reply

    How can I just implement this in success.phtml without using a function?

    • Hi Sam,

      There’s no actual way of doing this without altering the _getOrdersTrackingCode() function.

      You might want to get help from a specialist in order to make everything work as described.

      Hope this helps!

  2. Dan Brown Dan Brown says : Reply

    Hi, is there a way to grab this function for quick use in success.phtml? I just need to have PHP output that datalayer script.

    Thanks in advance!!

    • Hi Dan,

      By default, Magento will use the Google Analytics block which will output the _trackTrans code. You need to override the function to output the dataLayer instead of the default gaq.push() by copying the file from “/app/code/core/Mage/GoogleAnalytics/Block/Ga.php” to “/app/code/local/Mage/GoogleAnalytics/Block/Ga.php” and replacing the default _getOrdersTrackingCode() function for the one supplied in the article.

      You will then need to do a test purchase and look into the code if everything works okay for you.

      And remember, I am not responsible for any trouble you may get by playing around applying this. If you’re not comfortable editing code, please make it done by a specialist.

      Hope this helps!

      • Tim Marsh Tim Marsh says : Reply

        Bonjour Pier-Yves, merci beaucoup for this!

        Quick question: in CE1.9, the GA core block has two protected functions – one at line 151 and one at 203. The first one looks like a universal analytics that writes the standard ecommerce data to GA using ga(ecommerce:send) and the second one is using the push method.

        I hate to be a pain, but which lines need replacing?

        Also, it would be awesome to see this post updated or augmented with a post showing how to do this in a generic sense for Magento, i.e. using the push method per Max’s comment (http://ludismedia.com/en/guide-to-e-commerce-conversion-tracking-using-google-tag-manager/#comment-57442) so as to keep the analytics data too?

        Tim

        (I’m not a developer so if I am wrong, please feel free to correct me!)

        Tim

        Will CE1.9 core GA code still push analytics (visit) code to GA though?

        I am using GTM to encapsulate GA snippet, AdWords conversion AND transaction data per this post, so want to make sure the suggested change still lets Magento’s GA.php scripts send visitor and ecommerce info.

        Thanks Pier-Yves!
        TIm

        PS: how would your code above in ga.php change to accommodate push?

        tim

        • Hi Tim!

          Content que vous aimiez this article! 😉 As you might have noticed, I took your 3 comments and made them into 1!

          As per the dataLayer.push() method instructions, I should indeed update the post to use it instead, you’re right.. I’ve been having this in my todo list for too long! To answer your other question about keeping data in GA, using dataLayer.push() will keep your visitor data as you would like.

          To use push() instead, just use dataLayer.push({…}); instead of dataLayer = [{…}].

          For the function you need to replace in GA.php, you should replace the one using the Universal Analytics “ga(ecommerce:send)” method probably but I would have to look into it myself to make sure. It would be the one you currently see when you do a transaction and land on the TY page.

          As always, go make the changes and allow some time to testing to make sure you don’t lose data!

          Hope it helps!

          • George George says :

            Hi Pier,

            I am using the Google Tag Manager extension by ShopGo on CE 1.9.1.0

            I see the screenshots in your article are somewhat dated as GTM now has a new interface.

            As I am a complete newbie in GTM – could you please explain exactly what settings need to be done also in Google Analytics and possibly update the screenshots too?

            Also – is it necessary to edit any Magento code? I see the extension has added the GTM code without issues.

            Another thing which bothers me – setting tracking to Transaction. Does that actually limit GA to track only sales and not visitor page views? I need a complete statistics for both sales and visitor behavior on the site.

            I hope you can clarify all that 🙂

            PS. The site is new and is using Universal Analytics

          • Hi George,

            I made this article with GTM v1. The version 2 of GTM just came out recently and it would be a good idea for me to update this how-to indeed. The new interface moves things around a bit but follows the same principles.

            In order to use GTM, you will have to edit some code or use a plugin for that. I prefer the first method, as the how-to describes!

            In GTM, you will indeed need 2 tags in order to track both visits AND transactions. One for visits and one for transactions.

            Hope it helps!

  3. Lakinzn Lakinzn says : Reply

    Hi, pls re the data layer, do you implement it by yourself or is it up to a programmer to implement that on the page? And are you specifying it to him? Thx.

    • Hi, it is best suited to implement this with the help of a Magento programmer in order so that you do not break anything. I guess that a Magento programmer will understand what to do by reading this article without any major problem! Hope this helps.

  4. Sam Sam says : Reply

    Thanks for the feedback. I skipped right to localizing the file and replacing the function to see what gets output on the success page, though I don’t get anything. I have Google API set to enabled.

    Do I need to go through the google tag manager steps in order for there to be any output on the success page?

    • Hi Sam,

      Prior to doing the change, did the function returned the conversion gaq.push()? If not, the problem is not in the function, but in your config! You need to have your built-in Google Analytics integration activated in Magento.

      Hope it helps!

  5. Yvan Nguyen Yvan Nguyen says : Reply

    Hi, i’m using the following code as Anlytics ecommerce code in GTM:

    dataLayer = [{
    ‘transactionId’: ‘3211’,
    ‘transactionTotal’: ‘1’,
    ‘transactionProducts’: [{

    ‘name’: ‘Fotovoltaico’,

    ‘sku’: ‘Bolzano/Bozen’,

    ‘category’: ‘Trentino Alto Adige’,
    ‘price’: ‘1’,
    ‘quantity’: ‘1’
    },{

    ‘name’: ‘Riscaldamento Ecologico’,
    ‘sku’: ‘Bolzano/Bozen’,
    ‘category’: ‘Trentino Alto Adige’,
    ‘price’: ‘1’,
    ‘quantity’: ‘1’

    },{

    ‘name’: ‘Solare Termico’,

    ‘sku’: ‘Bolzano/Bozen’,
    ‘category’: ‘Trentino Alto Adige’,
    ‘price’: ‘1’,
    ‘quantity’: ‘1’
    },{

    ‘name’: ‘Geotermico’,
    ‘sku’: ‘Bolzano/Bozen’,
    ‘category’: ‘Trentino Alto Adige’,
    ‘price’: ‘1’,
    ‘quantity’: ‘1’

    },{

    ‘name’: ‘Infissi’,
    ‘sku’: ‘Bolzano/Bozen’,
    ‘category’: ‘Trentino Alto Adige’,
    ‘price’: ‘1’,
    ‘quantity’: ‘1’

    }]

    }];

    This code is working only for a single product suche as “Infissi”, but it doesn’t work with the selection of 5 products. Which is the problem?
    Thanks

    • Hi,

      From what I see, all your SKUs are the same, which Google might see all of your 5 items like the same one and taking the last values you supplied, hence “Infissi”.

      A SKU is usually a unique and alphanumeric code that refers to a unique item. You should avoid using slashes or other non-alphanumeric symbols for compatibility purposes.

      Your datalayer object with unique SKUs could look something like this, but it’s up to you to define unique SKUs for each and every product you sell.

      dataLayer = [{
      ‘transactionId’: ‘3211’,
      ‘transactionTotal’: ‘1’,
      ‘transactionProducts’:
      [{
      ‘name’: ‘Fotovoltaico’,
      ‘sku’: ‘TAA-BB-Fotovoltaico’,
      ‘category’: ‘Trentino Alto Adige’,
      ‘price’: ‘1’,
      ‘quantity’: ‘1’
      },{
      ‘name’: ‘Riscaldamento Ecologico’,
      ‘sku’: ‘TAA-BB-Riscaldamento-Eco’,
      ‘category’: ‘Trentino Alto Adige’,
      ‘price’: ‘1’,
      ‘quantity’: ‘1’
      },{
      ‘name’: ‘Solare Termico’,
      ‘sku’: ‘TAA-BB-Solare-Termico’,
      ‘category’: ‘Trentino Alto Adige’,
      ‘price’: ‘1’,
      ‘quantity’: ‘1’
      },{
      ‘name’: ‘Geotermico’,
      ‘sku’: ‘TAA-BB-Geotermico’,
      ‘category’: ‘Trentino Alto Adige’,
      ‘price’: ‘1’,
      ‘quantity’: ‘1’
      },{
      ‘name’: ‘Infissi’,
      ‘sku’: ‘TAA-BB-Infissi’,
      ‘category’: ‘Trentino Alto Adige’,
      ‘price’: ‘1’,
      ‘quantity’: ‘1’
      }]
      }];

  6. Pieter Pieter says : Reply

    Hi,

    I have a question about the example you and others use.

    In the example the transaction total is 11.99. But the order consist of three products with the total transaction price of 31.97.

    ‘price’: 11.99,
    ‘quantity’: 1

    ‘price’: 9.99,
    ‘quantity’: 2

    Is the variable “transactionTotal” getting the wrong value ? Should it be:

    ‘transactionTotal’: 31.97,

  7. Steve Steve says : Reply

    Hi Pier,

    A very good and interesting read. We are looking to implement GTM on our eCommerce site which is on megento. Before we simply put the GA tracking code in megento and it did all the rest. What is worrying us is the Data Layer, but reading above most people are too. I have found a plug in http://www.magentocommerce.com/magento-connect/google-tag-manager-3.html. Not sure if you have seen this one, but wondered if you think this good solution to a tricky problem?

    • Hi Steve,

      The plugin you proposed seems like a solution that wasn’t available at the moment I wrote this. I would try it if I were you. Keep in mind that this plugin is not compatible with magento 1.8 as we write those lines, meaning you could have problems using it with a Magento 1.8 install.

  8. Marcelo Marcelo says : Reply

    Hi Pier,

    Good article. Do you know how would the data layer output look like with the new Universal Analytics e-commerce tracking?

    Thanks!

    • Hi Marcelo, this is an interesting question. The truth is, using Universal Analytics or not, the dataLayer is sort of “future proof”. What I mean by that is that, the dataLayer speaks to the Google Tag Manager, not Google Analytics, ensuring that the GTM will do it’s magic and adapt your data to whatever is needed in order for the tracking to work.

      That being said, the only thing that should change in the procedure is to choose “Universal Analytics” instead of the “Classic version” in the tag type dropdown.

      We all know that the Google’s seemless isn’t always as seemless as we would’ve thought in the first place so make sure to validate your data after this massive change, even though everything should go just right. Take note that Google seems to already have thought about this and gives you the chance to come back to an earlier version of your containers, just in case things do work as planned.

  9. Hi Pier-Yves,

    Would another path be to implement the Magento PHP code directly in a macro inside GTM? (create an html object with the PHP values and the dataLayer population)

    In that case, you would be totally independant from the Magento files (except the part where you have to change the standard _gaq.push).

    • Hi Marc-André,

      Sure, you could do some sort of black magic macros in GTM in order to fetch your conversion values directly from HTML tags that you would have on your Thank You page without sending any dataLayer object to the GTM, but that’s a way more advanced technique.

      I’m glad you point it out as it will be the subject to an entirely new how-to article soon!

  10. Eric Eric says : Reply

    In all of the blog posts I’ve come across, the embed code contains sample values, such as:

    ‘transactionId’: ‘1234’,
    ‘transactionAffiliation’: ‘Acme Clothing’,
    ‘transactionTotal’: 11.99,

    I’m working on a music site with 6 albums and ~60 individual songs for sale. Is there a way to dynamically populate these values with what was in the user’s shopping cart? I suspect there is, I just can’t find it.

    Thanks! Great blog – very valuable.

    • Hi Eric! Are you using Magento? If so, this blog post will help you with every steps. Otherwise, you should be able to retrieve this info from your eCommerce platform by adapting the PHP script section with the help of a programmer. There is also a way to do so with advanced macros directly in GTM. Stay tuned, as I will publish an article on that somewhere next week! Thanks.

  11. Mike Mike says : Reply

    Hi Pier!

    Very nice tutorial. One question though: In the first step “Setting up Google Tag Manager”, it says “put the Google Tag Manager snippet right after the opening of the tag” (as is anyway recommended by Google).

    I’m wondering though how this can be correctly set-up in Magento? Via backend “System – Configuration – Design”, snippets can only be added either at the END of head or END of body – but not after the opening body.

    Any recommendations?

    • Hi Mike, that’s indeed a good question.

      In order for this to work, you will need to have your theme modified. You can either modify your header directly through your theme or adapt the Google Analytics module to do so. I prefer the second option. Please have a look at this section of the article, you’ll have the steps towards doing this.

      Thanks!

      • Mike Mike says : Reply

        Hi Pier!

        Thanks for the quick response. Okay, now I see – when following/reading the tutorial, I didn’t make the connex from you mentioning “it should be added at the beginning of the body”, to your actual description “Adding the Google Tag Manager Snippet to your Magento Installation” of how to do so.

        I gave this a try now – however, I didn’t have the ga.phtml file in my template directory, therefore I copied it from the base template. After modifying as described above, it is still injecting the wrong code though (still injecting a GA snippet instead of the GTM snippet – seems it doesn’t use my newly created ga.phtml).
        In case u have any ideas on that, happy to hear your feedback.

        Thanks anyways,
        Mike

        • Hi Mike,

          Do you have any sort of cache enabled? Maybe that’s why it doesn’t trigger. Otherwise, try to modify the base version directly as it might work!

          Thanks.

          • Mike Mike says :

            Hi Pier,

            tried that already before, didn’t work either though.
            Nothingtheless, if I only activate Google Analytics in Backend (as in your screenshot above), I would assume it shld also be placed right at the beginning of , no? In my case, it is also still embedded somewhere withing head section (therefore, changing the snippet to include GTM instead of GA wld not pop up in the right place anyway, would it?)

            If it wasn’t just me, maybe it wld make the article even clearer if you were to clarify that “Here’s a way to update your Magento install in order to make the GTM pop right in place.” refers to “right place (:= beginning of body section).

  12. Max Max says : Reply

    Hi Pier-Yves,

    Why are you assigning the transaction as the only element in the dataLayer array
    dataLayer = [{…}];

    Instead of adding the element to it using the push method:
    dataLayer.push({…});

    Like we see in the GTM documentation:
    https://developers.google.com/tag-manager/devguide

    Thanks,
    Max

    • Hi Max,

      Both ways are good. As I mentioned, there is many ways of getting things done.

      As shown here, it removes any visit information from the thank you page dataLayer replacing it by the transaction data only and it works for me.

      The dataLayer.push() can be used instead if you want to have your TY page visits shown in Google Analytics, but it’s not my case. That is definitely a good point though and it is good you mention it.

      Thanks!

  13. Scotty Scotty says : Reply

    Hi Pier-Yves,

    Great guide! We have successfully used GTM with ecommerce tracking, fired with conditions {{event}} equals transactionEvent. With Universal Analytics Google has updated the tracking script according to this page: https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce.

    My questions, how should you fire the ecom tag in GTM with this new syntax? It obviously don’t fire with the rule above. However, when only using the Universal tracking code (GTM disabled) ecom data flows to Analytics.

    Thanks a lot!

    • Hi Scotty,

      I’m glad that you like this guide.

      I know that Google issued a whole lot of new functions along with the Universal Analytics switch. It is good that you pointed it out as it’s a must have for non-GTM users.

      Now for the GTM part: I’m happy to tell you that there is nothing to change to the dataLayer object. The only thing that will change is your GTM tags. Instead of being “classic Analytics” tags, your just change them to “Universal Analytics” tags. You will still need the “transaction” and “page view” type tags though. The macros stay the same.

      Thanks.

  14. Niel Niel says : Reply

    Hi Pier-Yves regarding your response to scotty, i don’t can you please give an code example?

    • Hi Niel, What do you mean by code example? There’s actually no code change from what is described in the article itself (above). The only thing that changes is the GTM tag type. So, under the “Creating The Google Analytics Conversion Tag” section, all you need to change is the type: From “Google Analytics” to “Universal Analytics”. Hope this helps!

  15. alex alex says : Reply

    Hi Pier,

    Kindly check the below code, which we have updated now and its working and tracking in our local server, But If it comes to live data’s are not fetching. But our site has SSL secured server, so is this a cause for tracking problem?

    dataLayer =[{
    “event”:”trackTransaction”,
    “transactionId”:”100013827″,
    “transactionAffiliation”:”Digital Product”,
    “transactionTotal”:99,
    “transactionShipping”:0,
    “transactionTax”:0,
    “transactionProducts”:[{
    “sku”:”EM-TYO”,
    “name”:”Fiverr Clone”,
    “category”:”Software”,
    “price”:99,
    “quantity”:1}]}];

    Screen shot Link: http://imgur.com/qKDvZH3

    GTM rules mentioned given below for your refer.
    {{event}} equals trackTransaction

    • Hi Alex,

      Everything looks good from here. Do you guys have any cache enabled live that would prevent the dataLayer from showing live?

      After that, did you put the gtm.dom event also in your tag firing rule?

      BTW, the screenshot doesn’t show me any anomaly. What do you see as wrong?

      Have a nice day!

  16. Sam Sam says : Reply

    I am getting this error message when I put the code on my website:
    Parse error: syntax error, unexpected ‘protected’ (T_PROTECTED)

    Do you know what I am doing wrong?

    Thank you for your help!

  17. jeff jeff says : Reply

    i am a beginner so i was wondering if you could provide some insight…

    I have been asked to develop an ecomm layer for a client’s partner in sales. Site ABC sells insurance and when a user clicks ‘view plans’ they are taken to Site DEF to view plans and make a purchase.
    Site ABC and DEF will have the same GTM container code. However since we want to track ecomm transactions on site DEF we need to tell them what data layer code to add to their site (since we do not have access to it)

    I am a bit confused as to what dataLayer code to provide them. My confusion stems from the example provided to me on https://support.google.com/tagmanager/answer/3002596?hl=en – for the info provided for ‘transactionId’ is ‘1234’ and for ‘transactionTotal’ is ‘38.26’ and so on but the purchase data is variable so what do i put for these?

    dataLayer = [{
    ‘transactionId’: ‘1234’,
    ‘transactionAffiliation’: ‘Acme Clothing’,
    ‘transactionTotal’: 38.26,
    ‘transactionTax’: 1.29,
    ‘transactionShipping’: 5,
    ‘transactionProducts’: [{
    ‘sku’: ‘DD44’,
    ‘name’: ‘T-Shirt’,
    ‘category’: ‘Apparel’,
    ‘price’: 11.99,
    ‘quantity’: 1
    },{
    ‘sku’: ‘AA1243544’,
    ‘name’: ‘Socks’,
    ‘category’: ‘Apparel’,
    ‘price’: 9.99,
    ‘quantity’: 2
    }]
    }];

    Thanks for any help you can provide to this beginner

    • Hi Jeff,

      The data of the dataLayer is variable indeed. You will need to provide the good values of the transaction with variables, as stated in the article at the PHP section of it. “1234” and “38.26” are just samples and must be replaced by valid data.

      Hope that helps.

  18. Mike Mike says : Reply

    Hi Pier,

    I have successfully setup ecommerce tracking according to your very helpful guide above.

    After some weeks of observations, we realized that not all transactions are properly tracked (about 25 % of all successful transactions never fire). The problem here is that apparently those users do not navigate to the Thank you page (/checkout/onepage/success). As far as I understood and observed, this page is only opened AFTER a successful payment, and when the user decides to (usually manually) navigate back to our shop. If a user doesn’t navigate back, the ThankYou page is never called, thus we can’t track this one.

    Q: how could we make sure the ThankYou page is always hit? Is there another/better place to fire the transaction-success?
    (PS: this happens randomly across all our 3 different payment providers…indicating that it depends on the behavior of the user after purchase is through).

    Looking fwd to your feedback!

    • Hi Mike,

      I’m glad this tutorial made it for you too. Does the 25% of failed transactions come from Paypal? If so, you will need to have a Paypal Express checkout in order to complete the transaction from your Website instead of on Paypal.

      That way, none of your Paypal buyers will drop after payment.

      Hope that helps.

      • Victoria Victoria says : Reply

        Hi Pier,

        Thanks for a really informative article.
        Just to check, if one doesn’t have Paypal Express – Paypal buyers will all drop off and transaction data will not be collected for them?

        Thanks 🙂

        • Hi Victoria,

          In fact, the only difference is that Paypal express finishes the transaction in Magento. If you use Paypal Standard, you will need your customer to come back on your thank you page after he does his payment (the will be a thank you page in paypal telling they will be redirected to the website). If they do not come back, they will never see the Thank you page, so does your dataLayer.push().

          Hope it helps!

  19. Sam Sam says : Reply

    Where do I put the code for the function _getOrdersTrackingCode() ? I am getting an error when I put it on the success page

  20. Boki Boki says : Reply

    I didn’t find folder /GoogleAnalytics/ on my installation of Magento CE 1.7.0.1 or any further mentioned folders or files.

    File: /app/code/local/Mage/GoogleAnalytics/Block/Ga.php

  21. Eva Eva says : Reply

    Hi,
    I am using the HTML code to measure e-commerce transactions on a website. Do I have to generate any Macro on GTM to capture e-commerce information with the dataLayer? Thought that this Macro was necessary so GTM could read the information of the dataLayer values… I did it so with the custom dimensions.
    Thanks

  22. Mecci Mecci says : Reply

    Hi,

    I am trying to implement eCommerce tracking for one of my clients. The website does not support dataLayer, how do i implement the eCommerce tracking using custom javaScript. Would appreciate if you could help me here or guide me to a place where i can read this up.

    Thanks in advance,

    • Hi,

      I suggest you read the article entirely. It should provide you with instructions to do so but you might need to tweak things a bit. Just replace the Magento file paths with your application’s and it should be a good starting point.

      All you’ll need different is to put the dataLayer object on your eCommerce thank you page.

      Hope that helps.

  23. Vivek Vivek says : Reply

    What about dataLayer.push();

    Do we need to do in magento even if we are using google-tag-manager plugin and configured everything else ?

  24. Daniel Daniel says : Reply

    Hi Pier,

    Do you have to create a separate ‘listener’ on GTM or does “equals > event >gtm.com” automatically do that?

    Also do you have to turn off GA on magento?

    For some reason the information is just not pulling through to analytics

    • Hi Daniel,

      there is no listener whatsoever to pub aside from the ‘transaction’ tag. You will need to have GA turned on in order to show the modified scripts in GA.php.

      Go ahead and test a full transaction with the debug mode activated. This way, you’ll see what gets fired and if there is something missing.

      Hope it helps!

  25. Minime Minime says : Reply

    I am a newbie with GTM and I noticed there are tons of things to learn and setup in GTM. Things to take consideration regarding the environment I work in:

    I work with VB.NET, so every file I work with has a mark-up page (.aspx) and a codebehind (.aspx.vb)

    My questions are the following:

    1) I understand that, for eCommerce, the following Data Layer must be located in the .aspx page of my code:

    Beginning of DATA LAYER

    dataLayer = [{
    ‘transactionId’: ‘1234’,
    ‘transactionAffiliation’: ‘Acme Clothing’,
    ‘transactionTotal’: 38.26,
    ‘transactionTax’: 1.29,
    ‘transactionShipping’: 5,
    ‘transactionProducts’:
    [{
    ‘sku’: ‘DD44’,
    ‘name’: ‘T-Shirt’, ‘
    category’: ‘Apparel’,
    ‘price’: 11.99,
    ‘quantity’: 1
    }]
    }];

    END OF DATA LAYER SCRIPT

    GTM CODE GOES HERE

    I understand that the variables such as ‘Acme Clothing’, ‘T-Shirt’, ‘Apparel’, etc. can be changed as well as the prices when we ‘push’ info into the datalayer.

    I also understand that the transactionProducts is basically an array of products.

    How would I go about ADDING new products (arrays) to the array of products in the data layer? For instance, if I have 2 or 3 or 5 products? I know I will write a loop, but can someone provide me with a vb.net example on how to do this and change/modify the .aspx GTM data layer script from code behind? Is my data layer in the .aspx correctly setup?

    How would I go about modifying/pushing data into the data layer from the vb.net (.aspx.vb) code behind? Any short examples or hints will be greatly appreciated.

    I am really confused about this as I cannot find any examples online.

    Any help will be appreciated.

    Thank you

    • Hi Minime,

      I’m not a big ASP.net user but it should be the same process.

      Since the tracking is client-side, you should have everything pushed in javascript.

      As for the products, it’s a simple array of javascript objects, so just push some more products in there.

      Hope it helps!

  26. Any Any says : Reply

    Thanks for this detailed guide.

    I have implemented it on site http://staging.evemattress.co.uk .
    app/code/local/Mage/GoogleAnalytics/Block/Ga.php
    protected function _getOrdersTrackingCode()
    {
    $orderIds = $this->getOrderIds();
    if (empty($orderIds) || !is_array($orderIds)) {
    return;
    }
    $collection = Mage::getResourceModel(‘sales/order_collection’)
    ->addFieldToFilter(‘entity_id’, array(‘in’ => $orderIds))
    ;

    //Replacing analytics code with GTM code

    //GTM tracking Starts
    $aOrders = array();
    foreach ($collection as $order) {
    $objOrder = new stdClass();
    $objOrder->transactionId = $order->getIncrementId();
    $objOrder->transactionAffiliation = Mage::app()->getStore()->getFrontendName();
    $objOrder->transactionTotal = $order->getBaseGrandTotal();
    $objOrder->transactionTax = $order->getBaseTaxAmount();
    $objOrder->transactionShipping = $order->getBaseShippingAmount();

    $aItems = array();
    foreach ($order->getAllVisibleItems() as $item) {
    $objItem = array();
    $objItem[‘sku’] = $item->getSku();
    $objItem[‘name’] = $item->getName();
    $objItem[‘category’] = null; //todo
    $objItem[‘price’] = $item->getBasePrice();
    $objItem[‘quantity’] = $item->getQtyOrdered();
    $aItems[] = (object) $objItem;
    }

    $objOrder->transactionProducts = $aItems;
    $aOrders[] = $objOrder;
    }
    return (empty($aOrders))? null : sprintf(‘dataLayer.push(%s);’, json_encode($aOrders));
    //GTM tracking ends
    }

    Unfortunately my dataLayer is not getting populated with transaction details.
    I confirmed tag firing in GTM debug mode, but its not populating dataLayer.
    https://drive.google.com/file/d/0BxhQ6CCx580FVmN0eWpvNUJKTkU/view?usp=sharing

    Can you please help me to troubleshoot the issue?

    • Hi,

      From what I see here, you changed the method to use dataLayer.push() which is ok. Keep in mind that when you do that, you don’t want to push an array, you will want to push an object.

      Good thing is I updated the post to reflect the dataLayer.push() method instead. This way, no more confusion for nobody!

      Have a good day!

  27. Any Any says : Reply

    Thanks for the quick reply.

    I replaced code with this one:
    protected function _getOrdersTrackingCode()
    {
    $orderIds = $this->getOrderIds();
    if (empty($orderIds) || !is_array($orderIds)) {
    return;
    }
    $collection = Mage::getResourceModel(‘sales/order_collection’)
    ->addFieldToFilter(‘entity_id’, array(‘in’ => $orderIds))
    ;

    //Replacing analytics code with GTM code

    //GTM tracking Starts
    $aOrders = array();
    foreach ($collection as $order) {
    $objOrder = new stdClass();
    $objOrder->transactionId = $order->getIncrementId();
    $objOrder->transactionAffiliation = Mage::app()->getStore()->getFrontendName();
    $objOrder->transactionTotal = $order->getBaseGrandTotal();
    $objOrder->transactionTax = $order->getBaseTaxAmount();
    $objOrder->transactionShipping = $order->getBaseShippingAmount();

    $aItems = array();
    foreach ($order->getAllVisibleItems() as $item) {
    $objItem = array();
    $objItem[‘sku’] = $item->getSku();
    $objItem[‘name’] = $item->getName();
    $objItem[‘category’] = null; //todo
    $objItem[‘price’] = $item->getBasePrice();
    $objItem[‘quantity’] = $item->getQtyOrdered();
    $aItems[] = (object) $objItem;
    }

    $objOrder->transactionProducts = $aItems;
    $aOrders[] = $objOrder;
    }
    $strToReturn = ”;
    foreach($aOrders as $objFinalOrder){
    $strToReturn .= sprintf(‘dataLayer.push(%s);’, json_encode($objFinalOrder));
    }

    return $strToReturn;
    //GTM tracking ends
    }

    But unfortunately still not populating dataLayer when I checked it in GTM debug mode.

    • Do you get anything to output on the thank you page?

      • marcus marcus says : Reply

        Hello, thank you for the detailed article! I’m also having the same issue, my transactions tag that I setup in GTM is firing on the Thank You page, but the dataLayer is still not populated with the order information. Do you have any ideas to help me troubleshoot this?

        Thanks

        • Hi Marcus,

          It will be hard for me to troubleshoot the issue without access to your things, but I can lead you in the right direction!

          Make sure you:
          – have installed the Google Tag Assistant plugin.
          – have activated the Preview and Debug mode for the current GTM container. More on this here.

          After this, if you get the GTM fired up with all the proper tags dans that the dataLayer is indeed populated with the right data the problem should be in your GTM tag configuration.

          I hope it helps!

  28. Simone Simone says : Reply

    Wow, nice! Thanks!
    And if i have configurable products, how can i add in the datalayer the sku for the single “option” product?
    i think it is needed another “for each” for check the skus inside the product.
    Thanks.

  29. tadhg tadhg says : Reply

    Fantastic stuff. It seems with version 2 of GTM most data layer code can be managed from the GTM interface. I’ve replaced analytics with tag manager in my magento installation as a result lost magento’s own onepage checkout reporting, I dont see where users are dropping out of the checkout process anymore, do have any plans to write an article about that? most stuff available online relates to GTM version 1 so i’m finding it difficult to learn about version 2!

  30. Martina Martina says : Reply

    I also get the error;

    Parse error: syntax error, unexpected ‘protected’ (T_PROTECTED)

    and I do have the <?php opening tag in place.

    Is this because the class declaration is missing?

    • Hi Martina!

      I also came across this problem a few months ago. The problem comes from something missing in your script. Maybe a missing “;” or “}”. I would double check that.

      After that, make sure that the function can be accessed from the thank you page. Some 3rd party themes remove default Magento files from the thank you page.

      Hope it helps!

  31. tom tom says : Reply

    Dear Pier,
    My magento is 1.6.1.0 version and have no ga.phtml file, In this case where can i paste the GTM code? thank you.

    • Hi Tom,

      You can pick the default one (and copy it in your theme directory, do not modify the base files) here:
      /app/design/frontend/base/default/template/googleanalytics/ga.phtml

      I hope it helps!

  32. Nicolas Colombres Nicolas Colombres says : Reply

    Hello Pier,

    Im starting my journey in GTM and this article is very helpfull to understand it better. Thanks alot men!

  33. Nik Nik says : Reply

    Hi,

    We’re placing foll. ecommerce code before GTM snippet (.push is not used). And we want the code to fire when the confirmation page loads. So will the code fire everytime or are there any scenarios when it won’t fire?:

    dataLayer = [{
    ‘transactionId’: ‘[variable]’,
    ‘transactionAffiliation’: 0 ,
    ‘transactionTotal’: [variable],
    ‘transactionTax’: [variable],
    ‘transactionShipping’: 0,
    ‘transactionProducts’: [{
    ‘sku’: ‘[variable]’,
    ‘name’: ‘[variable]’,
    ‘category’: ‘[variable]’,
    ‘price’: [variable],
    ‘quantity’: [variable]
    }]
    }];

    Thanks,
    Nik

    • Hi, this should fire everytime the page loads. I would not recommend not using the dataLayer.push() method as it will break your GA data, whereas attribution and conversion paths won’t be made just to name a few.

      I would recommend using this after the GTM tag instead:
      dataLayer.push({
      ‘transactionId’: ‘[variable]’,
      ‘transactionAffiliation’: 0 ,
      ‘transactionTotal’: [variable],
      ‘transactionTax’: [variable],
      ‘transactionShipping’: 0,
      ‘transactionProducts’: [{
      ‘sku’: ‘[variable]’,
      ‘name’: ‘[variable]’,
      ‘category’: ‘[variable]’,
      ‘price’: [variable],
      ‘quantity’: [variable]
      }]
      });

Leave a Reply

 
 
TOP