Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch google analytics realtime activeUsers in php?

I downloaded API files from https://github.com/google/google-api-php-client and tried below code...

$client->setApplicationName("Analytics");
$client->setDeveloperKey("key");
$service = new Google_Service_Analytics($client);

$optParams = array(
    'dimensions' => 'rt:medium');

try {
  $results = $service->data_realtime->get(
      'ga:profileid',
      'rt:activeUsers',
      $optParams);
  // Success.
} catch (apiServiceException $e) {
  // Handle API service exceptions.
  $error = $e->getMessage();
}
print_r($results);

It shows an error (401) Login Required'

When i tried the call from https://console.developers.google.com/project/apps~rational-photon-578/apiui/api/analytics/method/analytics.data.realtime.get

I got the required realtime users belongs profileid.

So how can i implement a login process (Without going to google site) in this ?

I tried the below code...

$client_id              = 'xxxxxxxxxxxxxxx';
$service_account_name   = '[email protected]';
$key_file_location      = 'location of .p12 keyfile';

$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");

if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}

$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics'),
$key
);

$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
} 

$_SESSION['service_token'] = $client->getAccessToken();
echo $_SESSION['service_token'];
$service = new Google_Service_Analytics($client);


$optParams = array(
'dimensions' => 'rt:medium');


try {
$results = $service->data_realtime->get(
  'ga:profileid',
  'rt:activeUsers',
  $optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}
print_r($results);

Here i am getting the access_token and details...but the analytics data fetching fails because an error "Insuffient permission"

I got the results when i made test from google console with mentioned profile id.

like image 374
jpk Avatar asked May 13 '14 13:05

jpk


People also ask

How do I extract data from Google Analytics API?

It's very simple. Go to Behavior => Overview, click the “Export” button, and select the format for exporting your report (PDF, Google Sheets, Excel, CSV).


1 Answers

Accessing the Google Analytics API requires authentication. It sounds like you would like to access your own data and not data owned by another user. To do this you will need to create a service account.

The php client lib on Github that you are using, has an example for using a service account you can find it service-account.php

The example uses the Boooks API. You can change it to the Google analytics API by doing the following

$service = new Google_Service_Books($client);

change to

$service = new Google_Service_Analytics($client);

If you have any problems let me know and I will see if I cant give you a full example using Google Analytics with a service account.

Note for others:

At the time of this question the Real-time API is still in beta you have to request access. Normally takes 24 hours to get access.

like image 62
DaImTo Avatar answered Nov 15 '22 00:11

DaImTo