我'm attempting to have my php application call Google'的Calendar API使用服务进行身份验证 . 我对Education G Suite拥有管理员权限,并执行了以下步骤:https://developers.google.com/identity/protocols/OAuth2ServiceAccount
-
创建了具有域范围权限的服务帐户,并保存了正确的凭据 .
-
使用我的ClientID(由UI确认)将日历(读写)https://www.googleapis.com/auth/calendar范围添加到"Managed API Client Access"下的管理员帐户
-
根据以下示例,对php API客户端进行了正确调用,尝试模拟管理员和其他用户帐户:https://developers.google.com/api-client-library/php/auth/service-accounts
但是,当我尝试获取任何日历信息时,我继续收到以下错误:
Google_Service_Exception:{“error”:“unauthorized_client”,“error_description”:“客户端未经授权使用此方法检索访问令牌 . ” }
根据谷歌搜索,这通常意味着我没有委派域范围的权限,但我绝对有 . 我尝试过其他Google apis也有同样的结果 .
这是我的代码 . 感谢您的任何想法或帮助 .
<?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);
...
?>
3 回答
在上面的步骤2中添加了不正确的范围 . 希望这仍然允许一些人看到正确的步骤 .
在Google开发者控制台上创建项目时,您应该已创建服务帐户凭据 . 然后,您将被提升为下载文件,该文件包含服务帐户的凭据 .
用于连接服务帐户的代码与使用浏览器或本机客户端凭据进行连接的代码不同 .
ServiceAccount.php link to code
您似乎使用了正确的服务帐户代码 . 但是,您可能已下载了错误的凭据文件,我建议您再次从Google开发人员控制台下载该文件 .
我也遇到过这个问题,但只有在使用$ client - > setSubject(impersonationemail)时才会遇到这个问题 . 尝试注释掉这一行,看看它给你的响应代码 .