使用 PHP API oauth2.0 的 Google 日历服务帐户 - 如何访问未共享的日历


Google Calendar Service Account with PHP API oauth2.0 - How to access calendars that are not shared

我在使用 Google 提供的 PHP 库读取日历事件时遇到问题。我想阅读的日历不是公开共享的,但我想在我的服务器应用程序上阅读它们。

保存日历的帐户与我的帐户是分开的(我将其称为API帐户),尽管日历是与我共享的。

根据谷歌上未公开共享的日历详细信息:

任何人都可以:什么也看不见

您可以:仅查看忙/闲(隐藏详细信息)。

API 帐户和我的帐户都有一个带有 P12 密钥的 OAuth2.0 服务帐户。

我遵循了以下指南:http://www.daimto.com/google_service_account_php/它帮助我弄清楚了身份验证过程。我已经设法阅读了公开共享的日历,这两个帐户都没有任何问题。这是我的代码:

// Start the Google client
$client = new Google_Client();
$client->setClientId({{client_id from google}});
$client->setApplicationName("Project Name");
$client->setClientSecret({{client_secret from google}});
$key = file_get_contents({{key_file_location on my server}});
$cred = new Google_Auth_AssertionCredentials(
        $Email_address,
        // Scopes that we will be using
        array(
           "https://www.googleapis.com/auth/calendar"
        ),
        $key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
}
// Use Google Calendar API plugin
$service = new Google_Service_Calendar($client);
$optParams = array(
    'singleEvents'=> true,
    'timeMin'=>date(DateTime::ATOM),
    'timeMax' => date(DateTime::ATOM, time()+(3 * 24 * 60 * 60))
);
$results = $service->events->listEvents(
    '{{Calendar ID from Google Calendar Settings}}',
    $optParams
);

但是,当尝试将代码用于未公开共享的日历时,我在任一帐户上都收到以下错误:

致命错误:未捕获的异常"Google_Service_Exception" 消息"调用 GET 时出错 https://www.googleapis.com/calendar/v3/calendars{{日历ID}}:(404) 未找到...

当我尝试var_dump($client->getAuth())时,我注意到有一个值可能表明身份验证不起作用:["authenticated":"Google_Client":private]=> bool(false) 。这发生在两个帐户以及公开共享和公开未共享的日历上。

我可以将 Google API 资源管理器与我的帐户一起使用,以便在未公开共享的日历上显示 JSON 数据。Google PHP API 或 Google 帐户设置是否缺少一些允许我做我想做的事情?

谢谢你的时间。

如果您想使用服务帐号访问私人日历,则需要执行权限委派(如果您拥有包含这些日历的网域(https://developers.google.com/drive/web/delegation 将其描述为云端硬盘,但它适用于日历),或者您需要使用服务帐号的电子邮件地址共享私人日历。

感谢您的建议。

事实证明,问题是API帐户的负责人没有与开发人员帐户的服务器帐户电子邮件共享日历。

由于我无法访问API帐户设置,并且来自Google日历API的错误不是很具有描述性,因此需要一段时间才能弄清楚。