How to add ecommerce tracking with gtag in magento order success

By | April 10, 2022
Spread the love

Every merchant wants to track their sales in google analytics. Currently google have changed google analytics (GA) to google tag manager(GTag). If you use gtm.js as your Google Analytics tag and you have Ecommerce reporting enabled, you can measure ecommerce transactions.

<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=
        'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','{your-gtm-id}');</script>

 

To measure a transaction, send a purchase event with the items in the transaction. For example:

<?php if($order && $order->getId()):?>
<script type="text/javascript">
var i = 0;
var items = [];
<?php foreach($order->getAllVisibleItems() as $item):?>
    <?php 
        $categoryName = '';
        $product      = ObjectManager::getInstance()->create("\Magento\Catalog\Model\Product")->load($item->getProductId());
        if($product && $product->getId() && $product->getCategoryIds()){
            $categoryIds  = $product->getCategoryIds();
            if (isset($categoryIds[0])){
                $category     = ObjectManager::getInstance()->create("\Magento\Catalog\Model\Category")->setStoreId(1)->load($categoryIds[0]);
                $categoryName = $category->getName();
            }
        }
    ?>
    items[i] = {
         item_id: '<?php echo $item->getSku()?>',
         item_name: "<?php echo $item->getProduct()->getName()?>",
         affiliation: "xxxxxxx",
         currency: "USD",
         discount: <?php echo number_format($order->getDiscountAmount(),2)?>, 
         index: i,
         item_brand: "<?php echo $item->getProduct()->getBrandName()?>",
         item_category: "<?php echo $categoryName;?>",
         item_variant: "main",
         price: <?php echo number_format($item->getPrice(),2); ?>,
         quantity: <?php echo intval($item->getQtyOrdered())?>,
    };
    i++;
<?php endforeach;?>

dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
dataLayer.push({
  event: "purchase",
  ecommerce: {
      transaction_id: '<?php echo $order->getIncrementId();?>', 
      affiliation: "xxxxxx",
      value: <?php echo number_format($order->getGrandTotal(),2); ?>,
      tax: <?php echo number_format($order->getTaxAmount(),2)?>,
      shipping: <?php echo number_format($order->getShippingAmount(),2); ?>,
      discount: <?php echo number_format($order->getDiscountAmount(),2)?>, 
      currency: "USD",
      coupon: "<?php echo $order->getCouponCode();?>",
      items: items
  }
});
</script>
<?php endif;?>

 

See google guide here

https://developers.google.com/analytics/devguides/collection/ga4/ecommerce?client_type=gtm#add_or_remove_an_item_from_a_shopping_cart