I'm working on an API in Laravel and need to send events to Google Tag Manager (GTM) using PHP. I've created a helper class to send the event via a Guzzle HTTP call. While I always receive a 200 status code indicating a success response, I do not see the event in the Google Analytics console.
Here is my code:
<?php
namespace App\Helpers;
use GuzzleHttp\Client;
class GoogleTagManager
{
protected $client;
private $event;
protected $trackingId; // Your Google Analytics Tracking ID
public function __construct($event)
{
$this->event = $event;
$this->client = new Client(['base_uri' => 'https://www.google-analytics.com']);
$this->trackingId = env("GOOGLE_TAG_GTM_ID");
}
/**
* Send Event to Google TagManager
* @return bool
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function sendEvent()
{
try {
$params = $this->getParams();
$response = $this->client->post('/collect', [
'form_params' => $params
]);
return $response->getStatusCode() == 200;
} catch (\Exception $ex) {
$log = [];
$log["method"] = "GoogleTagManager - sendEvent";
$log["message"] = $ex->getMessage();
$log["file"] = $ex->getFile();
$log["line"] = $ex->getLine();
\Log::info(print_r($log, true));
return false;
}
}
/**
* Get Event Body Array
* @return array
*/
private function getParams()
{
return [
'tid' => $this->trackingId,
'name' => $this->event,
'event' => $this->event,
'params' => [
'page' => "Home Page"
]
];
}
}
Despite receiving a 200 status code, the events are not appearing in Google Analytics. I have tried different packages as well but with no success:
What am I doing wrong? How can I correctly send events to Google Tag Manager and ensure they appear in the Google Analytics console?
Any help or guidance on this would be greatly appreciated.