Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google analytics 4 API with authentication

My website already has universal analytics and we are displaying different analytics profile data on our dashboard by authenticating users. Because each user will have access to a different analytics profile. So the steps we follow in UA are,

  • Ask the user to authenticate.
  • Get auth code and create an access token.
  • Passing access token to listManagementProfiles API to get the list of profiles for the authenticated user.
  • Based on the selected profile we display the analytics data. (we use google service analytics library)

sample code:

if (!class_exists('Google_Client')) {
    require_once '/lib/google-api-php-client-master/src/Google/Client.php';
    require_once '/lib/google-api-php-client-master/src/Google/Service/Analytics.php';
}

$this->client = new Google_Client();
$this->client->setApprovalPrompt('force');
$this->client->setAccessType('offline');
$this->client->setClientId('************');
$this->client->setClientSecret('*************');
$this->client->setRedirectUri('*****************');
$this->client->setScopes('https://www.googleapis.com/auth/analytics');
$this->client->setDeveloperKey('*************************');

$this->service = new Google_Service_Analytics($this->client);
$accessToken = $this->client->authenticate($authCode);
if ($accessToken) {
   $this->client->setAccessToken($accessToken);
        return true;
} else {
   return false;
}

        

Where I'm stuck?

  • I've checked for the GA4 documentation and followed the steps provided in the doc. I have created the account/property for GA4 in one of my google accounts.
  • I then enabled the analytics service from google console.
  • Created service account.
  • Downloaded JSON file.
  • Downloaded the google admin client library from here

GA4 sample code:

require 'vendor/autoload.php';

use Google\Analytics\Admin\V1alpha\AnalyticsAdminServiceClient;
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;

putenv('GOOGLE_APPLICATION_CREDENTIALS=config.json');

$client = new AnalyticsAdminServiceClient();

$accounts = $client->listAccountSummaries();

But this does not require the access_token and without an access token, it allows to fetch the accounts lists. I don't want the manual process of giving access to the service account for each analytics account.

I want my user to authenticate to my website and then only do the rest process based on it.

How can I achieve that?

I also read something that GA4 does not have profiles(views), then how can I access the profile data in GA4? do I need to list down the accounts/properties list to the user for selection?

I need the referral, organic search, users, and session data on my website. What endpoint of GA4 provides this data? Any other library do I need to use?

like image 853
Dipti Gajjar Avatar asked Jun 18 '26 10:06

Dipti Gajjar


1 Answers

I think you are close. You are just mixing oauth and service account.

With your UA analytics code you are using the Google analytics reporting api / google analytics management api to request access of the user to access their Google analytics accounts. You are currently using Oauth2 to request access of a user to access "their" google analytics accounts. These are accounts that they control.

With your GA4 accounts you are connecting to the google analytics admin api though you are currently using a service account.

Service accounts must be pre authorized. They are intended for use with accounts that the developer owns. You need to swtich it to use Oauth2 and not a service account. This way the users will be authenticated to their own account.

Google analytics admin Oauth2

Here is a sample with Oauth2.

<?php

// composer composer require google/analytics-admin

require 'vendor/autoload.php';
use Google\Client;

use Google\Analytics\Admin\V1alpha\AnalyticsAdminServiceClient;

putenv('GOOGLE_APPLICATION_CREDENTIALS=C:\YouTube\dev\credentials.json');  // Installed app credentials.

$credentials =  getenv('GOOGLE_APPLICATION_CREDENTIALS');

$myfile = file_get_contents($credentials, "r") ;

$clientObj = json_decode($myfile);

$client = getClient();

$tokenResponse = $client->getAccessToken();

print_r($tokenResponse);
print_r($tokenResponse["access_token"]);


$service = new AnalyticsAdminServiceClient( [
    'credentials' => Google\ApiCore\CredentialsWrapper::build( [
        'scopes'  => [
            'https://www.googleapis.com/auth/analytics',
            'openid',
            'https://www.googleapis.com/auth/analytics.readonly',
        ],
        'keyFile' => [
            'type'          => 'authorized_user',
            'client_id'     => $clientObj->installed->client_id,
            'client_secret' => $clientObj->installed->client_secret,
            'refresh_token' => $tokenResponse["refresh_token"]
        ],
    ] ),
] );

$accounts = $service->listAccounts();

foreach ($accounts as $account) {
    print 'Found account: ' . $account->getName() . PHP_EOL;
}


function getClient()
{
    $client = new Client();
    $client->setApplicationName('Google analytics admin beta Oauth2');
    $client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
    $client->setAuthConfig(getenv('GOOGLE_APPLICATION_CREDENTIALS'));
    $client->setAccessType('offline');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'tokenAdmin.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

Note this is a console app, not a web app. You may have to tweek it to work with web but you should just be able to copy your UA auth code and dump the tokens in as i have shown here.

Code shamelessly copied from Simple How to Integrate php with Google analytics admin api.

like image 127
DaImTo Avatar answered Jun 21 '26 06:06

DaImTo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!