Magento 1.9 – Implement E-commerce Datalayer on Success Page

google apimagento-1.9onepage-checkout

I have installed Google Tag Manager and want to add an additional datalayer for ecommerce tracking on success page which contains the transition id, product specific data like sku, price, name, quantity and so on.

I want something like this for my success page after open body tag (pseudocode):

<body>
<script>
   <?php 
       if ( $this->getOrderId() ) $transactionId = $this->getOrderId();
       $currentOrder = Mage::getResourceModel( 'sales/order_collection' )->byId( $transactionId ); 
       $transactionAffiliation = Mage::app()->getStore()->getFrontendName();
       $transactionTotal = $currentOrder->getTotal();
       $transactionTax = $currentOrder->getTax();
       $transactionShipping = $currentOrder->getShipping();
       $transactionProducts = $currentOrder->getProducts();
   ?>
   dataLayer = [{
     'transactionId': <?php echo "'".$transactionId."'" ?>,
     'transactionAffiliation': <?php echo "'".$transactionAffiliation."'" ?>,
     'transactionTotal': <?php echo $transactionTotal ?>,
     'transactionTax': <?php echo $transactionTax ?>,
     'transactionShipping': <?php echo $transactionShipping ?>,
     'transactionProducts': [
      <?php foreach( $transactionProducts as $product ): ?>
         {
         'sku': <?php echo "'".$product->getSku()."'" ?>,
         'name': <?php echo "'".$product->getName()."'" ?>,
         'category': <?php echo "'".$product->getCategory()."'" ?>,
         'price': <?php echo $product->getPrice() ?>,
         'quantity': <?php echo $product->getQuantity() ?>
         },
      <?php endforeach; ?>
      ]
  }];
</script>
...

So I have to replace this pseudocode with "real" Magento code to get the order details on succes page. But which correct functions should I use to implement this?

Hope you can help me 🙂

Best Answer

Here is the code which can go on success page -:

<?php 
$orderId = Mage::getSingleton('checkout/session')->getLastOrderId();
$order = Mage::getModel('sales/order')->load($orderId);
$orderCurrency      = $order->getBaseCurrencyCode();
$orderGrandTotal    = $order->getBaseGrandTotal();
$orderShippingTotal = $order->getBaseShippingAmount();
$orderTax           = $order->getBaseTaxAmount();
$orderItems = $order->getAllVisibleItems();
//exit;
?>
<script type="text/javascript">
//<![CDATA[
    window.dataLayer = window.dataLayer || [];
    <?php $intCtr=0;?>
    dataLayer.push({
      'ecommerce': {
        'purchase': {
          'actionField': {
            'id': '<?php echo $order->getIncrementId()?>',                         // Transaction ID. Required for purchases and refunds.
            'affiliation': '<?php echo $order->getAffiliation() ?>',
            'revenue': '<?php echo $orderGrandTotal?>',                     // Total transaction value (incl. tax and shipping)
            'tax': '<?php echo $orderTax?>',
            'shipping': '<?php echo $orderShippingTotal?>',
            'coupon': '<?php echo $order->getCouponCode() ?>'
          },
          'products': [
          <?php foreach($orderItems as $item): ?>
                <?php $intCtr++;?>
                <?php if($item->getParentItemId()) continue;?>
          {                            
            'name': '<?php echo $this->jsQuoteEscape($item->getName()) ?>',     // Name or ID is required.
            'id': '<?php echo $this->jsQuoteEscape($item->getSku()) ?>',
            'price': '<?php echo $item->getBasePrice()?>',
            'quantity': <?php echo $item->getQtyOrdered()?>
            <?php if ($intCtr==count($orderItems)):?>
}]
            <?php else:?>
},
            <?php endif;?>
            <?php endforeach;?>
        }
      }
    });
//]]>
</script>

If you are not a Magento developer then recommendation is to use good module or extension which gives you much more insight and data to see better reporting in Google Analytics. Have a look at the following module

https://www.scommerce-mage.co.uk/enhanced-ecommerce-tracking-with-google-tag-manager.html

Hope it helps!

Related Topic