This code example uses Laravel's Http
client.
You need to generate the private key from your service account in a Google Cloud Platform project. Then grant access to your GA4 property to the service account client email.
There are some instructions for doing that in the JReviews Dashboard Addon documentation, which is where the code below comes from.
function getAuthToken($clientEmail, $privateKey)
{
$base64URLEncode = function($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
};
$header = $base64URLEncode(json_encode(['alg' => 'RS256', 'typ' => 'JWT']));
$claim = $base64URLEncode(json_encode([
'iss' => $clientEmail,
'scope' => 'https://www.googleapis.com/auth/analytics.readonly',
'aud' => 'https://www.googleapis.com/oauth2/v4/token',
'iat' => time(),
'exp' => time() + (60 * 60),
]));
$privateKeyId = openssl_pkey_get_private($privateKey);
openssl_sign($header.'.'.$claim, $signature, $privateKeyId, "sha256");
$jwt = $header.'.'.$claim.'.'.$base64URLEncode($signature);
$response = \Http::post('https://www.googleapis.com/oauth2/v4/token', [
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt,
]);
if ($response->ok()) {
return $response->json()['access_token'];
}
return false;
}
}
$res = \Http::withToken(getAuthToken($clientEmail, $privateKey))
->post('https://analyticsdata.googleapis.com/v1beta/properties/YOUR-GA4-PROPERTY-ID:runReport', [
'keepEmptyRows' => true,
'dateRanges' => [
'startDate' => '2022-12-01',
'endDate' => '2022-12-31',
],
'dimensions' => [
['name' => 'eventName'],
['name' => 'date'],
],
'metrics' => [
['name' => 'eventCount'],
['name' => 'sessions']
],
'orderBys' => [
'dimension' => [
'dimension_name' => 'date',
],
'desc' => false,
],
'dimensionFilter' => [
'andGroup' => [
'expressions' => [
'filter' => [
'fieldName' => 'pagePath',
'stringFilter' => [
'value' => '/url-path',
'matchType' => 'EXACT'
]
],
'filter' => [
'fieldName' => 'eventName',
'stringFilter' => [
'value' => 'contact_click',
'matchType' => 'EXACT'
],
],
]
]
]
]);
$res->json();