0
votes

I have the following error when try to use Google SearchAnalytics API from PHP code:

PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/webmasters/v3/sites/{MY SITE GOES HERE}/searchAnalytics/query: (403) Insufficient Permission' in /Users/Ihar_Cheliadzinski/Workspace/DSS/google-login/google-api-client/src/Google/Http/REST.php:110

I have tested this API in API Explorer: https://developers.google.com/apis-explorer/?hl=en_US#p/webmasters/v3/webmasters.searchanalytics.query and it works fine.

I think something wrong with authorization in PHP code, but this code works good with Gmail API.

Could you help me on this please?

This is my PHP file:

<?php
require 'google-api-client/src/Google/autoload.php';

define('APPLICATION_NAME', 'My Project');
define('CREDENTIALS_PATH', '~/.credentials/gmail.json');
define('CLIENT_SECRET_PATH', 'client_secrets.json');
define('SCOPES', implode(' ', array(
    Google_Service_Webmasters::WEBMASTERS_READONLY,
    Google_Service_Webmasters_SearchAnalyticsQueryRequest::NULL_VALUE,
    Google_Service_Webmasters_SearchAnalyticsQueryResponse::NULL_VALUE
)
));

/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient() {
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');

    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->authenticate($authCode);

        // Store the credentials to disk.
        if(!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
     }
     $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
    }
    return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
    }
    return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();

$service = new Google_Service_Gmail($client);

$webmastersService = new Google_Service_Webmasters($client);
$searchanalytics = $webmastersService->searchanalytics;
$request = new Google_Service_Webmasters_SearchAnalyticsQueryRequest;
$request->setStartDate("2015-10-01");
$request->setEndDate("2015-10-01");
$qsearch = $searchanalytics->query('{MY SITE GOES HERE}', $request);
$rows = $qsearch->getRows();
echo json_encode($rows);
1
Insufficient Permission you don't have permission to do that call!?Kanti
but this call works good using API Explorer with the same POST link here: developers.google.com/apis-explorer/?hl=en_US#p/webmasters/v3/…LiveReload

1 Answers

0
votes
  1. Make sure you load file with permissions for Search Analytics, not only gmail.

  2. query requires following scopes:

https://www.googleapis.com/auth/webmasters.readonly https://www.googleapis.com/auth/webmasters

I'm not sure if

Google_Service_Webmasters_SearchAnalyticsQueryRequest::NULL_VALUE, Google_Service_Webmasters_SearchAnalyticsQueryResponse::NULL_VALUE

are required.