Google Analytics API (PHP) pull data from second property - 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

Related

Google Analytics API: auto login user and fetch data, showing error "The OAuth client was invalid."

I want to access google analytic data using oAuth , so that I do not have to login again and again.
for that I download google analytic Php library , install it using composer , put the code provided by google , my code is below -
require_once 'vendor/autoload.php';
$analytics = initializeAnalytics();
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
printResults($results);
function initializeAnalytics()
{
// Creates and returns the Analytics Reporting service object.
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = 'myproject.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
return $analytics;
}
function getFirstProfileId($analytics) {
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
// Get the list of views (profiles) for the authorized user.
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
// Return the first view (profile) ID.
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults($analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
function printResults($results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "First view (profile) found: $profileName\n";
print "Total sessions: $sessions\n";
} else {
print "No results found.\n";
}
}
When I used to run this code it providing below error -
Fatal error: Uncaught Google_Service_Exception: { "error": "invalid_client", "error_description": "The OAuth client was invalid." } in D:\wamp64\www\store2\pdf\printpdf\vendor\google\apiclient\src\Google\Http\REST.php on line 118
Basically, if anybody can provide me a step by step process of accessing data from google analytics, because I roll out my head whole day, but there is not a single post which can provide me steps to follow, some which I found are old , and not working for me
This is the code i use
Serviceaccount.php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
$service = getAuthenticateServiceAccount();
/**
* Authenticating to Google using a Service account
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Initializes an Analyticsreporting.v4 service object.
*
* #return An authorized Analyticsreporting.v4 service object.
*/
function getAuthenticateServiceAccount() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Analytics::ANALYTICS);
return new Google_Service_AnalyticsReporting($client);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
?>
Reporting.php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/ServiceAccount.php';
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2016-01-01");
$dateRange->setEndDate("2017-06-30");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("ga:sessions");
$users = new Google_Service_AnalyticsReporting_Metric();
$users->setExpression("ga:users");
$users->setAlias("ga:users");
//Create the Dimensions object.
$date = new Google_Service_AnalyticsReporting_Dimension();
$date->setName("ga:date");
$pagePath = new Google_Service_AnalyticsReporting_Dimension();
$pagePath->setName("ga:pagePath");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("81692014");
$request->setPageSize("10000");
$request->setDateRanges($dateRange);
$request->setDimensions(array($date,$pagePath));
$request->setMetrics(array($sessions,$users));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
$data = $service->reports->batchGet( $body );
showData($data->reports[0]);
$cnt = 0;
while ($data->reports[0]->nextPageToken > 0 && $cnt < 1) {
// There are more rows for this report.
$body->reportRequests[0]->setPageToken($data->reports[0]->nextPageToken);
$data = $service->reports->batchGet( $body );
showData($data->reports[0]);
$cnt++;
}
function showData($data) {
?> <pre><table><?php
?><tr><?php // Header start row
for($i = 0; $i < sizeof($data->columnHeader->dimensions);$i++) {
?> <td> <?php print_r($data->columnHeader->dimensions[$i]); ?> </td> <?php
}
for($i = 0; $i < sizeof($data->columnHeader->metricHeader->metricHeaderEntries);$i++) {
?> <td> <?php print_r($data->columnHeader->metricHeader->metricHeaderEntries[$i]->name); ?> </td> <?php
}
?><tr><?php // Header row end
// Display data
for($i = 0; $i < sizeof($data->data->rows);$i++) {
?><tr><?php // Data row start
// Dimensions
for($d = 0; $d < sizeof($data->columnHeader->dimensions);$d++) {
?> <td> <?php print_r($data->data->rows[$i]->dimensions[$d]); ?> </td> <?php
}
// Metrics
for($m = 0; $m < sizeof($data->columnHeader->metricHeader->metricHeaderEntries);$m++) {
?> <td> <?php print_r($data->data->rows[$i]->metrics[0]->values[$m]); ?> </td> <?php
}
?><tr><?php // Header row end
}
?></table></pre><?php
}
function showText($data)
{
?> <pre> <?php print_r($data); ?> </pre> <?php
}
/**
* Returns the Analytics data.
* Documentation https://developers.google.com/analyticsreporting/v4/reference/reports/batchGet
* Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
* #service Authenticated Analyticsreporting service.</param>
* #body A valid Analyticsreporting v4 body.</param>
* #return GetReportsResponseResponse</returns>
*/
function BatchGet($service, $body)
{
try
{
// Initial validation.
if ($service == null)
throw new Exception("service");
if ($body == null)
throw new Exception("body");
// Make the request.
return $service->reports->batchGet($body);
}
catch (Exception $ex)
{
throw new Exception("Request Reports.BatchGet failed.", $ex->getMessage());
}
}
?>
Update:
Remember to make sure you granted the service account assess to your Google analytics account at the account level.
Note code was ripped from my github project

Is there any way to get data from shared Google Sheet document?

I need to create a web page that has to show current prices from Google Sheets. There is a manual https://developers.google.com/api-client-library/php/auth/web-app#protectauthcode but it request authorisation.
Is there any way to import data every time when user open my php page, even if he doesn't have Google account? Or I need to create server-to-server communication and sync every time to json file or my DataBase by cron task?
I managed, here is my solution:
<?php
$apiKey="yourAPIkey";
include_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey($apiKey);
$service = new Google_Service_Sheets($client);
$spreadsheetId = 'SheetID';
$range = 'A1:B';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (count($values) == 0) {
print "No data found.\n";
} else {
print "Name, Major:\n";
foreach ($values as $row) {
printf("<p>%s, %s</p>", $row[0], $row[1]);
}
}
?>
Install library
Get Simple API access key

Google API error

I am trying to use google API to get events off calendars on an account. I am using a service account. I am receiving two errors when I attempt to manually echo the code or it will remain a blank page if I use foreach(...).
Here are the two errors:
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/users/me/calendarList/primary: (404) Not Found' in C:\wamp\www\newOLP\scripts\oAuth2\Google\Http\REST.php on line 110
( ! ) Google_Service_Exception: Error calling GET https://www.googleapis.com/calendar/v3/users/me/calendarList/primary: (404) Not Found in C:\wamp\www\newOLP\scripts\oAuth2\Google\Http\REST.php on line 110
Here is my code:
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.
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 = $jsonDecode['client_id'];
$Email_address = $jsonDecode['client_email'];
$key_file_location = 'privateKey.p12';
$client = new Google_Client();
$client->setApplicationName("CalCon");
$key = file_get_contents($key_file_location);
// separate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar.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_Calendar($client);
?>
<html><body>
<?php
$calendarList = $service->calendarList->listCalendarList();
echo $service->calendars->get('primary')->getSummary()."<br />";
echo $service->calendarList->get('primary')->getSummary();
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry;
echo "hi";
echo $calendarListEntry->getSummary()."<br>\n";
// get events
$events = $service->events->listEvents($calendarListEntry->id);
foreach ($events->getItems() as $event) {
echo "-----".$event->getSummary()."<br>";
}
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>
</body></html>

How pull web statistics using google analytics api through php client

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

PHP Google Analytics API - Simple example

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

Categories