0

я следующее сообщение об ошибке при попытке использовать Google SearchAnalytics API из PHP код:
Google PHP Client API: Недостаточно разрешений (searchanalytics)

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

Я проверил этот API в API Explorer: https://developers.google.com/apis-explorer/?hl=en_US#p/webmasters/v3/webmasters.searchanalytics.query и это работает хорошо.

Я думаю, что что-то не так с авторизацией в PHP-коде, но этот код хорошо работает с API Gmail.

Не могли бы вы мне помочь?

Это мой PHP-файл:

<?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); 
+0

'Недостаточно разрешения 'у вас нет разрешения на выполнение этого звонка !? – Kanti

+0

, но этот вызов работает хорошо, используя API-интерфейс API с той же ссылкой POST: https://developers.google.com/apis-explorer/?hl=ru_RU/pdf/webmasters/v3/webmasters.searchanalytics.query – LiveReload

ответ

0
  1. Убедитесь, что вы загрузите файл с правами доступа для поиска Analytics, не только Gmail.

  2. запрос требует следующих областей:

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

Я не уверен, если

Google_Service_Webmasters_SearchAnalyticsQueryRequest :: NULL_VALUE, Google_Service_Webmasters_SearchAnalyticsQueryResponse :: NULL_VALUE

.

Смежные вопросы