Getting Google Analytics RealTime data (part 2: OAuth)

To be able to connect to Google API through a server (and without having to imput a password every time, we need to establish an OAuth Connection.

* 1. create project at https://console.developers.google.com/project
* 2. enable 'Analytics API' under 'APIs & auth' / APIs
* 3. create 'NEW CLIENT ID' (OAuth client) under 'APIs & auth' / Credentials
* i. select 'Service account'
* ii. save generated key file to 'key.p12' and upload it on your server web directory
* iii. remember CLIENT ID
* 4. Access your Google Analytics Account, then, under the tab "Admin", go to User Management, and add as a new user with basic read & analyse access the long email address generated when you created your API credenticals: xxxxxxxxx-yyyyyyyyyyyyyyyyyy@developer.gserviceaccount.com
* 5. get View ID, (see the last article that show how to find it)
* 5. download or clone the google php library https://github.com/google/google-api-php-client
* 6. Code the program in php thanks to these resources:
* doc here: https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime/get

* real time metrics doc: https://developers.google.com/analytics/devguides/reporting/realtime/dimsmets/



Check the following code :

require_once 'google-api/src/Google/autoload.php'; $PATH_TO_KEY_FILE = '/oauth/client_secrets.p12';$CLIENT_ID = 'lklkklklklklklk3rqrv5jkh0.apps.googleusercontent.com';
$CLIENT_EMAIL = '44773430-qolfdfdfdfqpb93ke46lb0odq@developer.gserviceaccount.com';
$SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
$GA_VIEW_ID = 'ga:6335556';
$client = new Google_Client();
$client->setClientId($CLIENT_ID);
$client->setAssertionCredentials(
    new Google_Auth_AssertionCredentials(
        $CLIENT_EMAIL,
        array($SCOPE),
        file_get_contents($PATH_TO_KEY_FILE)
    )
);
$service = new Google_Service_Analytics($client);
try {
    $result = $service->data_realtime->get(
        $GA_VIEW_ID,
        'rt:activeVisitors'
    );
//print the number of visitors realtime
    echo $result->totalsForAllResults['rt:activeVisitors'];
     
} catch(Exception $e) {
    var_dump($e);
}
?> 





Commentaires