Google Analytics - access to api without logging in

I successfully configured google analytics api and got successful data.

I want to access api analytics without logging in to gmail.

i.e. I will be hard to enter login credentials, but how to do this with PHP?

Is there any api function to accomplish this task (for PHP)

Thanks!

+7
google-api google-analytics google-analytics-api google-api-php-client
source share
4 answers

Hello Analytics API: PHP Quick Launch Guide for Service Accounts walks you through the steps necessary to create and add a service account to an existing Google Analytics Account / Property / View.

After downloading, you have the php client files and the p12 file downloaded from the developer console, you can create an authorized analytics service object as follows:

// Creates and returns the Analytics service object. // Load the Google API PHP Client Library. require_once 'google-api-php-client/src/Google/autoload.php'; // Use the developers console and replace the values with your // service account email, and relative location of your key file. $service_account_email = '<Replace with your service account email address.>'; $key_file_location = '<Replace with /path/to/generated/client_secrets.p12>'; // Create and configure a new client object. $client = new Google_Client(); $client->setApplicationName("HelloAnalytics"); $analytics = new Google_Service_Analytics($client); // Read the generated client_secrets.p12 key. $key = file_get_contents($key_file_location); $cred = new Google_Auth_AssertionCredentials( $service_account_email, array(Google_Service_Analytics::ANALYTICS_READONLY), $key ); $client->setAssertionCredentials($cred); if($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion($cred); } return $analytics; 

With the returned service object, you can make calls to the Google Analytics API:

 // Calls the Core Reporting API and queries for the number of sessions // for the last seven days. $analytics->data_ga->get( 'ga:' . $profileId, '7daysAgo', 'today', 'ga:sessions'); 
+2
source share

The Google Analytics API is not suitable for you for several reasons.

  • Safety If the end user has his own credentials, he can log in to your google account and gain access to all your data.
  • Delay The API is not intended to be used on page loading. If the loading of your page depends on it, the loading may take a long time for your users.
  • Quota . The API has a limited quota that will extinguish quickly if you request it every time a user enters your site.
  • Design . Ultimately, the API was designed to be used by the extraction of data offline, and not in real time by others.

Given this, if you want to show your users data, you must create some kind of system that downloads the necessary data that you want to display offline, store it in the database and display on the page. Thus, you can request data once and show it several times, rather than disclosing your credentials.

Google even published an AppEngine app that does just that. It requests data and stores it in a database, so it can be viewed by any unauthenticated users and with a minimum delay, because at a time it is simply retrieved from the data warehouse. He called the super program Google Analytics .

UPDATE 09/02

When executing the request in your application, you still need to run the oAuth command and, as you want it to be automated, you want to avoid the login screen. There are 2 options

  • Use oAuth for installed applications . Manually enter the login screen and save the update tokens. You can use the update token daily to get the access token and request data without manual intervention.
  • Use service accounts . You don’t need to manually approve the login screen, but you need to provide email access to the service account in your Google Analytics account. Service accounts use cryptography for authentication, so a crypto module for php may be required for use.
0
source share

Use service account: https://developers.google.com/api-client-library/php/auth/service-accounts https://developers.google.com/analytics/solutions/articles/hello-analytics-api# authorize_access

To do this, you need the google-api-php-client library, you can create a service account in the Google developer console, and then add an email if this account is in your Google Analytics user management profile for the profile you want to access. By following the code in the links above, you can access your Google Analytics data without logging in to Goolge (because you already have an email address and a key p12 for authorization)

0
source share

Hi Kieran,

  • Service account
    Using server-side authorization using the Google Python Client API, you can use this demo to access Google Analytics data and charts for each user without logging in .

  • oAuth for Google APP
    Another way is to use oAuth. But in this case, you need to pay for a Google Apps account to run Google Apps . You can read here how to combine applications and oAuth for access without login.

I added here the working code of the new (2016) beta version of the Google Client PHP client for anonymous access using json - including amChart.

