PHP Google Analytics API - Simple example - php

I am trying to set some basic example of using Google Analytics with this library: https://github.com/google/google-api-php-client
For starter I have:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("MY_SECRET_API"); //security measures
$service = new Google_Service_Analytics($client);
$results = $service->data_ga;
echo '<pre>';
print_r($results);
echo '</pre>';
Q: How to get data from Google Analytics from this query ?
/*
https://www.googleapis.com/analytics/v3/data/
ga?ids=ga%123456
&dimensions=ga%3Acampaign
&metrics=ga%3Atransactions
&start-date=2013-12-25
&end-date=2014-01-08
&max-results=50
*/

$client->setDeveloperKey("MY_SECRET_API");
First of all, for as far as I experienced this won't work for authentication, you'll need to use a OAuth2 authentication. There are two options to do this, using client ID for web application or using a service account. Authorization api
After you have this, you can make a call like this.
(I use a service account here)
First authenticate:
$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);
Make a call:
$ids = 'ga:123456'; //your id
$startDate = '2013-12-25';
$endDate = '2014-01-08';
$metrics = 'ga:transactions';
$optParams = array(
'dimensions' => 'ga:campaign',
'max-results' => '50'
);
$results = $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);
//Dump results
echo "<h3>Results Of Call:</h3>";
echo "dump of results";
var_dump($results);
echo "results['totalsForAllResults']";
var_dump($results['totalsForAllResults']);
echo "results['rows']";
foreach ($results['rows'] as $item) {
var_dump($item);
}

You will need to do a http get to get the information from the url.
http://www.php.net/manual/en/function.http-get.php
Remember you will still need to add the Oauth2 auth code to the string before you can send that request. This link might help if you dont have auth code already.
https://developers.google.com/analytics/solutions/articles/hello-analytics-api#authorize_access

what you could do is create a new function...
function ga_campaign_transactions($gaEmail, $gaPass, $gProfile, $limit)
{
require_once('classes/google-analytics/gapi.class.php');
$gDimensions = array('campaign');
$gMetrics = array('transactions');
$gSortMetric = NULL;
$gFilter = '';
$gSegment = '';
$gStartDate = '2013-12-25';
$gEndDate = '2014-01-08';
$gStartIndex = 1;
$gMaxResults = $limit;
$ga = new gapi($gaEmail, $gaPass);
$ga->requestReportData($gProfile, $gDimensions, $gMetrics, $gSortMetric, $gFilter, $gSegment, $gStartDate, $gEndDate, $gStartIndex, $gMaxResults);
$gAnalytics_results = $ga->getResults();
//RETURN RESULTS
return $gAnalytics_results;
}
$gProfile = '123456'; // The Profile ID for the account, NOT GA:
$gaEmail = 'YOUR GOOGLE EMAIL'; // Google Email address.
$gaPass = 'YOUR GOOGLE PASSWORD'; // Google Password.
// NOTE: if 2 step login is turned on, create an application password.
$limit = 50;
$ga_campaign_transactions = ga_campaign_transactions($gaEmail, $gaPass, $gProfile, $limit)
//OUTPUT
if(!empty($ga_campaign_transactions))
{
$counter=0;
$gaCampResults= array(); // CREATE ARRAY TO STORE ALL RESULTS
foreach($ga_campaign_transactions as $row)
{
$dim_list = $row->getDimesions();
$met_list = $row->getMetrics();
$gaCampResults[$counter]['campaign'] = $dim_list['campaign'];
$gaCampResults[$counter]['transactions'] = $met_list['transactions'];
$counter++;
}
}
if(!empty($gaCampResults))
{
$totalCampTransactions = count($gaCampResults);
?>
<h2>We Found ( <?php echo number_format($totalCampTransactions,0);?> ) Results</h2>
<ul>
<?php
foreach($gaCampResults as $gaRow){
echo "<li>Campaign:".$gaRow['campaign']." | Transactions: ".$gaRow['transactions']."</li>";
}
?>
</ul>
<?php
}
find Analytics Profile ID
Create Google Application password
Hopefully that puts you on the right track :)
untested this, but similar to what I've been using...
Marty

Related

Google Calendar API, getItem and getSummery returns nothing

