In this simple how to we will look at how to integrate php with the new Google Analytics admin api, using Oauth2. By using Oauth2 we can request consent of the user to access their GA4 Google analytics account in order to retrieve information about their profiles. The Google Analytics admin api is the GA4 equivalent to the Google analytics management api in UA.
Php Analytics admin client library
The Google Analytics admin client library is actually falls under the Google Cloud php client library. It has its own GitHub repository and can be found here Php Analytics admin. As this client library falls under the Google cloud client library for the most part only service account authentication has been documented. This wont work if you want to access the data owned by your user for that we want to use Oauth2.
To achieve that I have merged the two client libraries. The old OAuth Php client library and the PHP Analytics admin library. The good thing about this is that if you are currently connecting to UA using the Google APIs php client library you should be able to copy most of your current authorization code, and just apply it to the Php Analytics admin api as I have shown here.
Authorization to the Php Analytics admin
In the following code which again should be very close to what you have now. I am going to request access of the user and get an access token and refresh token back. This code is for an installed app. So it will not run on a web server. If you need help getting it to work on a web server please feel free to open a question on stack overflow. I should spot it.
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;
}
Applying the authorization.
In the following code. I am loading my credentials and getting an Client using the code above. So my $client should have a valid refresh_token and access_token within it.
I can then build the AnalyticsAdminServiceClient by passing it the refresh token that I have. It will then be able to request a new access token when ever it needs one.
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"]
],
] ),
] );
Conclusion
It can be a little frustrating that Google has only released samples for the Php analytics admin using service accounts. However by merging the old library and the new one we can still use it with standard Oauth2 and request access of our users to access their Google analytics GA4 accounts.