How do I retrieve Google Analytics data through the Google Analytics API using PHP?
Is it possible to get a page wise status through API?
I am working with a website having 30K pages and I need to create a dashboard showing page wise statistics for corresponding user.
Yes it is possible to get the stats you are talking about though the Google Analytics API using PHP.
There is a client library for php that I recommend it can be found on GitHub
Because you will only be accessing your own data I recommend you go with a service account for authentication.
Simple example:
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
//calulating start date
$date = new DateTime(date("Y-m-d"));
$date->sub(new DateInterval('P10D'));
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params );
?><html>
<?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td>".$header['name']."</td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
<?php
?>
I you can find a tutorial for that code at Google Service account php
Related
I have created a php script that uses the Google Analytics API, I want to run it with a cron job once an hour. It works fine in my browser, but I need to sign in from time to time with my gmail account and grant access.
How can I save my gmail login data in the php script, so it signs in automatically? This script will only use my login data, so it can be hard coded.
<?php
require_once 'Google/autoload.php';
session_start();
// ******************************************************** //
// Get these values from https://console.developers.google.com
// Be sure to enable the Analytics API
// ******************************************************** //
$client_id = 'xxxxxxxx';
$client_secret = 'xxxxxxxx';
$redirect_uri = 'http://example.com/xxxx';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType('offline'); // Gets us our refreshtoken
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
print "Access from google: " . $_SESSION['token']."<br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "<b>Account:</b> ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo '-----<b>WebProperty:</b> ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
// note sometimes a web property does not have a profile / view
foreach($wp->getProfiles() as $view) {
echo '----------<b>View:</b> ' ,$view['name'], " " , $view['id'], "<br /> \n";
} // closes profile
}
} // Closes web property
} // closes account summaries
}
//Adding Dimensions
$params = array('dimensions' => 'ga:pagePath', 'metrics' => 'ga:timeOnPage,ga:uniquePageviews');
// requesting the data
$data = $service->data_ga->get("ga:xxxxxxxx", date("Y-m-d"), date("Y-m-d"), "ga:users,ga:sessions", $params );
?><html>
<?php echo date("Y-m-d") . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td>".$header['name']."</td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
if($row[1]<7.0 && $row[2]>100 ){
$length = strlen($row[0]);
if($length<12){
$row[0] = substr($row[0], 3);
print $row[0];
$short_url=$row[0];
$blocked=1;
//PDO
// configuration
$dbhost = "localhost";
$dbname = "xxxxxxxxx";
$dbuser = "xxxxxxxxx";
$dbpass = "xxxxx";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "UPDATE urls SET blocked = :blocked WHERE short_url = :short_url";
$q = $conn->prepare($sql);
$q->execute(array(':short_url'=>$short_url,
':blocked'=>$blocked ));
}
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td><td>".$row[3]."</td></tr>";
}
}
//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
?>
Use a service account instead.
A service account doesn’t need to prompt a user for access because you have to set it up. Go to the Google Analytics website in the Admin section for the Account you want to retrieve data from. This is very important it must be at the account level add this email address as a new user. just give them read access.
<?php
require_once 'Google/autoload.php';
session_start();
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '[Your client id]';
$Email_address = '[YOur Service account email address Address]';
$key_file_location = '[Locatkon of key file]';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials($Email_address,
array($scopes),
$key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12-14", "ga:users,ga:sessions", $params );
?>
<html>
Results for date: 2014-12-14<br>
<table border="1">
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td><b>".$header['name']."</b></td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
code ripped from Google Service account Php
For a particular website in my Google Analytics account, two properties are registered for the same website. Don't know who set it up like this first, but for now the first one has data from, say, 2010 to 2012, and the second has 2013 onward. I want to access the second property. Here's what the reporting page looks like (names smudged out):
By following the official tutorial for PHP, I'm able to access the first account and display its total sessions. But I'm not able to access the second account. I thought I'd change the following function:
function getFirstprofileId(&$analytics) {
$index = 0;
$accounts = $analytics->management_accounts->listManagementAccounts();
echo "<pre>";
print_r($accounts);
echo "</pre>";
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[$index]->getId();
$webproperties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($webproperties->getItems()) > 0) {
$items = $webproperties->getItems();
$firstWebpropertyId = $items[$index]->getId();
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstWebpropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
return $items[$index]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No webproperties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
The $index = 0; thing you see is what I did, thinking that just by changing $index to 1 or something, I'll be able to access the next property, but it throws me an error saying Call to a member function getId() on a non-object on the code $firstAccountId = $items[$index]->getId();
Any help will be appreciated.
The problem you are having is probably related to the fact that you are using an old tutorial. Which uses Oauth2 and the old PHP client lib. Because you are only trying to access your own data I recommend you go with a service account.
The current php client lib can be found on github: Google-api-php-client
Below is the code from my tutorial on using a service account with php to access Google Analytics Data.
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
//calulating start date
$date = new DateTime(date("Y-m-d"));
$date->sub(new DateInterval('P10D'));
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params );
?><html>
<?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td>".$header['name']."</td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
Make sure that you give the service account email address access at the Account level in Google Analytics.
Code ripped from the tutorial: Google Service account PHP
I have a site where I would like to show all visitors some data from my Google Analytics account (unique page views from separate countries). As far as I'm concerned it is possible to do this with OAuth 2.0 and Google Analytics API. I would like the authentication to be automated, so that whoever comes to my site can view this data, not just me who can log in to my Google Analytics account.
What I've done
Made a project with Google Developers Console.
Changed Analytics API to ON.
Created a service account.
Generated API key for both server- and browser applications (don't know which and where to use exactly).
Downloaded Google APIs Client Library for PHP.
Uploaded the .p12 key that was downloaded when I created a service account, uploaded it to my site and linked to it in google-api-php-client-master/examples/service-account.php.
Declared my service account client id in google-api-php-client-master/examples/service-account.php.
Current code
<?php
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
session_start();
include_once "templates/base.php";
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Books.php';
/************************************************
ATTENTION: Fill in these values! You can get
them by creating a new Service Account in the
API console. Be sure to store the key file
somewhere you can get to it - though in real
operations you'd want to make sure it wasn't
accessible from the webserver!
The name is the email address value provided
as part of the service account (not your
address!)
Make sure the Books API is enabled on this
account as well, or the call will fail.
************************************************/
$client_id = 'SECRET-NUMBERS.apps.googleusercontent.com';
$service_account_name = '';
$key_file_location = 'SOMENUMBERS-privatekey.p12';
echo pageHeader("Service Account Access");
if ($client_id == 'SECRET-NUMBERS.apps.googleusercontent.com'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new Google_Service_Books($client);
/************************************************
If we have an access token, we can carry on.
Otherwise, we'll get one with the help of an
assertion credential. In other examples the list
of scopes was managed by the Client, but here
we have to list them manually. We also supply
the service account
************************************************/
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.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
/************************************************
We're just going to make the same call as in the
simple query as an example.
************************************************/
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
echo "<h3>Results Of Call:</h3>";
foreach ($results as $item) {
echo $item['volumeInfo']['title'], "<br /> \n";
}
echo pageFooter(__FILE__);
Issues
In google-api-php-client-master/examples/service-account.php there's this piece of code which I don't quite understand:
$service_account_name = '';
what should I declare here?
When I have done all the above and loaded the page google-api-php-client-master/examples/service-account.php on my site, I get these two errors:
Warning: You need to set Client ID, Email address and the location of the Key from the Google API console
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'' in /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php:327 Stack trace: #0 /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php(289): Google_Auth_OAuth2->refreshTokenRequest(Array) #1 /home/texterx1/public_html/google-api-php-client-master/examples/service-account.php(75): Google_Auth_OAuth2->refreshTokenWithAssertion(Object(Google_Auth_AssertionCredentials)) #2 {main} thrown in /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php on line 327
What have I done wrong?
Ok the first thing you need to do is grab the Email address on developer console for your app that was created along with the app.
1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com
Login to your GA go to the admin section for the account you want the Service account to access. You need to give that email account Access at the account level just give them Read and analyze.
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
// Values from APIs console for your app
$client_id = 'Client ID';
$service_account_name = 'Email address';
$key_file_location = 'The file you downloaded';
$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.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
}
I am trying to access my Google Drive files from a php script that will be run in a cron job, but I can't see my files.
I am using a Service account set up in Google Developpers console, which do not need authorisation interaction with the user (me).
This is my code:
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
$client_id = '260186860844-kg9uiqe7pjms3s54gabqfnph0iamjdjn.apps.googleusercontent.com';
$service_account_name = '260186860844-kg9uiqe7pjms3s54gabqfnph0iamjdjn#developer.gserviceaccount.com';
$key_file_location = 'privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Whatever");
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/drive'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Drive($client);
$parameters = array(
// 'maxResults' => 10,
);
$dr_results = $service->files->listFiles($parameters);
foreach ($dr_results as $item) {
echo $item->title, "<br /> \n";
}
It seems I am correctly connected (got token, no errors prompted), but I only get one single file listed, which is not part of my Drive, and which is named "How to get started with Drive"!
I am using latest Google APIs Client Library for PHP , with php 5.4
Google will create its own google drive for service account.
What you need to do is SHARE your folder with service's account email from console.
Give it permission "can edit".
I made a shared folder in my GUI accessible drive, then I insert the files from the commandline under this folder shared, so I see them ;)
I am implementing cloud storage api in php for uploading mp3 files and loading those in site.
I want to upload the files without authorization dialog is that possible? is there any sample without oauth2?
Everything going to cloud storage needs auth key. You can set up a service account get a bearer key without the user logging in. I modified some code from google-api-php-client. To provide the bearer key. Using the following.
function getMediaKey(){
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path("../google-api-php-client/src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
$client_id = '<your clientid>';
$service_account_name = '<serviceaccountemail';
$key_file_location = '< location of you privatekey.p12>';
//echo pageHeader("Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/devstorage.full_control'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$bearerKey = $client->getAccessToken();
return $bearerKey;
}
Then you can post your media files using the bearer key.
checkout https://developers.google.com/storage/docs/json_api/
Try it for examples