如何使用 Google 网站站长工具 API 访问用户数据

How to access user data with Google Webmaster Tools API

我刚开始使用 google 中的 api 库,但在访问用户数据时遇到了一些问题。为了进行实验,我使用了该领域中 previos 问题的代码。 我的代码为 google 搜索控制台 api 执行请愿书,但它 return 是一个空数组。我从管理控制台 (https://developers.google.com/identity/protocols/OAuth2ServiceAccount) 对服务帐户进行了自动授权,所以我不知道为什么 return 什么都没有。

set_include_path(get_include_path() . PATH_SEPARATOR . '$path/google-api-php-client-master/src');
require_once realpath('$path/google-api-php-client-master/src/Google/autoload.php');

$client_id = "my-client-id"; 
$service_account_name = "my-service-account-name@developer.gserviceaccount.com"; 
$key_file_location = "privatekey.p12";

$client = new Google_Client();
$client->setApplicationName("WMtools_application");
$service = new Google_Service_Webmasters($client);

if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/webmasters.readonly'),
    $key
);
try{
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
  }
    $_SESSION['service_token'] = $client->getAccessToken();
}catch(Exception $e){
    echo "Exception captured",  $e->getMessage(), "\n";
}
try{
    $results = $service->sites->listSites();

    $siteList = $results->siteEntry;

    var_dump($siteList);
}catch(Exception $e2){
    echo "No results",  $e2->getMessage(), "\n";
}

我解决了这个问题。案例是我已将域范围的权限委托给我的服务帐户,并且我没有在我向 API 的请愿书中包含我想从中访问数据的用户电子邮件。要解决它只需要这样将它添加到 google_Auth_AssertionCredentials:

$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/webmasters.readonly'),
    $key
);
$cred->sub = $service_account_user_email; //example@google.com