客户端无权使用此方法检索访问令牌 - Google 日历 php api

Client is unauthorized to retrieve access tokens using this method - Google calendar php api

我看了很多文章:

https://developers.google.com/calendar/quickstart/php

和其他人.. 我想使用服务帐户,我授予了我的日历权限,我已经下载了 json 密钥。如果我使用 Google 中的代码,我得到:

missing the required redirect URI

如果我使用代码:

$client = new Google\Client();
$client->setApplicationName('Gcal');
$client->setAuthConfig($key_file_location);
$client->setScopes([Google_Service_Calendar::CALENDAR]);
$client->setSubject($calendarId);
$client->setAccessType('offline');
$service = new Google_Service_Calendar($client); 

我有:

Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested

我没有 admin.google 访问权限,我只需要访问我自己的日历并删除旧事件。 请让我知道我缺少什么。

谢谢

我尝试重新创建您的案例,我想我知道出了什么问题。

如果您选择“Web 服务器”,则在创建客户端配置时:

然后你可以使用示例中的php,运行脚本,从获取变量中获取访问令牌并将其返回给控制台:

但是,如果您正在创建客户端配置并使用“Web 浏览器”,那么您的脚本会要求重定向 URI,您可以将其添加到示例 php:

...
$client = new Google_Client();
$client->setRedirectUri('https://yourdomain.com/somedir');
$client->setApplicationName('Google Calendar API PHP Quickstart');
...

然而你必须去 Google Cloud Platform:

并授权您的域和重定向 URI。当您现在 运行 您的脚本时,您将在重定向站点上获得访问令牌。

如果您从 Google 工作区帐户设置了 domain wide delegation,则仅使用 Google 日历 api 的服务帐户。

您可以通过创建一个普通的网络客户端并授权您的代码一次并存储刷新令牌来解决这个问题。以后您可以使用刷新令牌访问日历。

您可能应该监控此解决方案,因为在极少数情况下刷新通常会过期。因此,如果它确实无法请求新的访问令牌,您将不得不重新授权代码并获取新的刷新令牌。

function buildClient(){
    
    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());    // load the stored refresh token.
    return $client;
}

然后在调用 api 之前确保检查您不需要新的访问令牌。

if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());