EDIT - this tutorial (albeit almost like a Google tutorial) was what ultimately worked: http://teev.io/blog/google-analytics-api-php
I am trying to follow the guide given here:
https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-php
I have completed all the steps:
- Created a project.
- Created a service account. (when requesting for JSON or P12, I chose JSON)
- I ran
composer require google/apiclient:^2.0putty and updated the composer.json file. - Placed my file
service-account-credentials.jsonthat I just uploaded to a folder/public_html - Created a file
HelloAnalytics.phpand placed it in a folder /public_html.
HelloAnalytics.php:
<?php
require_once '/home/user/vendor/autoload.php';
$analytics = initializeAnalytics();
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
printResults($results);
function initializeAnalytics()
{
$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';
$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_AnalyticsReporting($client);
return $analytics;
}
function getFirstProfileId($analytics) {
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
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) {
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
function printResults($results) {
if (count($results->getRows()) > 0) {
$profileName = $results->getProfileInfo()->getProfileName();
$rows = $results->getRows();
$sessions = $rows[0][0];
print "First view (profile) found: $profileName\n";
print "Total sessions: $sessions\n";
} else {
print "No results found.\n";
}
}
What sadly causes this error:
Fatal error: call the list of member functions ManagementAccounts () for a non-object in ...
Any tips on how to really make this work?
source
share