Search code examples
phpgoogle-analyticsgoogle-analytics-apiphp-curlgoogle-analytics-4

GA4 custom event from server side, can someone tell me how i can do the following code in php?


const measurement_id = `G-XXXXXXXXXX`;
const api_secret = `<secret_value>`;

fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurement_id}&`api_secret`=${api_secret}`, {
  method: "POST",
  body: JSON.stringify({
    client_id: 'XXXXXXXXXX.YYYYYYYYYY',
    events: [{
      name: 'tutorial_begin',
      params: {},
    }]
  })
});

can someone tell me how i can do the above code in php? i have tried the following but it is not working,

$data = array(
                'client_id' => self::ga_extract_cid_from_cookies(),
                'user_id' => 123,
                'timestamp_micros' => time(),
                'non_perosnalised_ads' => false,
                'events' => array(
                    'name' => 'login'
                )
            );
$dataString = json_encode($data);

$post_url = 'https://www.google-analytics.com/mp/collect?api_secret=xxxxxxx&measurement_id=xxxxxxxxx';
        $ch = curl_init($post_url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);

When i run the above its not sending any event to google analytics account. I don't know what is the error and how to find it. Need help on this pls.


Solution

  • I believe the main problem in your example, apart from the typo in the $datastring variable, was that the user id was sent as an int, not as a string. My example here works:

    $ip = str_replace('.', '', $_SERVER['REMOTE_ADDR']);
    $data = array(
                    'client_id' => $ip,
                    'user_id' => '123',
                    'events' => array(
                        'name' => 'event_serverside'
                    )
                );
    $datastring = json_encode($data);
    $post_url = 'https://www.google-analytics.com/mp/collect?api_secret=xxxxxxxxxx&measurement_id=xxxxxxxxx';
    $ch = curl_init($post_url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
    curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $post_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($ch, CURLOPT_POST, TRUE);
    $result = curl_exec($ch);