How to add ecommerce tracking with gtag in magento order success

By | December 10, 2019
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 gtag.js as your Google Analytics tag and you have Ecommerce reporting enabled, you can measure ecommerce transactions.

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

<script type="text/javascript">
  <!-- Your google tag manager code must be above -->
  var i = 0;
  var items = [];
  <?php foreach($order->getAllVisibleItems() as $item):?>
  	  items[i] = {
          'id': <?php echo $item->getProductId()?>,
          'name': '<?php echo $item->getProduct()->getName()?>',
          'category': '',
          'brand': '<?php echo $item->getProduct()->getAttributeText('manufacturer')?>',
          'variant':  '<?php echo $item->getSku()?>',
          'price': '<?php echo $item->getPrice()?>',
          'quantity': '<?php echo $item->getQtyOrdered()?>',
  <?php endforeach;?>

  gtag('event', 'purchase', {
    "transaction_id": "<?php echo $order->getIncrementId();?>",
    "affiliation": "Google online store",
    "value": '<?php echo $amount?>',
    "currency": "USD",
    "tax": '<?php echo $order->getTaxAmount()?>',
    "shipping": '<?php echo $order->getShippingAmount()?>',
    "items": items