1

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!

Community
  • 1
  • 1
TheLeonKing
  • 3,501
  • 7
  • 32
  • 44
  • •Added the e-mail address of the service account to Google Analytics. <-- At the account level? this might help http://www.daimto.com/google_service_account_php/ – Linda Lawton - DaImTo Nov 14 '14 at 10:59
  • @DaImTo Yeah, at the account level. Strangely enough, your code works for me ( thanks for that! :-) ), but the code in my original post doesn't. – TheLeonKing Nov 14 '14 at 11:13
  • yeah the original one seams weird to me , I wonder if its using the older version of the client lib. – Linda Lawton - DaImTo Nov 14 '14 at 11:16
  • I think the best place to start is: https://github.com/google/google-api-php-client. As @DalmTo has mentioned it could be the library version. – carlodurso Nov 14 '14 at 23:08
  • @carlodurso Thanks, but that's the one I used. Maybe I'm referencing to the wrong files? – TheLeonKing Nov 15 '14 at 17:24

0 Answers0