Skip to content

Instantly share code, notes, and snippets.

@jreviews
Last active December 14, 2022 15:13
Show Gist options
  • Save jreviews/d424e97a26744303ac0abac1b8e2893c to your computer and use it in GitHub Desktop.
Save jreviews/d424e97a26744303ac0abac1b8e2893c to your computer and use it in GitHub Desktop.
Generate GA4 custom report for specific path, event and timeframe using Google Analytics Data API

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment