Skip to content

Commit

Permalink
Generator fallback ClientID
Browse files Browse the repository at this point in the history
In case the cookie is not found.
  • Loading branch information
barryvdh authored Feb 9, 2021
1 parent 782118d commit d911e27
Showing 1 changed file with 24 additions and 11 deletions.
35 changes: 24 additions & 11 deletions Observer/SaveGaUserId.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,30 @@ public function execute(Observer $observer)
return;
}

$gaUserId = $this->getUserIdFromCookie();
if ($gaUserId === null) {
$gaCookieUserId = random_int(1E8, 1E9);
$gaCookieTimestamp = time();
$gaUserId = implode('.', [$gaCookieUserId, $gaCookieTimestamp]);
$this->logger->info('Google Analytics cookie not found, generated temporary value: ' . $gaUserId);
}

$order = $observer->getEvent()->getOrder();

$order->setData('ga_user_id', $gaUserId);
}

/**
* Try to get the Google Analytics User ID from the cookie
*
* @return string|null
*/
protected function getUserIdFromCookie()
{
$gaCookie = explode('.', $this->cookieManager->getCookie('_ga'));

if (empty($gaCookie) || count($gaCookie) < 4) {
return;
return null;
}

list(
Expand All @@ -77,19 +95,14 @@ public function execute(Observer $observer)
) = $gaCookie;

if (!$gaCookieUserId || !$gaCookieTimestamp) {
return;
return null;
}

$client = $this->gaclient;

if ($gaCookieVersion != 'GA' . $client->getVersion()) {
if ($gaCookieVersion != 'GA' . $this->gaclient->getVersion()) {
$this->logger->info('Google Analytics cookie version differs from Measurement Protocol API version; please upgrade.');
return;
return null;
}

$gaUserId = implode('.', [$gaCookieUserId, $gaCookieTimestamp]);

$order->setData('ga_user_id', $gaUserId);
return implode('.', [$gaCookieUserId, $gaCookieTimestamp]);
}

}
}

0 comments on commit d911e27

Please sign in to comment.