Google Analytics API Authentication

in Google Analytics API

This article explains how to obtain OAuth tokens for use with the Google Analytics API. I'm writing some tutorials for the API at the moment, but all calls to it require a common step to obtain access tokens, so I'm documenting the process here to save repeating myself. I'm just going to cover the Installed Application OAuth flow because it's a quick method of generating some tokens for development purposes.

Registering Your Application

Before you use OAuth, you need to register your application in the Google API console. Once you've signed in to the console using your Google account, you will see the following screen:

Creating a Project in the Google API Console
Creating a Project in the Google API Console

If you're already using the console for another API, then you won't see this screen, you'll go directly to the dashboard; otherwise, you'll need to create a project using the Create Project button to generate a generic project called API Project, then you will be taken to the dashboard:

The Google API Console Dashboard
The Google API Console Dashboard

You fist need to activate the Analytics API for your account by changing its status in the Services tab:

The Google API Console Services Tab
The Google API Console Services Tab

When you click on the button in the Status column, you will be taken to a page to accept the API terms of usage, then the button will light up to show that the API is active.

Now that you've activated the console and GA API, you can go to the API Access tab to generate the client tokens you need for you tool:

The Button for Creating a Client ID
The Button for Creating a Client ID

Press the big blue button to create a new OAuth client ID, then a dialog will appear for you to enter your application name and branding details:

Product Name and Logo Shown to your Users
Product Name and Logo Shown to your Users

The only required field is the Product Name, so you just need to enter a name into it and click next to be taken to the Client ID Settings screen:

Selecting the Type of Client ID to Create
Selecting the Type of Client ID to Create

Change the Application Type to Installed application then press the Create client ID button, and your tokens should be generated:

Your Client ID, Client Secret, and Redirect URL
Your Client ID, Client Secret, and Redirect URL

Obtaining an OAuth Token

Now that you have a client ID and secret, you need to authorize your application to access your Google Analytics account. This is achieved by visiting the Google OAuth console using the URL generated by the following code:

<?php
require_once(dirname(__FILE__) . "/google-api-php-client/src/Google_Client.php");
 
$clientId = "YOUR_CLIENT_ID";
$clientSecret = "YOUR_CLIENT_SECRET";
$redirectUrl = "urn:ietf:wg:oauth:2.0:oob";
 
$analyticsWriteScope = "https://www.googleapis.com/auth/analytics";
 
$client = new Google_Client();
$client->setClientId($clientId);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUrl);
$client->setScopes(array($analyticsWriteScope));
 
$authUrl = $client->createAuthUrl();
 
print "$authUrl\n";
?>
Generating an OAuth 2.0 Authorization URL

This is using the Google API Client Library for PHP, so you need to download and extract it into the root of your project directory. Then you need to enter the client tokens you generated earlier into the $clientId and $clientSecret variables. Once you run this code, the you should be presented with an authorization URL similar to the following:

https://accounts.google.com/o/oauth2/auth?response_type=code
&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&client_id=1234567890
-3dfgdh4o8dgd432jnedbok123456b6q1fe.apps.googleusercontent.com
&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics
&access_type=offline&approval_prompt=force
Example OAuth Authorization URL

Navigating to this URL in a browser will take you to the following screen:

Google OAuth Console
Google OAuth Console

Pressing the Allow button should generate an initial OAuth code:

OAuth Code
OAuth Code

You can use this code with the following script to generate a set of OAuth parameters that can be used with the API:

<?php
require_once(dirname(__FILE__) . "/google-api-php-client/src/Google_Client.php");
 
$clientId = "YOUR_CLIENT_ID";
$clientSecret = "YOUR_CLIENT_SECRET";
$oauthCode = "YOUR_GENERATED_CODE";
$redirectUrl = "urn:ietf:wg:oauth:2.0:oob";
 
$analyticsWriteScope = "https://www.googleapis.com/auth/analytics";
 
$client = new Google_Client();
$client->setClientId($clientId);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUrl);
$client->setScopes(array($analyticsWriteScope));
 
$oauthParams = $client->authenticate($oauthCode);
 
print "$oauthParams\n";
?>
Generating OAuth Access and Refresh Tokens

This is pretty much the same code as before, but it has an additional variable, called $oauthCode, for your access code and it's using the authenticate() method to generate the OAuth parameters instead of the createAuthUrl() method used in the previous script. Running this should output a JSON object containing all the parameters you need to access an account using the Google Analytics API:

{
 "access_token":"ya12.GYABDEDSA21d555U444NCmzaUtiJ5zzzzZCrSDSfv344DSg4111urYg",
 "token_type":"Bearer",
 "expires_in":3600,
 "refresh_token":"1\/ABCD1DSALqwCsfSFDGGSFDBccSfggddd",
 "created":1361313449
}
The JSON Response from the OAuth API

This needs to be saved somewhere ready for use in future scripts.

Comments

I'm keen to get feedback on my posts, so if you have any questions or comments, then please send me a message and I'll be happy to help.