Skip to content

Commit

Permalink
refactor: refactor debug mode and fix bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
hirale committed Jun 13, 2024
1 parent 48d317e commit f8a604f
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 26 deletions.
26 changes: 15 additions & 11 deletions src/app/code/community/Hirale/GAMeasurementProtocol/Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
class Hirale_GAMeasurementProtocol_Helper_Data extends Mage_Core_Helper_Abstract
{
const GA4_MEASUREMENT_PROTOCOL_URL = 'https://www.google-analytics.com/mp/collect';
const GA4_MEASUREMENT_PROTOCOL_DEBUG_URL = 'https://www.google-analytics.com/debug/mp/collect';
const GTAG_URL = 'https://www.googletagmanager.com/gtag/destination';
protected $_isMeasurementEnabled = null;
protected $_measurementId = null;
protected $_apiSecret = null;
Expand All @@ -26,7 +26,7 @@ public function isDebugMode()

public function getMeasurementProtocolUrl()
{
return $this->isDebugMode() ? self::GA4_MEASUREMENT_PROTOCOL_DEBUG_URL : self::GA4_MEASUREMENT_PROTOCOL_URL;
return self::GA4_MEASUREMENT_PROTOCOL_URL;
}


Expand All @@ -49,16 +49,20 @@ public function getApiSecret()

public function getClientId()
{

if (isset($_COOKIE['_ga'])) {
$ga = explode('.', $_COOKIE['_ga']);
$clientId = $ga[2] . '.' . $ga[3];
} else {
$randomNumber = mt_rand(1000000000, 9999999999);
$timestamp = time();
$clientId = $randomNumber . '.' . $timestamp;
$session = Mage::getSingleton('core/session');
$clientId = $session->getData('ga_client_id');
if (!$clientId) {
if (isset($_COOKIE['_ga'])) {
$ga = explode('.', $_COOKIE['_ga']);
$clientId = $ga[2] . '.' . $ga[3];
} else {
$randomNumber = mt_rand(1000000000, 9999999999);
$timestamp = time();
$clientId = $randomNumber . '.' . $timestamp;
}
$session->setData('ga_client_id', $clientId);
}

return $clientId;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public function __construct()

public function handle($data)
{
$event = $data['data']['event'];
$event = $data['data'];
$url = $this->helper->getMeasurementProtocolUrl();
$measurementId = $this->helper->getMeasurementId();
$apiSecret = $this->helper->getApiSecret();
Expand All @@ -26,10 +26,9 @@ public function handle($data)
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
curl_exec($ch);
if ($this->helper->isDebugMode()) {
Mage::log($payload);
Mage::log($response);
}
if (curl_errno($ch)) {
throw new Exception(curl_error($ch));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,40 @@ class Hirale_GAMeasurementProtocol_Model_Observer
protected $baseEventData;



public function __construct()
{
$this->helper = Mage::helper('gameasurementprotocol');
$this->gaHelper = Mage::helper('googleanalytics');
$this->queue = Mage::getModel('hirale_queue/task');
}

public function generateClientId(Varien_Event_Observer $observer)
{
$this->helper->getClientId();
}


/**
* Add a task to the queue for processing by the Hirale_GAMeasurementProtocol_Model_Api class.
*
* @param array $event The name of the event to be processed.
* @param array $events The name of the event to be processed.
*/
protected function addToQueue($event)
protected function addToQueue($events)
{
try {
foreach ($events['events'] as &$event) {
$params = &$event['params'];
if ($this->helper->isDebugMode()) {
$params['debug_mode'] = true;
}
$params['user_agent'] = Mage::helper('core/http')->getHttpUserAgent();
$params['platform'] = Mage::helper('core/string')->cleanString(Mage::app()->getRequest()->getServer('HTTP_SEC_CH_UA_PLATFORM'));
}

$this->queue->addTask(
'Hirale_GAMeasurementProtocol_Model_Api',
compact('event')
$events
);
} catch (Exception $e) {
Mage::logException($e);
Expand All @@ -37,9 +53,13 @@ protected function getBaseEventData()
if (!$this->baseEventData) {
$this->baseEventData = [
'client_id' => $this->helper->getClientId(),
"timestamp_micros" => floor(microtime(true) * 1000000),
"non_personalized_ads" => false
'timestamp_micros' => floor(microtime(true) * 1000000),
'non_personalized_ads' => true
];
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
$customer = Mage::getSingleton('customer/session')->getCustomer();
$this->baseEventData['user_id'] = $customer->getId();
}
}
return $this->baseEventData;
}
Expand Down Expand Up @@ -122,7 +142,7 @@ public function addToWishlist(Varien_Event_Observer $observer)
$eventData = $this->getBaseEventData();
$value = 0;
$currency = Mage::app()->getStore()->getBaseCurrencyCode();
$newItems =[];
$newItems = [];
foreach ($items as $item) {
$_product = $item->getProduct();
$_price = $_product->getFinalPrice();
Expand Down Expand Up @@ -176,11 +196,6 @@ public function dispatchRouteEvent(Varien_Event_Observer $observer)
$route = $request->getModuleName() . '_' . $request->getControllerName() . '_' . $request->getActionName();
$eventData = $this->getBaseEventData();

if (Mage::getSingleton('customer/session')->isLoggedIn()) {
$customer = Mage::getSingleton('customer/session')->getCustomer();
$eventData['user_id'] = $customer->getId();
}

$events = [];
switch ($route) {
case 'checkout_onepage_index':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@
</global>
<frontend>
<events>
<controller_front_send_response_after>
<observers>
<gameasurementprotocol_controller_front_send_response_after>
<type>singleton</type>
<class>gameasurementprotocol/observer</class>
<method>generateClientId</method>
</gameasurementprotocol_controller_front_send_response_after>
</observers>
</controller_front_send_response_after>
<sales_quote_item_save_after>
<observers>
<gameasurementprotocol_sales_quote_item_save_after>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
<depends>
<enabled>1</enabled>
</depends>
<comment>When in debug mode, all requests will be logged and sent to debug endpoint, check system.log for more details.</comment>
<comment>When in debug mode, all requests will be logged in the system log, you can check debug view (https://support.google.com/analytics/answer/7201382) for more info.</comment>
</debug_mode>
</fields>
</measurement>
Expand Down

0 comments on commit f8a604f

Please sign in to comment.