Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for Google Analytics 4 Enhanced eCommerce #3198

Merged
merged 15 commits into from
May 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 165 additions & 24 deletions app/code/core/Mage/GoogleAnalytics/Block/Ga.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,36 +197,177 @@ protected function _getOrdersTrackingCodeUniversal()
*/
protected function _getOrdersTrackingCodeAnalytics4()
{
$result = [];
$request = $this->getRequest();
$moduleName = $request->getModuleName();
$controllerName = $request->getControllerName();

//purchase events
$orderIds = $this->getOrderIds();
if (empty($orderIds) || !is_array($orderIds)) {
return '';
if (!empty($orderIds) && is_array($orderIds)) {
$collection = Mage::getResourceModel('sales/order_collection')
->addFieldToFilter('entity_id', ['in' => $orderIds]);
/** @var Mage_Sales_Model_Order $order */
foreach ($collection as $order) {
$orderData = [
'currency' => $order->getBaseCurrencyCode(),
'transaction_id' => $order->getIncrementId(),
'value' => number_format($order->getBaseGrandTotal(), 2),
'coupon' => strtoupper($order->getCouponCode()),
'shipping' => number_format($order->getBaseShippingAmount(), 2),
'tax' => number_format($order->getBaseTaxAmount(), 2),
'items' => []
];

/** @var Mage_Sales_Model_Order_Item $item */
foreach ($order->getAllVisibleItems() as $item) {
$orderData['items'][] = [
'item_id' => $item->getSku(),
'item_name' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'price' => $item->getBasePrice(),
'discount' => $item->getBaseDiscountAmount()
];
}
$result[] = "gtag('event', 'purchase', " . json_encode($orderData, JSON_THROW_ON_ERROR) . ");";
}
}
$collection = Mage::getResourceModel('sales/order_collection')
->addFieldToFilter('entity_id', ['in' => $orderIds]);
$result = [];
/** @var Mage_Sales_Model_Order $order */
foreach ($collection as $order) {
$orderData = [
'currency' => $order->getBaseCurrencyCode(),
'transaction_id' => $order->getIncrementId(),
'value' => number_format($order->getBaseGrandTotal(), 2),
'coupon' => strtoupper($order->getCouponCode()),
'shipping' => number_format($order->getBaseShippingAmount(), 2),
'tax' => number_format($order->getBaseTaxAmount(), 2),
'items' => []

//Begin advanced eCommerce events
//product page
if ($moduleName == 'catalog' && $controllerName == 'product') {
$productViewed = Mage::registry('current_product');
$eventData = [];
$eventData['currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
$eventData['value'] = number_format($productViewed->getFinalPrice(), 2);
$eventData['items'] = [];
$eventData['items'][] = [
'id' => $productViewed->getSku(),
'name' => $productViewed->getName(),
'list_name' => 'Product Detail Page',
'brand' => $productViewed->getAttributeText('manufacturer'),
'category' => 'Products',
'price' => number_format($productViewed->getFinalPrice(), 2),
];

/** @var Mage_Sales_Model_Order_Item $item */
foreach ($order->getAllVisibleItems() as $item) {
$orderData['items'][] = [
'item_id' => $item->getSku(),
'item_name' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'price' => $item->getBasePrice(),
'discount' => $item->getBaseDiscountAmount()
$result[] = "gtag('event', 'view_item', " . json_encode($eventData, JSON_THROW_ON_ERROR) . ");";
}

//category page
elseif ($moduleName == 'catalog' && $controllerName == 'category') {
$layer = Mage::getSingleton('catalog/layer');
$category = $layer->getCurrentCategory();
$productCollection = clone $layer->getProductCollection();
$toolbarBlock = Mage::app()->getLayout()->getBlock('product_list_toolbar');
$pageSize = $toolbarBlock->getLimit();
$currentPage = $toolbarBlock->getCurrentPage();
if ($pageSize !== 'all') {
$productCollection->setPageSize($pageSize)->setCurPage($currentPage);
}
$eventData = [];
$eventData['currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
$eventData['value'] = 0.00;
fballiano marked this conversation as resolved.
Show resolved Hide resolved
$eventData['item_list_id'] = 'category_'.$category->getUrlKey();
$eventData['item_list_name'] = $category->getName();
$eventData['items'] = [];

foreach ($productCollection as $productViewed) {
$eventData['items'][] = [
'id' => $productViewed->getSku(),
'name' => $productViewed->getName(),
'list_name' => 'Product Detail Page',
'brand' => $productViewed->getAttributeText('manufacturer'),
'category' => 'Products',
'price' => number_format($productViewed->getFinalPrice(), 2),
];
$eventData['value'] += $productViewed->getFinalPrice();
}
$eventData['value'] = number_format($eventData['value'], 2);
$result[] = "gtag('event', 'view_item_list', " . json_encode($eventData, JSON_THROW_ON_ERROR) . ");";
}

//cart
elseif ($moduleName == 'checkout' && $controllerName == 'cart') {
$removedProduct = Mage::getSingleton('core/session')->getRemovedProductCart();
if ($removedProduct) {
$_removedProduct = Mage::getModel('catalog/product')->load($removedProduct);
$eventData = [];
$eventData['currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
$eventData['value'] = number_format($_removedProduct->getFinalPrice(), 2);
$eventData['items'] = [];
$eventData['items'][] = [
'id' => $_removedProduct->getSku(),
'name' => $_removedProduct->getName(),
'list_name' => 'Product Detail Page',
'brand' => $_removedProduct->getAttributeText('manufacturer'),
'category' => 'Products',
'price' => number_format($_removedProduct->getFinalPrice(), 2),
];
$result[] = "gtag('event', 'remove_from_cart', " . json_encode($eventData, JSON_THROW_ON_ERROR) . ");";
Mage::getSingleton('core/session')->unsRemovedProductCart();
}

$addedProduct = Mage::getSingleton('core/session')->getAddedProductCart();
if ($addedProduct) {
$_addedProduct = Mage::getModel('catalog/product')->load($addedProduct);
$eventData = [];
$eventData['currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
$eventData['value'] = number_format($_addedProduct->getFinalPrice(), 2);
$eventData['items'] = [];
$eventData['items'][] = [
'id' => $_addedProduct->getSku(),
'name' => $_addedProduct->getName(),
'list_name' => 'Product Detail Page',
'brand' => $_addedProduct->getAttributeText('manufacturer'),
'category' => 'Products',
'price' => number_format($_addedProduct->getFinalPrice(), 2),
];
$result[] = "gtag('event', 'add_to_cart', " . json_encode($eventData, JSON_THROW_ON_ERROR) . ");";
Mage::getSingleton('core/session')->unsAddedProductCart();
}

$productCollection = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();
$eventData = [];
$eventData['currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
$eventData['value'] = 0.00;
discountscott marked this conversation as resolved.
Show resolved Hide resolved
$eventData['items'] = [];

foreach ($productCollection as $productInCart) {
$eventData['items'][] = [
'id' => $productInCart->getSku(),
'name' => $productInCart->getName(),
'list_name' => 'Product Detail Page',
'brand' => $productInCart->getAttributeText('manufacturer'),
'category' => 'Products',
'price' => number_format($productInCart->getFinalPrice(), 2),
];
$eventData['value'] += $productInCart->getFinalPrice();
}
$eventData['value'] = number_format($eventData['value'], 2);
$result[] = "gtag('event', 'view_cart', " . json_encode($eventData, JSON_THROW_ON_ERROR) . ");";
}

//begin checkout
elseif ($moduleName == 'checkout' && $controllerName == 'onepage') {
$productCollection = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();
$eventData = [];
$eventData['currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
$eventData['value'] = 0.00;
$eventData['items'] = [];

foreach ($productCollection as $productInCart) {
$eventData['items'][] = [
'id' => $productInCart->getSku(),
'name' => $productInCart->getName(),
'list_name' => 'Product Detail Page',
'brand' => $productInCart->getAttributeText('manufacturer'),
'category' => 'Products',
'price' => number_format($productInCart->getFinalPrice(), 2),
];
$eventData['value'] += $productInCart->getFinalPrice();
}
$result[] = "gtag('event', 'purchase', " . json_encode($orderData, JSON_THROW_ON_ERROR) . ");";
$eventData['value'] = number_format($eventData['value'], 2);
$result[] = "gtag('event', 'begin_checkout', " . json_encode($eventData, JSON_THROW_ON_ERROR) . ");";
}
return implode("\n", $result);
}
Expand Down
26 changes: 26 additions & 0 deletions app/code/core/Mage/GoogleAnalytics/Model/Observer.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,30 @@ public function setGoogleAnalyticsOnOrderSuccessPageView(Varien_Event_Observer $
$block->setOrderIds($orderIds);
}
}

/**
* Add 'removed item' from cart into session for GA4 block to render event on cart view
*
* @param Varien_Event_Observer $observer
*/
public function removeItemFromCartGoogleAnalytics(Varien_Event_Observer $observer)
{
$productRemoved = $observer->getEvent()->getQuoteItem()->getProduct();
if ($productRemoved) {
Mage::getSingleton('core/session')->setRemovedProductCart($productRemoved->getId());
}
}

/**
* Add 'added item' to cart into session for GA4 block to render event on cart view
*
* @param Varien_Event_Observer $observer
*/
public function addItemToCartGoogleAnalytics(Varien_Event_Observer $observer)
{
$productAdded = $observer->getEvent()->getQuoteItem()->getProduct();
if ($productAdded) {
Mage::getSingleton('core/session')->setAddedProductCart($productAdded->getId());
}
}
}
16 changes: 16 additions & 0 deletions app/code/core/Mage/GoogleAnalytics/etc/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@
</googleanalytics_order_success>
</observers>
</checkout_multishipping_controller_success_action>
<sales_quote_remove_item>
<observers>
<googleanalytics_remove_item>
<class>googleanalytics/observer</class>
<method>removeItemFromCartGoogleAnalytics</method>
</googleanalytics_remove_item>
</observers>
</sales_quote_remove_item>
<sales_quote_add_item>
<observers>
<googleanalytics_add_item>
<class>googleanalytics/observer</class>
<method>addItemToCartGoogleAnalytics</method>
</googleanalytics_add_item>
</observers>
</sales_quote_add_item>
</events>
<layout>
<updates>
Expand Down