我正在尝试使用服务身份验证的PHP应用程序来调用Google的日历API。我对教育套房有管理访问权限,并且已经执行了以下步骤,如下所示:https://developers.google.com/inentity/protocols/oauth2serviceaccount
- 使用域范围内的权威创建了一个服务帐户,并保存了适当的凭据。
- 使用我的clientId(UI确认(
- 根据这些示例这里:https://developers.google.com/api-client-library/php/auth/service-accounts
但是,当我尝试获取任何日历信息时,我将继续收到以下错误:
google_service_exception:{" error":" unuthorized_client"," error_description":"未经授权使用此方法来检索访问令牌。"}
通过谷歌搜索,这通常意味着我没有授权范围内的权威,但我肯定有。我尝试了其他带有相同结果的Google API。
这是我的代码。感谢您的想法或帮助。
<?php require_once __DIR__ . '/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=****/client_secret.json');
$user_to_impersonate = 'user@****.com';
$user_scopes = array(
Google_Service_Calendar::CALENDAR
);
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject($user_to_impersonate);
$client->setScopes($user_scopes);
$client->setAccessType('offline');
$calendar = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $calendar->events->listEvents($calendarId, $optParams);
...
?>
客户未经授权使用此方法检索访问令牌。
在Google Developer Console上创建项目时,您应该已经创建了服务帐户凭据。然后,您将晋升以下载文件此文件包含服务帐户的凭据。
您用于连接到服务帐户的代码与使用浏览器或本机客户凭证连接的代码使用不同。
serviceaccount.php 链接到代码
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 Developer Console下载该文件。
在上面的步骤2中添加了错误的示波器。希望这仍然使某些人能够看到正确的步骤。
我也遇到了这个问题,但仅在使用$ client-> setSubject(ImpersonationEmail(时;尝试评论这一行,看看它给您的响应代码。