Google Analytics - pass a generated event to a user session?

bernard

BuSo Pro
Joined
Dec 31, 2016
Messages
2,587
Likes
2,298
Degree
6
If you have a php file that returns an empty tracking pixel, how would you best get this into Google Analytics as an event connected to the relevant user session?

I asked GPT and using the Measurement Protocol, but then the event got tracked as Direct traffic instead of being an Event connected to an actual User session.

I then asked GPT again and was told to grab the clientID and pass it to the tracking script and then pass it to GA, which should do the trick?

JavaScript:
ga(function(tracker) {

var clientId = tracker.get('clientId');
var imageUrl = 'https://example.com/tracker.php?clientId=' + clientId; 
// then use imageUrl as the source of the tracking pixel });

});

and

PHP:
<?php
// Load Universal Analytics parameters
$data = array(
    'v' => 1,
    'tid' => 'UA-XXXX-Y', // replace with your Tracking ID
    'cid' => $_GET['clientId'],
    't' => 'event',
    'ec' => 'affiliate',
    'ea' => 'click',
);

// rest of the script...
Is this approach feasible?
 
It is feasible.

You need to have the client id AND the session id and setup a timestamp_micros just after the session started (ie during the session as far as GA4 is concerned).

I've just implemented this to get affiliate purchases back into GA4.

I end up with a MP POST to:
https://www.google-analytics.com/mp/collect?api_secret=XYZ&measurement_id=G-XXXXXXXXX

JSON body:
JSON:
{

"client_id": "1939774731.1689271853",
"non_personalized_ads":false,
"timestamp_micros":1689271853318000,
"events": [
{"name": "purchase",
       "params": { 
"session_id":1689271853,
"currency": "USD",
 "transaction_id": "200468906",
 "value": 7.11,
"shipping": 0,  
"tax": 0, "items":[]    }
     }]
   }

You could do this with a click to an affiliate offer. (Although I just use GA4 gtag for this. GA4 is good at catching these).

The trick is the session id and timestamp.

In my case I had to store session_id, client_id, timestamp in a database and wait for any transaction to occur.
 
You could do this with a click to an affiliate offer. (Although I just use GA4 gtag for this. GA4 is good at catching these).

Yes, I want to see if it catches them, it's javascript generated links, so that's the issue, they didn't turn up in UA.

Maybe they'll show in GA4. I realized you had to turn on Enhanced Tracking for it to get outbound links.
 
for external link clicks you can intercept the click, send the event to GA4 and get a callback from GA4 when it's finished. Then complete the click. (I use gtag for this).
 
for external link clicks you can intercept the click, send the event to GA4 and get a callback from GA4 when it's finished. Then complete the click. (I use gtag for this).

This is voodoo to me.

I have no experience what so ever with programmatic Google Analytics.
 
OK.
I'd outsource it then. Or use Google Tag Manger - less technical and no real coding required.
 
Back