1

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.

1
  • According to Google they always return a 200 status even if something was wrong: developers.google.com/analytics/devguides/collection/protocol/… "The Measurement Protocol does not return an error code if the payload data was malformed, or if the data in the payload was incorrect or was not processed by Google Analytics." Commented Jun 27, 2024 at 9:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.