3
votes

I am trying to retrieve the Google Analytics Management Profiles using the latest PHP client API (https://github.com/google/google-api-php-client).

I have the following code snippet:

// we've got the token, so set it
$google_client->setAccessToken($_SESSION['access_code']);

if ($google_client->getAccessToken()) {
    $profiles = $google_analytics_service->management_profiles->listManagementProfiles("~all", "~all");
    print "<h1>Profiles</h1><pre>" . print_r($profiles, true) . "</pre>";
}

/* $url = 'https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles'; */
/* // json decode as array */
/* $analytics_auth = json_decode($_SESSION['access_code'], true); */

/* $ch = curl_init($url . '?access_token=' . $analytics_auth['access_token']); */
/* curl_exec($ch); */
/* curl_close($ch); */

The error message I get with the above is:

Error calling GET https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles?key=AIza[SNIP]: (403) Access Not Configured

Note: However I decided to run the same with cURL and it returns a JSON array with the profiles (the commented code). Is this a bug, or me? What I do notice is that my access_token starts with "ya29".

2

2 Answers

6
votes

I think you are missing a step:

   <?php    
    require_once 'Google/Client.php';
    require_once 'Google/Service/Analytics.php';  
    session_start(); 
    $client = new Google_Client();
    $client->setApplicationName("Client_Library_Examples");
    $client->setDeveloperKey("{developerkey}");  
    $client->setClientId('{clientID}.apps.googleusercontent.com');
    $client->setClientSecret('{Client secret}');
    $client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
    $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));


    //For loging out.
    if ($_GET['logout'] == "1") {
    unset($_SESSION['token']);
       }


    // Step 2: The user accepted your access now you need to exchange it.
    if (isset($_GET['code'])) {

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

    // Step 1:  The user has not authenticated we give them a link to login    
    if (!$client->getAccessToken() && !isset($_SESSION['token'])) {

        $authUrl = $client->createAuthUrl();
        print "<a class='login' href='$authUrl'>Connect Me!</a>";
        }    


    // Step 3: We have access we can now create our service
    if (isset($_SESSION['token'])) {
        print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
        $client->setAccessToken($_SESSION['token']);
        $service = new Google_Service_Analytics($client);    

        // request user accounts
        $accounts = $service->management_accountSummaries->listManagementAccountSummaries();

       foreach ($accounts->getItems() as $item) {
        echo "Account: ",$item['name'], "  " , $item['id'], "<br /> \n";

        foreach($item->getWebProperties() as $wp) {
            echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WebProperty: ' ,$wp['name'], "  " , $wp['id'], "<br /> \n";    

            $views = $wp->getProfiles();
            if (!is_null($views)) {
                foreach($wp->getProfiles() as $view) {
                //  echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;View: ' ,$view['name'], "  " , $view['id'], "<br /> \n";    
                }
            }
        }

    } // closes account summaries

    }

 print "<br><br><br>"; // fix syntax
 print "Access from google: " . $_SESSION['token']; 


?>

Due to issue with the session_start and headers its a bit out of order. I added some comments to help you understand what its doing. Its a simple script but you can test it here Dummy Example for Hal9k

0
votes

The 403 problem was because the correct IP address wasn't set for the server applications key. This can be set in the Google Developers' Console. It's odd, however, that using cURL bypassed this.

Public API access Use of this key does not require any user action or consent, does not grant access to any account information, and is not used for authorization.

Key for server applications API key: AI[snip] IPs: 91.[snip] 109.[snip] Make sure correct IP address is set here