Google Analytics Reporting API V4 requires using OAuth 2.0 for authorization. There are basically 2 ways to work with it, based on the type of your application and your needs.
- Client-side authorization. This is when you are building a function to allow users to access their own Analytics data through your web application. When a user gets to the function for the first time, it redirects user to a sign-in page (the same page as you sign into your Google account) to get a token. The token lasts for some time and after that it requires user to re-login.
- Service account authorization. This is when you are actually using your own analytics data, and especially when you want it to be automatic or offline. An example is that you want to pull data from Google Analytics, say once a day, and store it in your data warehouse. Using a service account allows you to set up a cron event so that it runs automatically every day.
There are several other authentication flows I haven’t worked with yet. If the two points listed above cannot fulfill your need, please refer to this link for more authentication methods.
Okay, now let’s move on to our main topic: how to set up a service account. There are documentations out there, but I’m going to put it together and make it more specific for Google Analytics Reporting API working on Google Client Library in PHP.
On Google Cloud Platform Console, click menu button on the left top corner, then navigate to ‘IAM & Admin’, then select ‘Service accounts’.
Click ‘Create Service Account’. In the pop up window, specify service account name -> select ‘Furnish a new private key’ -> select key type ‘JSON’ -> click ‘Create’.
A JSON file will be downloaded after you click ‘Create’. Put the file in the directory that can be accessed by your application. Note that you can always come back and create another key file whenever needed.
Add the ‘Service account ID’ email to Google Analytics as a user with ‘view’ or higher permission.
Okay, the service account has been set up! Easy, right?
Now it’s time to use it in your code. First, you have to download the Google API Client Library. For PHP, follow the instructions here. Then, put the following code in your script, and you will be able to create a service object.
require_once 'vendor/autoload.php'; $key = PATH_TO_YOUR_JSON_FILE; // create the client object $client = new Google_Client(); // use the service account for authorization putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $key); $client->useApplicationDefaultCredentials(); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); // create the service object $analytics = new Google_Service_AnalyticsReporting($client);
$analytics object is here to service you to make API requests to Google Analytics Reporting API. I’ll give more examples on how to use it later on. Thanks for reading and hope it helps.