A Complete Example of Using Google Analytics Reporting API V4 in PHP to Get Custom Report

In the Google Analytics web console, user can create custom reports by specifying dimensions and metrics. There are many reasons you may want to use the Google Analytics Reporting API to programmatically create custom reports. For example,

  1. There are too many entries in the generated custom reports. The web console allows you to select only 5000 rows at a time and export.
  2. You want to combine more dimensions in a report. The web console allows you to add at most 5 dimensions, while the API allows 7.
  3. You want to automate the data exporting process. Say you would like to have a report automatically generated every day and stores in your database.

This example supposes that you have the following prepared:

  1. Knowledge about Google Analytics custom report, dimensions, metrics, etc.
  2. Have the Google API client library installed. If not, please refer to this document.
  3. Set up OAuth 2.0 for authorization. If not, please refer to my previous post.

Continue reading

Set Up Service Account for Google Analytics Reporting API – a PHP Example

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.

  1. 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.
  2. 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.

Continue reading