aawnu / php-ga4

PHP Wrapper for Google Analytics 4 with Server Side Tracking

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

question: How to get data to show up in debug?

8ctopus opened this issue · comments

I've been trying without success to get the debug mode working, in order to view events as soon as they are generated in debugView (I have some events that google says are not correct and I would like to figure out why)

https://analytics.google.com/analytics/web/#/a62992619p355170503/admin/debugview/overview

Do you know how to do it? I will be happy to submit a PR for the readme as I believe it will be useful for others.

Here's my sample code:

$clientId = $_COOKIE['_ga'] ?? $_COOKIE['_gid'] ?? null;

if (!$clientId) {
    throw new Exception('GA cookie not set');
}

$debug = true;

$analytics = Analytics::new($trackingId, $apiSecret, $debug)
    ->setClientId($clientId)
    ->setTimestampMicros(time());

$price = 1;
$transactionId = strtoupper(bin2hex(random_bytes(10)));

$purchase = Event\Purchase::new()
    ->setCurrency('USD')
    ->setValue($price)
    ->setTransactionId($transactionId);

$products = [
    [
        'name' => 'ball',
        'amount' => 5.00,
    ], [
        'name' => 'pen',
        'amount' => 5.00,
    ],
];

foreach ($products as $product) {
    $item = Item::new()
        ->setItemName($product['name'])
        ->setQuantity(1)
        ->setPrice($product['amount']);

    $purchase->addItem($item);
}

$analytics->addEvent($purchase);
$analytics->post();

There was a person previously that had issues with live debugger and I think it looks for something that GTAG sends. I did not make it work with the server side tracking, if you find a solution please feel free to share!

I have just looked into this again, and it appears that events sent through the measurement protocol which your implementation uses, do not show up in the debug view.

The only way to validate events being sent as per documentation is to send them to https://www.google-analytics.com/debug/mp/collect which will return a validation response such as

{
  "validationMessages": [
    {
      "fieldPath": "events",
      "description": "Event at index: [0] has invalid name [_badEventName]. Names must start with an alphabetic character.",
      "validationCode": "NAME_INVALID"
    }
  ]
}

Reference: https://developers.google.com/analytics/devguides/collection/protocol/ga4/validating-events?client_type=gtag

I would suggest adding a paragraph to the README about this, if you agree, I can submit a PR for it.

Sure, feel free to add it, perhaps some kind of notice around the top but somewhere after the gdpr notice.

Edit: Please do also add the link, either next to it or in the links at bottom.