I seem to have bumped into a google calendar api problem. and I can't really see where I have made the error so an extra set of eyes would be greatly appreciated. The problem in short is that the part of the code that should output the events.. doesn't (the "result" part of the code.
require_once "./google-api-php-client/src/Google/Client.php";
require_once "./google-api-php-client/src/Google/Service/Calendar.php";
// Service Account info
$client_id = "XXXXXX-XXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com";
$app_name = "Some-name";
$service_account_name = 'XXXXX-XXXXXXXXXXXXXXXXXXXXXXX#developer.gserviceaccount.com';
$key_file_location = 'google-api-php-client/Some-name-xxxxxxxxxx.p12';
$cal_id = "primary";
// Service Account info
$client_id = $client_id;
$service_account_name = $service_account_name;
$key_file_location = $key_file_location;
// Calendar id
$calName = $cal_id;
$client = new Google_Client();
$client -> setApplicationName($app_name);
$service = new Google_Service_Calendar($client);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar.readonly'),
$key
);
$client->setAssertionCredentials($cred);
$cals = $service->calendarList->listCalendarList();
print_r($cals);
echo "<br>events<br>";
$events = $service->events->listEvents($calName);
var_dump($events);
echo "<br>result:<br>";
// the following is what returns nothing, works fine until this point.
$i = 0;
foreach ( $events->getItems() as $event ) {
echo 'i:'.$i.' '.$event->getSummary();
$i++;
}
echo 'end';
Change $events to the below line:
$events = $service->events->listEvents('primary', $params);
Instead of primary, add $calName and also send $params in listEvents method.
Hope this works.

Google Analytics API (PHP) pull data from second property

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

How to set up google analytics account service?

