我刚刚开始使用Google的api库,但是在访问用户数据时遇到了一些麻烦。为了进行实验,我使用了该领域中来自previos问题的代码。我的代码对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 = "[email protected]";
$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; //[email protected]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句