I had successfully configured google analytics api and get successful data.
I want to access analytics api without gmail login.
i.e. I will hard code credentials to for login, but how to do it with PHP?
Is there any api function to achive this task (for PHP)
Thanks!
The Hello Analytics API: PHP Quickstart Guide for Service Accounts will walk you through the steps necessary to create and add a service account to your existing Google Analytics Account/Property/View.
Once you download have the php client libs and the p12 file downloaded from 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 now make calls to the Google Analytics APIs:
// 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');
The Google Analytics API is not fit for what you want for several reasons.
- Security. If the end user has your credentials he can log into your google account and have access to all your data.
- Latency. The API is not intended to be used on page load. If your page loads depend on it it may take a long time to load for your users.
- Quota. The API has a limited quota that will extinguish fast if you query it every time a user enters your website.
- Design. Ultimately, the API was designed to be used by yourself extracting data offline not in real time by others.
With these things in mind if you want to show your users the data you should build some kind of system that downloads the right data you want to show offline, store it in a database and display on the page. This way you can query the data once and show multiple times and not expose your credentials.
Google even published an AppEngine Application that does just that. It queries data and store in a database so it can be viewed by any unathenticated users and with minimum latency since at the view time it's just retrieved from the datastore. It's called Google Analytics superProxy.
UPDATE 09/02
When doing the request on your application you still need to complete oAuth and as you want it to be automated you want to avoid the login screen. There are 2 options
- Use oAuth for Installed Apps. Manually complete the login screen and store refresh tokens. Daily you can use the refresh token to get an access token and query data with no manual intervention.
- Use Service Accounts. These don't require manually approving the login screen but you need to grant access to the service account email in your Google Analytics Account. Service Accounts use crypto to authenticate so you might need a crypto module for php in order to use this.
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
It needs google-api-php-client library, you can create a service account in your google developer console, then add the email if this account into your Google analytics profile 'User Management' for the profile that your want to access.
The follow the code in the links above, you should be able to access your Google analytics data without Goolge login (because your already provide serive account email and p12 key for authorization)
Hi Kiran,
Service Account
Using server side authorization with the Google Python Client API you can use this demo to get access in google analytics data and charts for every user without login.
oAuth for Google APP
The other way is to use oAuth. But in this case you need a payable Google Apps for work Account Google Apps You can read here how to combine Apps and oAuth for access without login.
I have added here the working code for the new (2016) Google Client PHP API Beta for anonymous access using json - including an amChart.
Additionally the renewing process for the json credential files can be automated - this is not done in this code example.
A ClientLogin token can last for 2 weeks from the issue date, but this limit is service-specific and can be shorter. You can change lifetime in Google_AssertionCredentials.php(24) though this is a security risk (for your money - if someone calls the site automatically you run out of the allowed duty free volume)
class Google_AssertionCredentials {
const MAX_TOKEN_LIFETIME_SECS = 360000;
To make the autoload.php work correctly, you have to install the Client PHP API ressources by composer.phar into htdocs(Apache) or wwwroot(IIS) and place this code in the folder "vendor".
I did not use dataLoader and commented it out, for amChart stucks in my environment on load. Therefore I used the dataprovider, which works reliable.
/*
"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;
}
?>
Best regards
Axel Arnold Bangert - Herzogenrath 2016