In addition, the process of updating json credential files can be automated - this is not done in this code example. ClientLogin current may last 2 weeks from the release date, but this limit is service specific and may be shorter. You can change the lifespan in Google_AssertionCredentials.php (24), although this is a security risk (for your money - if someone calls the site it will automatically end with the allowable amount of duty free trading)

 class Google_AssertionCredentials { const MAX_TOKEN_LIFETIME_SECS = 360000; 

To make autoload.php work correctly, you need to install Client PHP API resources using composer.phar in htdocs (Apache) or wwwroot (IIS) and put this code in the vendor folder.

I did not use dataLoader and commented on it, for amChart stucks in my environment at boot time. Therefore, I used a dataprovider that works reliably.

 /* "dataLoader": { "url": "data.php", "format": "json" }, */ <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <title>Gimba - Google Analytics - GimbaChartAll</title> <script src="https://www.amcharts.com/lib/3/amcharts.js"></script> <script src="https://www.amcharts.com/lib/3/serial.js"></script> <script src="https://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"></script> <style> body, html { font-family: Verdana; font-size: 10px; } #chartdiv { width: 1100px; height: 700px; margin-left:auto; margin-right:auto; } </style> <script> var dataJS = <?php echo dataGA(); ?>; var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "theme": "light", /* "dataLoader": { "url": "data.php", "format": "json" }, */ "dataProvider": dataJS , "categoryField": "country", "categoryAxis": { "gridColor": "#0000FF", "gridAlpha": 0.07, "title": "Country" }, "creditsPosition": "top-right", "categoryField": "country", "categoryAxis": { "gridAlpha": 0.07, "gridPosition": "start", "tickPosition": "start", "title": "Country" }, "valueAxes": [ { "id": "v1", "gridAlpha": 0.1, "axisColor": "#0000ff", "title": "Users/Sessions" }, { "id": "v2", "gridAlpha": 0, "axisColor": "#0000ff", "position": "right", "title": "Page views" } ], "graphs": [ { "startDuration": 3, "type": "column", "title": "Sessions", "valueField": "sessions", "fillColors": "#0000ff" , "lineAlpha": 0, "fillAlphas": 0.6 }, { "type": "column", "title": "Users", "valueField": "users", "fillColors": "#0000ff" , "lineAlpha": 0, "fillAlphas": 0.2 }, { "type": "line", "valueAxis": "v2", "title": "Page views", "valueField": "pageviews", "lineColor": "#0000ff" , "lineThickness": 1, "bullet": "round" } ], "legend": {} } ); </script> </head> <body> <div id="chartdiv"></div> </body> </html> <?php //dataGA(); function dataGA() { require_once 'autoload.php'; $google_account = array( 'email' => ' xxxxxxxxxxxxxxxxxxxxxx@xxxxxxxxxxxxxxxx.iam.gserviceaccount.com ', 'key' => file_get_contents(__DIR__ . '/OAuthClientServiceAccount1.json'), 'profile' => 'xxxxxxxxx' ); // Creates and returns the Analytics service object. // Load the Google API PHP Client Library. // Create and configure a new client object. $client = new Google_Client(); $client->setApplicationName( 'Gimba3' ); $analytics = new Google_Service_Analytics($client); $scopes = array('https://www.googleapis.com/auth/analytics.readonly'); $client->setScopes($scopes); try{ $client->setAuthConfigFile(__DIR__ . '/OAuthClientServiceAccount1.json'); } catch(Exception $e){ echo "Key NOT OK<br>"; echo $e->getMessage()."<br>"; } try{ if( $client->isAccessTokenExpired() ) { $client->refreshTokenWithAssertion($client->setAuthConfigFile(__DIR__ . '/OAuthClientServiceAccount2.json')); } } catch(Exception $e){ echo "RefreshKey NOT OK<br>"; echo $e->getMessage()."<br>"; } $projectId = '123464155'; $results = $analytics->data_ga->get( 'ga:'.$projectId, '30daysAgo', 'today', 'ga:sessions,ga:users,ga:pageviews', array( 'dimensions' => 'ga:country', 'sort' => '-ga:sessions', 'max-results' => 10 )); $rows = $results->getRows(); //var_dump($rows); $dataGA = array(); foreach( $rows as $row ) { $dataGA[] = array( 'country' => $row[0], 'sessions' => $row[1], 'users' => $row[2], 'pageviews' => $row[3] ); } $res = json_encode($dataGA); return $res; } ?> 

Sincerely, Axel Arnold Bangert - Herzogenrath 2016

0
source share

All Articles