I'm trying to display some basic Google Analytics information about my website using the Google Analytics Reporting API and Oauth 2.0. I've been trying to make it work for hours, but in vain.
I've copied and edited the code from this topic. Everything should work correctly, but somehow when I view the page in my browser, I only see a blank page.
I have:
- Created a Service Account in the Google API Console.
- Enabled the Google Analytics API in the Google API Console.
- Added the e-mail address of the service account to Google Analytics.
The code ('XXXX' means I've filtered out personal information):
<?php
require_once 'google-api/src/Google/Client.php';
require_once 'google-api/src/Google/Service/Analytics.php';
$keyfile = 'XXXX.p12';
// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('Application Name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'XXXX@developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('XXXX.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'XXXX';
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
?>
I've struggled with this for a very long time, any help would be greatly appreciated!