Skip to content

Commit 0caaa00

Browse files
committed
Support for Google Analytics 4
1 parent c27408b commit 0caaa00

16 files changed

Lines changed: 423 additions & 110 deletions

classes/Form/ConfigurationForm.php

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,23 @@ public function generate()
9595
'required' => true,
9696
'hint' => $this->module->trans('This information is available in your Google Analytics account', [], 'Modules.GAnalytics.Admin'),
9797
],
98+
[
99+
'type' => 'switch',
100+
'label' => $this->module->trans('Enable Google Analytics 4', [], 'Modules.GAnalytics.Admin'),
101+
'name' => 'GA_V4_ENABLED',
102+
'values' => [
103+
[
104+
'id' => 'GA_V4_ENABLED',
105+
'value' => 1,
106+
'label' => $this->module->trans('Yes', [], 'Modules.GAnalytics.Admin'),
107+
],
108+
[
109+
'id' => 'GA_V4_ENABLED',
110+
'value' => 0,
111+
'label' => $this->module->trans('No', [], 'Modules.GAnalytics.Admin'),
112+
],
113+
],
114+
],
98115
[
99116
'type' => 'switch',
100117
'label' => $this->module->trans('Enable User ID tracking', [], 'Modules.GAnalytics.Admin'),
@@ -109,7 +126,8 @@ public function generate()
109126
'id' => 'ga_userid_disabled',
110127
'value' => 0,
111128
'label' => $this->module->trans('No', [], 'Modules.GAnalytics.Admin'),
112-
], ],
129+
],
130+
],
113131
],
114132
[
115133
'type' => 'switch',
@@ -188,6 +206,7 @@ public function generate()
188206

189207
// Load current value
190208
$helper->fields_value['GA_ACCOUNT_ID'] = Configuration::get('GA_ACCOUNT_ID');
209+
$helper->fields_value['GA_V4_ENABLED'] = Configuration::get('GA_V4_ENABLED');
191210
$helper->fields_value['GA_USERID_ENABLED'] = Configuration::get('GA_USERID_ENABLED');
192211
$helper->fields_value['GA_CROSSDOMAIN_ENABLED'] = Configuration::get('GA_CROSSDOMAIN_ENABLED');
193212
$helper->fields_value['GA_ANONYMIZE_ENABLED'] = Configuration::get('GA_ANONYMIZE_ENABLED');
@@ -209,6 +228,7 @@ public function treat()
209228

210229
$treatmentResult = '';
211230
$gaAccountId = Tools::getValue('GA_ACCOUNT_ID');
231+
$gaV4Enabled = Tools::getValue('GA_V4_ENABLED');
212232
$gaUserIdEnabled = Tools::getValue('GA_USERID_ENABLED');
213233
$gaCrossdomainEnabled = Tools::getValue('GA_CROSSDOMAIN_ENABLED');
214234
$gaAnonymizeEnabled = Tools::getValue('GA_ANONYMIZE_ENABLED');
@@ -218,7 +238,12 @@ public function treat()
218238
if (!empty($gaAccountId)) {
219239
Configuration::updateValue('GA_ACCOUNT_ID', $gaAccountId);
220240
Configuration::updateValue('GANALYTICS_CONFIGURATION_OK', true);
221-
$treatmentResult .= $this->module->displayConfirmation($this->module->getTranslator()->trans('Account ID updated successfully', [], 'Modules.GAnalytics.Admin'));
241+
$treatmentResult .= $this->module->displayConfirmation($this->module->trans('Account ID updated successfully', [], 'Modules.GAnalytics.Admin'));
242+
}
243+
244+
if (null !== $gaV4Enabled) {
245+
Configuration::updateValue('GA_V4_ENABLED', (bool) $gaV4Enabled);
246+
$treatmentResult .= $this->module->displayConfirmation($this->module->trans('Settings for Google Analytics 4 updated successfully'));
222247
}
223248

224249
if (null !== $gaUserIdEnabled) {
@@ -233,20 +258,20 @@ public function treat()
233258

234259
if (null !== $gaAnonymizeEnabled) {
235260
Configuration::updateValue('GA_ANONYMIZE_ENABLED', (bool) $gaAnonymizeEnabled);
236-
$treatmentResult .= $this->module->displayConfirmation($this->module->getTranslator()->trans('Settings for Anonymize IP updated successfully', [], 'Modules.GAnalytics.Admin'));
261+
$treatmentResult .= $this->module->displayConfirmation($this->module->trans('Settings for Anonymize IP updated successfully', [], 'Modules.GAnalytics.Admin'));
237262
}
238263

239264
if (null !== $gaTrackBackOffice) {
240265
Configuration::updateValue('GA_TRACK_BACKOFFICE_ENABLED', (bool) $gaTrackBackOffice);
241-
$treatmentResult .= $this->module->displayConfirmation($this->module->getTranslator()->trans('Settings for Enable Back Office tracking updated successfully.', [], 'Modules.GAnalytics.Admin'));
266+
$treatmentResult .= $this->module->displayConfirmation($this->module->trans('Settings for Enable Back Office tracking updated successfully.', [], 'Modules.GAnalytics.Admin'));
242267
}
243268

244269
if ($gaCancelledStates === false) {
245270
Configuration::updateValue('GA_CANCELLED_STATES', '');
246271
} else {
247272
Configuration::updateValue('GA_CANCELLED_STATES', json_encode($gaCancelledStates));
248273
}
249-
$treatmentResult .= $this->module->displayConfirmation($this->module->getTranslator()->trans('Settings for canceled order states updated successfully.', [], 'Modules.GAnalytics.Admin'));
274+
$treatmentResult .= $this->module->displayConfirmation($this->module->trans('Settings for canceled order states updated successfully.', [], 'Modules.GAnalytics.Admin'));
250275

251276
return $treatmentResult;
252277
}

classes/GoogleAnalyticsTools.php

Lines changed: 100 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,16 @@
2222

2323
class GoogleAnalyticsTools
2424
{
25+
/**
26+
* @var bool
27+
*/
28+
protected $isV4Enabled = false;
29+
30+
public function __construct($isV4Enabled = false)
31+
{
32+
$this->isV4Enabled = $isV4Enabled;
33+
}
34+
2535
/**
2636
* filter
2737
*
@@ -43,22 +53,44 @@ public function filter($gaScripts, $filterable)
4353
* add order transaction
4454
*
4555
* @param array $products
46-
* @param array $order
56+
* @param array $transaction
4757
*
4858
* @return string|void
4959
*/
50-
public function addTransaction($products, $order)
60+
public function addTransaction($products, $transaction)
5161
{
5262
if (!is_array($products)) {
5363
return;
5464
}
5565

56-
$js = '';
57-
foreach ($products as $product) {
58-
$js .= 'MBG.add(' . json_encode($product) . ');';
66+
if ($this->isV4Enabled) {
67+
$js = 'gtag(\'event\', \'purchase\', {
68+
"transaction_id": "' . $transaction['id'] . '",
69+
"items": [';
70+
71+
$isFirst = true;
72+
foreach ($products as $product) {
73+
if (!$isFirst) {
74+
$js .= ',';
75+
}
76+
$js .= '{
77+
"item_id": "' . $product['id'] . '",
78+
"item_name": "' . $product['name'] . '",
79+
"quantity": "' . $product['quantity'] . '",
80+
"price": "' . $product['price'] . '"
81+
}';
82+
$isFirst = false;
83+
}
84+
$js .= ']});';
85+
} else {
86+
$js = '';
87+
foreach ($products as $product) {
88+
$js .= 'MBG.add(' . json_encode($product) . ');';
89+
}
90+
$js .= 'MBG.addTransaction(' . json_encode($transaction) . ');';
5991
}
6092

61-
return $js . 'MBG.addTransaction(' . json_encode($order) . ');';
93+
return $js;
6294
}
6395

6496
/**
@@ -75,8 +107,10 @@ public function addProductImpression($products)
75107
}
76108

77109
$js = '';
78-
foreach ($products as $product) {
79-
$js .= 'MBG.add(' . json_encode($product) . ",'',true);";
110+
if (!$this->isV4Enabled) {
111+
foreach ($products as $product) {
112+
$js .= 'MBG.add(' . json_encode($product) . ",'',true);";
113+
}
80114
}
81115

82116
return $js;
@@ -86,18 +120,45 @@ public function addProductImpression($products)
86120
* addProductClick
87121
*
88122
* @param array $products
123+
* @param string $currencyIsoCode
89124
*
90125
* @return string|void
91126
*/
92-
public function addProductClick($products)
127+
public function addProductClick($products, $currencyIsoCode)
93128
{
94129
if (!is_array($products)) {
95130
return;
96131
}
97132

98133
$js = '';
99-
foreach ($products as $product) {
100-
$js .= 'MBG.addProductClick(' . json_encode($product) . ');';
134+
if ($this->isV4Enabled) {
135+
foreach ($products as $key => $product) {
136+
$productId = explode('-', $product['id']);
137+
$js .= '$(\'article[data-id-product="' . $productId[0] . '"] a.quick-view\').on(
138+
"click",
139+
function() {
140+
gtag("event", "select_item", {
141+
items: [
142+
{
143+
item_id: "' . $product['id'] . '",
144+
item_name: "' . $product['name'] . '",
145+
quantity: "' . $product['quantity'] . '",
146+
price: "' . $product['price'] . '",
147+
currency: "' . $currencyIsoCode . '",
148+
index: ' . $product['position'] . ',
149+
item_brand: "' . $product['brand'] . '",
150+
item_category: "' . $product['category'] . '",
151+
item_list_id: "' . $product['list'] . '",
152+
item_variant: "' . $product['variant'] . '",
153+
}
154+
]
155+
})
156+
});';
157+
}
158+
} else {
159+
foreach ($products as $product) {
160+
$js .= 'MBG.addProductClick(' . json_encode($product) . ');';
161+
}
101162
}
102163

103164
return $js;
@@ -110,15 +171,36 @@ public function addProductClick($products)
110171
*
111172
* @return string|void
112173
*/
113-
public function addProductClickByHttpReferal($products)
174+
public function addProductClickByHttpReferal($products, $currencyIsoCode)
114175
{
115176
if (!is_array($products)) {
116177
return;
117178
}
118179

119180
$js = '';
120-
foreach ($products as $product) {
121-
$js .= 'MBG.addProductClickByHttpReferal(' . json_encode($product) . ');';
181+
if ($this->isV4Enabled) {
182+
foreach ($products as $key => $product) {
183+
$js .= 'gtag("event", "select_item", {
184+
items: [
185+
{
186+
item_id: "' . $product['id'] . '",
187+
item_name: "' . $product['name'] . '",
188+
quantity: "' . $product['quantity'] . '",
189+
price: "' . $product['price'] . '",
190+
currency: "' . $currencyIsoCode . '",
191+
index: ' . $product['position'] . ',
192+
item_brand: "' . $product['brand'] . '",
193+
item_category: "' . $product['category'] . '",
194+
item_list_id: "' . $product['list'] . '",
195+
item_variant: "' . $product['variant'] . '",
196+
}
197+
]
198+
});';
199+
}
200+
} else {
201+
foreach ($products as $product) {
202+
$js .= 'MBG.addProductClickByHttpReferal(' . json_encode($product) . ');';
203+
}
122204
}
123205

124206
return $js;
@@ -138,8 +220,10 @@ public function addProductFromCheckout($products)
138220
}
139221

140222
$js = '';
141-
foreach ($products as $product) {
142-
$js .= 'MBG.add(' . json_encode($product) . ');';
223+
if (!$this->isV4Enabled) {
224+
foreach ($products as $product) {
225+
$js .= 'MBG.add(' . json_encode($product) . ');';
226+
}
143227
}
144228

145229
return $js;

classes/Handler/GanalyticsJsHandler.php

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,19 +40,17 @@ public function __construct(Ps_Googleanalytics $module, Context $context)
4040
* Generate Google Analytics js
4141
*
4242
* @param string $jsCode
43-
* @param bool $isBackoffice
4443
*
4544
* @return void|string
4645
*/
47-
public function generate($jsCode, $isBackoffice = false)
46+
public function generate($jsCode)
4847
{
4948
if (Configuration::get('GA_ACCOUNT_ID')) {
5049
$this->context->smarty->assign(
5150
[
51+
'isV4Enabled' => (bool) Configuration::get('GA_V4_ENABLED'),
5252
'jsCode' => $jsCode,
5353
'isoCode' => Tools::safeOutput($this->context->currency->iso_code),
54-
'jsState' => $this->module->js_state,
55-
'isBackoffice' => $isBackoffice,
5654
]
5755
);
5856

classes/Hook/HookActionCarrierProcess.php

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
namespace PrestaShop\Module\Ps_Googleanalytics\Hooks;
2222

23+
use Configuration;
2324
use Context;
2425
use PrestaShop\Module\Ps_Googleanalytics\Handler\GanalyticsDataHandler;
2526
use PrestaShop\Module\Ps_Googleanalytics\Repository\CarrierRepository;
@@ -52,17 +53,35 @@ public function run()
5253
);
5354

5455
$carrierName = $carrierRepository->findByCarrierId((int) $this->params['cart']->id_carrier);
55-
$ganalyticsDataHandler->manageData('MBG.addCheckoutOption(2,\'' . $carrierName . '\');', 'A');
56+
57+
if ((bool) Configuration::get('GA_V4_ENABLED')) {
58+
$js = $this->getGoogleAnalytics4($carrierName);
59+
} else {
60+
$js = $this->getUniversalAnalytics($carrierName);
61+
}
62+
$ganalyticsDataHandler->manageData($js, 'A');
5663
}
5764
}
5865

5966
/**
60-
* setParams
61-
*
6267
* @param array $params
6368
*/
6469
public function setParams($params)
6570
{
6671
$this->params = $params;
6772
}
73+
74+
protected function getUniversalAnalytics(string $carrierName)
75+
{
76+
return 'MBG.addCheckoutOption(2,\'' . $carrierName . '\');';
77+
}
78+
79+
protected function getGoogleAnalytics4(string $carrierName)
80+
{
81+
return 'gtag("event", "add_shipping_info", {
82+
currency: "' . $this->context->currency->iso_code . '",
83+
value: ' . $this->context->cart->getCartTotalPrice() . ',
84+
shipping_tier: "' . $carrierName . '"
85+
});';
86+
}
6887
}

