Question

I'm developing a website that uses Google Analytics API. I followed this tutorial -> https://developers.google.com/analytics/solutions/articles/hello-analytics-api?hl=pt-PT

and everything works fine. I get the "consent screen", I give "permissions" and I'm redirected to my website, with all information.

But, I want to change the things a little. I want to get all info of Google Analytics, without using the "consent screen", i.e. , using just the Google Analytics code (UA-XXXXXXXX-X) or any other way.

Any help?

Thanks

Was it helpful?

Solution

In order to use the Google analytics API you need authorization (permission to access the data). Becouse you only want to see your own data I recommend that you look into a service account. By setting up a service account in Google apis console it will allow you to access your own data with out needing to login and autenticate the code all the time.


Here is an example of how to use a service account in php ServiceAccount

That sample project is for the PredictionService not the google analytics service. You need to edit it slightly.

require_once '../../src/Google/Client.php'; 
require_once '../../src/Google/Service/Analytics.php'; 

// Set your client id, service account name, and the path to your private key. 
// For more information about obtaining these keys, visit: 
// https://developers.google.com/console/help/#service_accounts

const CLIENT_ID = 'INSERT_YOUR_CLIENT_ID'; 
const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME'; 


// Make sure you keep your key.p12 file in a secure location, and isn't 
// readable by others.

const KEY_FILE = '/super/secret/path/to/key.p12'; 


$client = new Google_Client(); 
$client->setApplicationName("Google Analytics Sample"); 


// Load the key in PKCS 12 format (you need to download this from the 
// Google API Console when the service account was created. 


$client->setAssertionCredentials(new Google_AssertionCredentials( 
    SERVICE_ACCOUNT_NAME(Email), 
    array('https://www.googleapis.com/auth/analytics.readonly'), 
    file_get_contents(KEY_FILE)) 
); 


$client->setClientId(CLIENT_ID); 
$service = new Google_Service_Analytics($client);

Now you have $service that you can use with the rest of your calls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top