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
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:
You fist need to activate the Analytics API for your account by changing its status in the 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:
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:
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:
Change the Application Type to Installed application then press the Create client ID button, and your tokens should be generated:
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:
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
$clientSecret variables. Once you run this code, the you should be presented with an authorization URL similar to the following:
Navigating to this URL in a browser will take you to the following screen:
Pressing the Allow button should generate an initial 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:
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:
This needs to be saved somewhere ready for use in future scripts.