<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">
Go to top icon

Tracking Magento 2 backend orders in Google Analytics using Measurement Protocol

Sarang Bhantar Sep 29, 2018

Magento 2.0 eCommerce Google Analytics

e-Commerce tracking is of immense importance and a significant number of merchants use Google Analytics for tracking all the transactions or order details. Though Magento 2 has the inbuilt implementation to send the transaction/order details placed on webstore or frontend to Google Analytics, it lacks the same ability when orders are being placed from the Magento backend, the admin, or when orders are created programmatically. This problem further leads to a situation where reports from Google Analytics won't match the reports generated from Magento. Imagine if your financial reports are missing a bulk of the orders.

To overcome this issue we can make use of the Measurement Protocol provided by Google and implement it into Magento 2. Before we begin please read and get an overview of the Measurement Protocol that will be useful to understand and customize if your requirement is different from what has been explained in this blog.

Create a custom module in Magento 2 or make use of an already created module, the choice is yours. Once you have the basic skeleton of your module we can move ahead.

Step 1: Add an Observer

We will make use of an observer that will catch the event when an order is being created in Magento Admin. For implementing this define the oberver event and the class that will take action on that event in the events.xml file which should be located in the etc/adminhtml folder in your module, the path will be like MyPackage/MyModule/etc/adminhtml/events.xml and the code can be like below:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_model_service_quote_submit_success">
<observer name="mymodule_analytics_order_success" instance="MyPackage\MyModule\Observer\AdminOrderPlaced"/>
</event>
</config>

We have placed the events.xml inside adminhtml directory because we want to catch the event only when the order is placed in the adminhtml area of Magento.

Why use the event "sales_model_service_quote_submit_success" ? The reason to use this particular event is because at this point in the order creation process the order is actually saved in the database and the entity id for the order is generated. So at this point we will be assured that the order is successfully placed in Magento and is ready to be sent in Google Analytics. You can modify the event according to your needs.

Create the class that will take action on the event we want to listen. In this case create file AdminOrderPlaced.php under MyPackage\MyModule\Observer, and put the below code in this file.

<?php
namespace MyPackage\MyModule\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
class AdminOrderPlaced implements ObserverInterface
{
/**
* @var \Magento\Sales\Model\Order
*/
protected $_order;
/**
* @var \MyPackage\MyModule\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Framework\App\State
*/
protected $_state;
/**
* @param \MyPackage\MyModule\Helper\Data $data
* @param \Magento\Framework\App\State $state
*/
public function __construct(
\MyPackage\MyModule\Helper\Data $data,
\Magento\Framework\App\State $state
)
{
$this->_helper = $data;
$this->_state = $state;
}
public function execute(EventObserver $observer)
{
$this->_order = $observer->getOrder();
$this->_helper->sendOrderToGoogle($this->_order);
}
}

In the above code we have injected a helper class which we will create shortly and we will define a function in this class that will implement the Measuremet Protocol API, helper class will be useful in case your application is creating orders from multiple code sections like programmatic approach so just by calling the functions defined in this helper class will make your life easy. The helper function will accept an object of Sales/Order so we don't have to reload the order object again in this case.

Step 2: Saving Google Analytics Tracking Id in Magento 2

Add the Google Analytics Tracking Id (Example: UA-XXXXXXX-X) into Magento configuration. You can find the tracking id from your analytics account, navigate to Admin Settings -> Property Settings. To save this id in Magento 2 navigate to Stores -> Configuration -> Sales -> Google API -> Google Analytics. In this configuration select 'Universal Analytics' under Account Type, enter the tracking id into the Account Number field and save the configuration.

Add the Helper Class

Now lets create a helper function which will implement the API used to send the order information to Google. Create a new file Data.php under directory MyPackage\MyModule\Helper containg the below code

<?php
namespace MyPackage\MyModule\Helper;
use \Magento\Framework\App\Helper\AbstractHelper;
class Data extends AbstractHelper
{
const GA_PROPERTY_ID = "google/analytics/account";

/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_scopeConfig;

/**
* @var \Magento\Framework\HTTP\Client\Curl
*/
protected $_curl;

/**
* @var \Magento\Framework\HTTP\Header
*/
protected $_http;

/**
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Framework\HTTP\Client\Curl $curl
* @param \Magento\Framework\HTTP\Header $http
*/
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\HTTP\Client\Curl $curl,
\Magento\Framework\HTTP\Header $http
)
{
$this->_storeManager = $storeManager;
$this->_scopeConfig = $scopeConfig;
$this->_curl = $curl;
$this->_http = $http;
}
public function sendOrderToGoogle(\Magento\Sales\Model\Order $order)
{
$data = [];
$url = 'https://www.google-analytics.com/collect';
$debugUrl = "https://www.google-analytics.com/debug/collect"; // Change url for testing the API

if($order->getId()) {
$store = $this->_storeManager->getStore($order->getStoreId());

$gaId = $this->_scopeConfig->getValue(self::GA_PROPERTY_ID,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$store);

$affiliation = 'admin'; // To recognize that order is placed in admin
if($gaId) {
$data['v'] = 1;
$data['tid'] = $gaId;
$data['cid'] = $order->getCustomerId();
$data['t'] = 'transaction';
$data['ta'] = $affiliation;
$data['ti'] = $order->getIncrementId();
$data['tr'] = $order->getGrandTotal();
$data['ts'] = $order->getShippingAmount();
$data['tt'] = $order->getTaxAmount();
$data['cu'] = 'USD';

if($this->sendData($data,$url)) {
// If order is sent successfully send order items
$data = [];
$data['v'] = 1;
$data['tid'] = $gaId;
$data['cid'] = $order->getCustomerId();
$data['t'] = 'item';
$data['ti'] = $order->getIncrementId();
foreach($order->getAllVisibleItems() as $item) {
$data['in'] = $item->getName();
$data['ip'] = $item->getPrice();
$data['iq'] = $item->getQtyOrdered();
$data['ic'] = $item->getSku();
$data['cu'] = 'USD';
$this->sendData($data,$url);
}
}
}
}
}
private function sendData($data,$url)
{
$url = $url."?".http_build_query($data);
$userAgent = $this->_http->getHttpUserAgent();
if(!$userAgent) { // User agent is a required option
$userAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311
Firefox/2.0.0.13';
}

$curlOptions = array(CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_TIMEOUT => 10,
CURLOPT_USERAGENT => $userAgent);
try {
$this->_curl->setOptions($curlOptions);
$this->_curl->get($url);
$response = $this->_curl->getBody();
if($this->_curl->getStatus() != 200)
return false;
} catch(Exception $e) {
return false;
}
return true;
}
}

Notice the function sendOrderToGoogle where we are making a curl request to the API url and sending the necessary order details. The user agent has to be set so make sure that it is sent in the request. You can debug your implementation by changing the API url to a debug url commented in the code. Go through the documentation of validating hits here.

Important Note: The transactions will be reflected in Google Analytics within 48 hours, so do not expect to see your orders instantly in analytics.

Similarly you can implement other data tracking requirements in Magento 2.

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.