You might have a need to display data from Google Analytics on your website like number of product page views in your webshop CMS. To achieve that, you would request the page views and maybe sessions (unique visits) for a certain URL from Google Analytics. If you’re using PHP, Google created Google API PHP client to help you do that. In this tutorial we’re going to use Server to Server Application authentication mechanism called two-legged OAuth.
Installing the PHP client
Download code from https://github.com/google/google-api-php-client or, better, use composer and
composer require google/apiclient @stable
Creating a Service Account
Go to Google Developers Console and create a project if you don’t have one for your app. Next, enable the API you want to use, we’re going to use Analytics API in this tutorial. After that, go to Credentials and go and create new Client ID. In the modal, select Service Account. New account will be created and a p12 key file will be downloaded. Store that file in a secure place, readable by your application.
Service account has Client ID and email address: put those in your configuration for future use.
Setting up authorization and Google_Client
To authorize, we’re going to use
[prism key=”code-authorize” language=”php”]
With this authorization credentials, create the client:
[prism key=”code-client” language=”php”]
Calling Analytics API
First, add that service account email address to analytics account view User Management. Next thing is to request analytics data. We’re going to request
pagePath dimension with
pageviews metrics for a specific analytics view. To get the Analytics View ID, go to analytics account -> Admin -> View settings. Data will be sorted by page views in descending order. We are also going to filter the data by pagePath, as we only want products pages.
[prism key=”code-request” language=”php”]
$items array now holds one item, with URL, sessions and page views data. Hope this tutorial helped you, and that you will be able to put various Google Analytics data to good use.