I'm new in using Google Analytics API and I'm facing a problem.
i got the error labeled as (403) User does not have any Google Analytics account.
With my google account I am able to view google anaytics pages and by code, I just can't.
Here is my code. i think I misused something in the 6 first lines, but what ?
Any idea is welcomed.
$scope = "https://www.googleapis.com/auth/analytics";
$client_id = "[12 numbers]-[32 letters/numbers].apps.googleusercontent.com";
$service_account_name = "[same 12 numbers]-[same 32 letters/numbers] #developer.gserviceaccount.com";
$key_file_location = "./google-account-service.p12";
$projectId = "[same 12 numbers]";
$projectName = "[my project name defined in console.developers.google.com]";
$client = new Google_Client();
$client->setApplicationName($projectName);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials($service_account_name, array($scope), $key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()){
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$client->getAccessToken();
$service = new Google_Service_Analytics($client);
// metrics
$_params[] = 'date';
$_params[] = 'date_year';
$_params[] = 'date_month';
$_params[] = 'date_day';
// dimensions
$_params[] = 'visits';
$_params[] = 'pageviews';
$_params[] = 'bounces';
$_params[] = 'entrance_bounce_rate';
$_params[] = 'visit_bounce_rate';
$_params[] = 'avg_time_on_site';
$from = date('Y-m-d', time()-2*24*60*60); // 2 days
$to = date('Y-m-d'); // today
$metrics = 'ga:visits,ga:pageviews,ga:bounces,ga:entranceBounceRate,ga:visitBounceRate,ga:avgTimeOnSite';
$dimensions = 'ga:date,ga:year,ga:month,ga:day';
$data = $service->data_ga->get('ga:'.$projectId, $from, $to, $metrics, array('dimensions' => $dimensions));
foreach($data['rows'] as $row) {
$dataRow = array();
foreach($_params as $colNr => $column) echo $column . ': '.$row[$colNr].', ';
}
the service account mail that you use is not valid. You need to create a project in console.developers.google.com and activate the api for google analytics. then you will get acces to you service account email use it in your code.
just a tip i noticed in your code u set the $projectid = the first 12 number as in the $clientid which is as far as i know wrong .. the $projectid must be equal to ( go to your google analytics account , take a look at the URL you will notice there is a segment looks like /a39569200w68518820p70543179/ take the numbers after the 'p' letter in this case the 70543179 numbers and set them as a value for $projectid variable ) i dont know if it solve your problem but i think you should know ..

Google Contact Api PHP - Server Account (server to server): Empty contacts array

When I use "this solution" I get a blank contacts array.
I'm using "google-api-php-client-0.6.7" with a serviceAccount.php into the examples/contacts folder, and a Google_ContactsService into src/contrib folder.
I have configured the Google Apis Access, with OAUTH 2 as Server Account. I have the p12 file, a client id and a cliend mail address. The project name is "Google Contacts Sample".
serviceAccount.php:
<?php
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_ContactsService.php';
const CLIENT_ID = 'xxxxxxxxxxxxx.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = 'xxxxxxxxxxxxx#developer.gserviceaccount.com';
const KEY_FILE = '/absolute_path/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Google Contacts Sample");
session_start();
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(SERVICE_ACCOUNT_NAME, array('https://www.googleapis.com/auth/contacts'), $key));
$client->setClientId(CLIENT_ID);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$token = $client->getAccessToken();
$service = new Google_ContactsService($client);
$result = $service->all();
print '<h2>Contacts Result:</h2><pre>' . print_r($result, true) . '</pre>';
Google_ContactsService.php:
<?php
class Google_ContactsService
{
const SCOPE = "https://www.google.com/m8/feeds";
/**
* #var Google_Client
*/
private $client;
public function __construct($pClient)
{
$this->client = $pClient;
$this->client->setScopes(self::SCOPE);
}
public function all()
{
$result = $this->execute('default/full?max-results=999');
$contacts = array();
foreach($result["feed"]["entry"] as $entry)
{
if(!isset($entry['gd$email']))
$entry['gd$email'] = array();
if(!isset($entry['gd$phoneNumber'])||empty($entry['gd$phoneNumber']))
continue;
$phones = array();
$emails = array();
foreach($entry['gd$phoneNumber'] as $phone)
{
$phone['$t'] = preg_replace('/\+33/', "0", $phone['$t']);
$phone['$t'] = preg_replace('/\-/', '', $phone['$t']);
$phones[] = $phone['$t'];
}
foreach($entry['gd$email'] as $email)
{
$emails[] = $email['address'];
}
$contacts[] = array(
"fullName"=>utf8_decode($entry['title']['$t']),
"phones"=>$phones,
"emails"=>$emails
);
}
return $contacts;
}
private function execute($pUrl)
{
$oauth = Google_Client::$auth;
$request = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/".$pUrl."&alt=json");
$oauth->sign($request);
$io = Google_Client::$io;
$result_json = $io->makeRequest($request)->getResponseBody();
$result = json_decode($result_json, true);
return $result;
}
}
When I go to "http://server.com/packs/googleapi/examples/contacts/serviceAccount.php" I don't see any contact.
The function Execute return empty.
What can I do?
Thanks.
I realize this is old so you have probably moved on but for other's finding this I believe the reason you don't see any contacts is that you are not delegating to a specific user. Not counting shared contacts on Google Apps Premier and Education Editions domains, contacts are private to that user.
I would change this line
$client->setAssertionCredentials(new Google_AssertionCredentials(SERVICE_ACCOUNT_NAME, array('https://www.googleapis.com/auth/contacts'), $key));
to be more like this
$auth = new Google_AssertionCredentials(SERVICE_ACCOUNT_NAME, array('https://www.google.com/m8/feeds'), $key);
$auth->sub = 'user#domain.com'; //whoever's contacts you want to see
$client->setAssertionCredentials($auth);
You could keep the first two lines together if you look at Google_AssertionCredentials method signature, but I think this makes it more explicit. Depending on what you are trying to achieve, user#domain.com will likely be a variable that is set from some kind of input, database, etc.

php zend gdata - Get list of google docs using oauth

I've got my session with the valid token that i set up this way :
$session_token = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
// Store the session token in our session.
$_SESSION['cal_token'] = $session_token;
Then i want to be able to do this:
$service = Zend_Gdata_Docs::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$docs = new Zend_Gdata_Docs($client);
$feed = $docs->getDocumentListFeed();
But using the token. Instead of the authentication with user/pass/service
I already looked at some example of this but i didn't find any way to make it work.
Thank you everyone!
// Retrieve user's list of Google Docs
$client = Zend_Gdata_AuthSub::getHttpClient($_SESSION['cal_token']);
$docs = new Zend_Gdata_Docs($client);
$feed = $docs->getDocumentListFeed();
foreach ($feed->entries as $entry) {
echo "$entry->title\n";
}

Categories