2
votes

I am trying to make a call to get data from Google Analytics.

<?php

require_once 'lib/apiClient.php';
require_once 'lib/contrib/apiAnalyticsService.php';
session_start();

$client = new apiClient();

$service = new apiAnalyticsService($client);

if (isset($_GET['logout'])) {
    unset($_SESSION['token']);
}

if (isset($_GET['code'])) {
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
    $accounts = $service->management_accounts->listManagementAccounts();
    print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";

    try {
        $data = $service->data_ga->get('ga:29214712', '2012-01-01', '2012-01-15',
            'ga:visits', array('dimensions' => 'ga:source,ga:keyword', 'sort' =>
            '-ga:visits,ga:source', 'filters' => 'ga:medium==organic', 'max-results' => '25'));
    }
    catch (apiServiceException $e) {
        echo $e->getCode();
        print_r($data);
    }

    $_SESSION['token'] = $client->getAccessToken();
} else {
    $authUrl = $client->createAuthUrl();
    print "<a class='login' href='$authUrl'>Connect Me!</a>";
}

After Wrapping the code in the TRY Catch Block i am getting the following error

403

Error calling GET https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A29214712&start-date=2012-01-01&end-date=2012-01-15&metrics=ga%3Avisits: (403) Forbidden

( ! ) Notice: Undefined variable: data in C:\wamp\www\gitgrow\index.php on line 43

Note: I have granted the permission and have forced the Profile ID to test it.

1

1 Answers

2
votes

The 403 error you're getting means the authorized user doesn't have access to the ga:29214712 reporting profile that is defined in your query.

Take a look at the HelloAnalyticsAPI.php sample in the examples/analytics/demo directory, and make sure you can connect to the API: http://code.google.com/p/google-api-php-client/source/browse/#svn%2Ftrunk%2Fexamples%2Fanalytics%2Fdemo

Also, take a look at the Google Analytics developer guide. It will describe how you can obtain the correct profile IDs: https://developers.google.com/analytics/devguides/reporting/core/v3/#user_reports