Step 1 – Create an API project from: https://console.developers.google.com/project
Step 2 – Give your project Analytics access
Step 3 – Create a service account set of OAuth creds.:
Step 4 – Download your newly created .p12 key
Step 5 – Link to your google analytics account from the admin section and make a note of the account id
The email you add to your account is the email generated when created the service oauth key in step 4. You need to give this email account full permissions.
Make a note of the account id here as you will need it for step 7.
Step 6 -Install the key and Google API Client to your server
1 – Download the php from: https://github.com/google/google-api-php-client
2 – You should already have the key from step 4.
3 – Decide on somewhere sensible to store the google code and key in your project. Away from the publicly accessible webroot.
Step 7 – Time to write/copy some code.
//include the api lib
// Start the google v3 api server authorization
$client = new Google_Client();
$cred = new Google_Auth_AssertionCredentials(
file_get_contents( __DIR__ . '/google-keys/AnXXXXXXXXXXXd.p12' )
//start the analytics shtuff
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
// requesting the data
$google_data = $service->data_ga->get(
"ga:XXXXXXX", //this is the account id you made a note of in step 5
'dimensions' => 'ga:pagePath'
//add filters and any other parameters here
- Ensure all your files on the server are correct, ie writeable by Apache
- Ensure the path to your .p12 key file is correct!
- Ensure the 1st param in the $cred is the email google made for you in the oauth console
- Ensure that that email is in your google analytics account with full permissions
- Ensure that you correct the account is in the first param passed to $service->data_ga->get(
- Ensure you update your project name in the code: $client->setApplicationName(‘YOURPOJECTNAME’);
- All the above code assumes you are simply dumping all the keys and google code into the same folder as the php file itself. But a better idea might be to place the google api code and keys somewhere completely separate to this analytics php sample in step 7. That way you can write separate files to access other google api’s without mixing things up.
That is about it. That took a while to find all that information as the docs are fairly useless for a newcomer to the GoogleAPI world.