classes/Hook/HookActionOrderStatusPostUpdate.php

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,12 @@ public function run()
7474
// If it was not already refunded
7575
if ($gaRefundSent === false) {
7676
// We refund it and set the "sent" flag to true
77-
$this->context->cookie->__set('ga_admin_refund', 'MBG.refundByOrderId(' . json_encode(['id' => $this->params['id_order']]) . ');');
77+
if ((bool) Configuration::get('GA_V4_ENABLED')) {
78+
$js = $this->getGoogleAnalytics4($this->params['id_order']);
79+
} else {
80+
$js = $this->getUniversalAnalytics($this->params['id_order']);
81+
}
82+
$this->context->cookie->__set('ga_admin_refund', $js);
7883
$this->context->cookie->write();
7984

8085
// We save this information to database
@@ -93,4 +98,17 @@ public function setParams($params)
9398
{
9499
$this->params = $params;
95100
}
101+
102+
protected function getUniversalAnalytics($idOrder)
103+
{
104+
return 'MBG.refundByOrderId(' . json_encode(['id' => $idOrder]) . ');';
105+
}
106+
107+
protected function getGoogleAnalytics4($idOrder)
108+
{
109+
return 'gtag("event", "refund", {
110+
currency: "' . $this->context->currency->iso_code . '",
111+
transaction_id: ' . $idOrder . '
112+
});';
113+
}
96114
}

0 commit comments

Comments
 (0)