如何使用Google网站管理员工具API访问用户数据


How to access user data with Google Webmaster Tools API

我刚开始使用谷歌的api库,我在访问用户数据时遇到了一些麻烦。为了进行实验,我使用了该领域前面问题中的代码。我的代码执行google搜索控制台api的请求,但它返回一个空数组。我从管理控制台(https://developers.google.com/identity/protocols/OAuth2ServiceAccount)授权了服务帐户,所以我不知道为什么它不返回任何东西。

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