我试图让我的php应用程序使用服务身份验证服务来调用Google的Calendar API。我对Education G Suite拥有管理员权限,并执行了以下步骤:https://developers.google.com/identity/protocols/OAuth2ServiceAccount
但是,当我尝试获取任何日历信息时,我仍然会收到以下错误:
Google_Service_Exception:{"错误":" unauthorized_client"," error_description":"客户端未经授权使用此方法检索访问令牌。&# 34; }
根据谷歌搜索,这通常意味着我没有授权域范围的权限,但我绝对有。我已尝试过其他Google apis,但结果相同。
这是我的代码。感谢您的任何想法或帮助。
destination_hash[job_signature(destination)] << destination.clone # or equivalent
答案 0 :(得分:1)
客户未经授权使用此方法检索访问令牌。
在Google开发者控制台上创建项目时,您应该创建了服务帐户凭据。然后,您将被提升为下载文件,该文件包含服务帐户的凭据。
用于连接服务帐户的代码与使用浏览器或本机客户端凭据进行连接的代码不同。
ServiceAccount.php link to code
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* Initializes a client object.
* @return A google client object.
*/
function getGoogleClient() {
return getServiceAccountClient();
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Scopes will need to be changed depending upon the API's being accessed.
* array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* @return A google client object.
*/
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([YOUR SCOPES HERE]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
您似乎使用了正确的服务帐户代码。但是,您可能已下载了错误的凭据文件,我建议您再次从Google开发人员控制台下载该文件。
答案 1 :(得分:0)
在上面的第2步中添加了不正确的范围。希望这仍然允许一些人看到正确的步骤。
答案 2 :(得分:0)
我也遇到过这个问题,但只有在使用$ client时才会遇到这个问题 - &gt; SETSUBJECT(impersonationemail); 尝试注释掉这一行,看看它给你的响应代码。