How to get google analytics in real time activeUsers in php?

I downloaded the API files from https://github.com/google/google-api-php-client and tried under the 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); 

The error message (401) "Login Required" will appear

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 have the necessary real-time users that belong to the profiler.

So how can I implement the login process (without going to google site)?

I tried the code below ...

 $client_id = 'xxxxxxxxxxxxxxx'; $service_account_name = ' xxxxxxxxxxxxxxxx@developer.gserviceaccount.com '; $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 get access_token and details ... but the extraction of analytical data occurs due to the error "Resolving immunity"

I got the results when I did a test from the Google console with the specified profile ID.

+6
source share
2 answers

Access to the Google Analytics API requires authentication. It looks like you would like to access your own data, not data belonging to another user. To do this, you need to create a service account.

In php client lib on Github that you use, there is an example of using a service account, you can find its service-account.php

This 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 can give you a complete example of using Google Analytics with a service account.

Note to others:

During this question, the real-time API is still in beta, you need to request access. It usually takes 24 hours to access.

+2
source

I successfully display the current data from my GA account to my site using the php code below:

 <?php //Cloning Google API's //git clone https://github.com/google/google-api-php-client.git //Setting include_path in PHP.ini //include_path = ".:/usr/local's/lib/php:/path/to/google-api-php-client/src" //Alternatively, you can set the same ini directive dynamically in your code. $lib_path = $_SERVER['DOCUMENT_ROOT'] . '/path/relative/to/DOCUMENT_ROOT/'; set_include_path(get_include_path() . PATH_SEPARATOR . $lib_path . 'google-api-php-client/src'); require_once 'Google/Client.php'; require_once 'Google/Service/Analytics.php'; $keyfile = 'path/relative/to/DOCUMENT_ROOT/xxxxxxxxxxxxxxxx.p12'; // keyfile location $gaEmail = ' xxxxxxxxxxxxxxxx@developer.gserviceaccount.com '; // email you added to GA $gaAuth = 'https://www.googleapis.com/auth/analytics.readonly'; // Create Client Object $client = new Google_Client(); $client->setApplicationName('Google_Analytics'); // name of your app $client->setClientId('xxxxxxxxxxxxxxxx.apps.googleusercontent.com'); // from API console $client->setAssertionCredentials(new Google_Auth_AssertionCredentials($gaEmail, array($gaAuth), file_get_contents($keyfile))); /* Sample Grabbing Analytics data $service = new Google_Service_Analytics($client); var_dump($service->management_accounts->listManagementAccounts()); $response = $service->data_ga->get( 'ga:87364223', // profile id '2014-09-01', // start date '2014-09-10', // end date 'ga:uniquePageviews', array( 'dimensions' => 'ga:pagePath', 'sort' => '-ga:uniquePageviews', 'filters' => 'ga:pagePath=~/[a-zA-Z0-9-]+/[a-zA-Z0-9-]+', // http://localhost/browse/style/3#showmoreexample url regex filter 'max-results' => '25' ) ); var_dump($response); */ // Your analytics profile id. (Admin -> Profile Settings -> Profile ID) $profile_id = 'ga:xxxxxxxx'; $start = 'yesterday'; $end = 'today'; try { $service = new Google_Service_Analytics($client); $results = $service->data_ga->get($profile_id, $start, $end, 'ga:visits'); echo $results['totalsForAllResults']['ga:visits']; } catch(Exception $e) { echo 'There was an error : - ' . $e->getMessage(); } ?> 
+1
source

All Articles