Forked from sdeering/Drupal 8 Send Google Analytics Event from PHP Back-end
Created
February 6, 2022 18:38
-
-
Save kvantstudio/3732b55bfae5db38849f12ce9e5532d2 to your computer and use it in GitHub Desktop.
Revisions
-
sdeering created this gist
Oct 30, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,49 @@ /** * Send Google analytics tracking event. * * @param mixed $action * Event action. */ public function sendGoogleTrackingEvent($action) { if (!$this->isProduction()) return; $googleAnalyticsUA = 'UA-XXXXXXXX-XX'; // phpcs:disable $data = [ 'v' => 1, 't' => 'event', 'tid' => $googleAnalyticsUA, 'cid' => \Drupal::service('uuid')->generate(), 'ec' => 'Category name', 'ea' => 'Action name, 'el' => 'Label name', 'uip' => \Drupal::request()->getClientIp(), 'ua' => $_SERVER['HTTP_USER_AGENT'], ]; // phpcs:enable $url = 'https://www.google-analytics.com/collect'; $content = http_build_query($data); $content = utf8_encode($content); $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-type: application/x-www-form-urlencoded']); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $content); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_exec($ch); curl_close($ch); } /** * Check if app is running in production. */ public function isProduction() { return (strpos($_SERVER['HTTP_HOST'], 'production.com') !== FALSE); } }