Universal Analytics could not track transaction in magento
Asked Answered
O

3

6

I'm using magento C.E 1.7. Recently I migrated to universal analytics from google analytics.

After migration, except transaction data, other details are tracked fine.

I have added the following script in head.phtml for universal analytics.

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXX-2', 'mysite.com');
  ga('send', 'pageview'); 
  ga('require', 'ecommerce', 'ecommerce.js');
  ga('ecommerce:send'); 


</script> 

In admin side too, I have saved the universal analytics tracking code.

What am I doing wrong? Why can't I track transaction data? Can anyone help on this?

Orian answered 6/3, 2014 at 15:48 Comment(1)
There is no transaction or product data in your post. You can look in the documentation (developers.google.com/analytics/devguides/collection/…) to see what this is supposed to look like.Paraclete
B
17

Hi I have the same problem today I have written a solution but first remove the custom script in your head.phtml...


First add the ga.phtml

You need to create new file in your template folder or edit the default one:

MAGENTOROOT/app/design/frontend/YOURTHEME/template/googleanalytics/ga.phtml

And add this in the file which will override the base/default Magento ga.phtml

<?php if (!Mage::helper('core/cookie')->isUserNotAllowSaveCookie()): ?>
<?php $accountId = Mage::getStoreConfig(Mage_GoogleAnalytics_Helper_Data::XML_PATH_ACCOUNT) ?>
<!-- BEGIN GOOGLE ANALYTICS CODEs -->
<script type="text/javascript">
//<![CDATA[
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    <?php echo $this->_getPageTrackingCode($accountId) ?>
    <?php echo $this->_getOrdersTrackingCode() ?>
//]]>
</script>
<?php endif; ?>

Overide the Default GoogleAnalytics Block

This is not the best way to do it but for simplicity I will use this if you want more clean solution you need to create module and add the rewrite code there.

Ok first copy the content of this file:

MAGENTOROOT/app/code/core/Mage/GoogleAnalytics/Block/Ga.php

and create new file in code/local which will override the code/core one:

MAGENTOROOT/app/code/local/Mage/GoogleAnalytics/Block/Ga.php

In the new file that you have created modify this two functions to match this code:

_getPageTrackingCode($accountId)

protected function _getPageTrackingCode($accountId)
{
    $pageName   = trim($this->getPageName());
    $optPageURL = '';
    if ($pageName && preg_match('/^\/.*/i', $pageName)) {
        $optPageURL = ", '{$this->jsQuoteEscape($pageName)}'";
    }
    // if you can think of better way to get the host name
    // let me know in the comments.
    $hostName = $_SERVER['SERVER_NAME'];
    return "
        ga('create', '".$this->jsQuoteEscape($accountId)."', 'auto');
        ga('send', 'pageview' ".$optPageURL.");
    ";
}

_getOrdersTrackingCode()

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))
    ;
    $result = array("
        // Transaction code...
        ga('require', 'ecommerce', 'ecommerce.js');
    ");

    foreach ($collection as $order) {
        if ($order->getIsVirtual()) {
            $address = $order->getBillingAddress();
        } else {
            $address = $order->getShippingAddress();
        }

        $result[] = "
            ga('ecommerce:addTransaction', {
                id:          '".$order->getIncrementId()."', // Transaction ID
                affiliation: '".$this->jsQuoteEscape(Mage::app()->getStore()->getFrontendName())."', // Affiliation or store name
                revenue:     '".$order->getBaseGrandTotal()."', // Grand Total
                shipping:    '".$order->getBaseShippingAmount()."', // Shipping cost
                tax:         '".$order->getBaseTaxAmount()."', // Tax

            });
        ";

        foreach ($order->getAllVisibleItems() as $item) {

            $result[] = "
            ga('ecommerce:addItem', {

                id:       '".$order->getIncrementId()."', // Transaction ID.
                sku:      '".$this->jsQuoteEscape($item->getSku())."', // SKU/code.
                name:     '".$this->jsQuoteEscape($item->getName())."', // Product name.
                category: '', // Category or variation. there is no 'category' defined for the order item
                price:    '".$item->getBasePrice()."', // Unit price.
                quantity: '".$item->getQtyOrdered()."' // Quantity.

            });
        ";

        }
        $result[] = "ga('ecommerce:send');";
    }
    return implode("\n", $result);
}
Burks answered 7/3, 2014 at 14:47 Comment(9)
And then use the magento admin panel to add the tracking code in : System > Configuration > Sales | Google API | Google AnalyticsBurks
Excellent answer! Congratulations! Just one question: Isn't there required also an update in the GoogleAnalytics/Model/Observer.php ? The method injectAnalyticsInGoogleCheckoutLink is still using the old _gaq.push functions from the old ga.jsBondy
Excellent answer, thanks for sharing :)! Worked like a charm. I needed GA Universal to add multiple tracking (support.google.com/analytics/answer/1032400?hl=en) to my Magento website, had to hack the code a little bit but it worked just fine.Booher
@Bondy yes that would need to be changed but is only needed if you are using Google Checkout for processing payments.Hoist
This was very useful. For those of us still using Magento 1.3.x I adapted this code into the older Magento core module code to update the analytics code to Universal for Magento 1.3.x too. github.com/gaiterjones/magento-google-universal-analyticsSexy
I posted a note below on how to correctly set cookie domain.Teletype
I have 2 stroes, one is using google analytics and the other one is universal analytics. I have overrided the class Ga.php and added the functions as _getOrdersTrackingCodeUniversal() and _getPageTrackingCodeUniversal($accountId) with the above said universal analytics code. I have implemented your code ga.phtml in the stores theme folder and called the above mentioned functions. The page tracking code is working when i saw in view source. But my orders are not tracked in google analytics. Kindly tell us what is wrong in my implementation?Frey
Hi alamelu for which store you are not seeing the orders for the one whit universal analytics or the one whit the default analytics?Burks
Hi @Frey have you set E-commerce to on on your analytics property see this link support.google.com/analytics/answer/1009612?hl=en-GBBurks
T
0

It's important to note on Daniel's answer that cookie domain is not getting set correctly.

Change this line:

ga('create', '".$this->jsQuoteEscape($accountId)."', '".$hostName."');

To:

ga('create', '".$this->jsQuoteEscape($accountId)."', {'cookieDomain':'".Mage::getStoreConfig('web/cookie/cookie_domain', Mage::app()->getStore() )."'});

It inserts the cookie domain correctly from your Magento config versus using the $hostName value which is not set and results in empty ''.

If you're using a CDN on a subdomain this becomes more important to save on that cookie traffic.

Teletype answered 14/5, 2014 at 23:59 Comment(2)
Hi JaseC thanks for your input but for some reason the var_dump(Mage::getStoreConfig('web/cookie/cookie_domain', Mage::app()->getStore() )) returns string(0) "" which version of magento you are using?Burks
I think much clean will be whit $hostName = $_SERVER['SERVER_NAME'];Burks
R
0

I had the same issue. Then I installed the extension below and now it's all working great. https://magento.mdnsolutions.com/extensions/mdn-google-universal-analytics.html

Hope it can help.

Responsiveness answered 13/11, 2014 at 1:9 Comment(2)
That is a dead link.Deterioration
@Deterioration the links has been fixed. Cheers!Responsiveness

© 2022 - 2024 — McMap. All rights reserved.