【问题标题】:access user calendar with service account使用服务帐户访问用户日历
【发布时间】:2014-11-07 13:51:30
【问题描述】:

我的 Intranet 上有一个 php 应用程序,它需要在我的用户日历中添加事件。

我遵循以下指示 https://developers.google.com/+/domains/authentication/delegation

我设置了 google-api-php 客户端并使用示例 service-accounts.php 作为我的起点。

$client_id = 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr.apps.googleusercontent.com';
$service_account_name = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy@developer.gserviceaccount.com';
$key_file_location = 'file.p12';

$client = new Google_Client();
$client->setApplicationName("egw - intranet");
$service = new Google_Service_Calendar($client);
//authenticate
if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/calendar'),
    $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();

$event = new Google_Service_Calendar_Event();
$event->setSummary('API V3 TEST');
$event->setLocation('rrrrrrrrrrrrrrrrrrrrrrrrr');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2014-11-03T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2014-11-04T10:25:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('email@domain.com');

$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $service->events- >insert('email2@domain.com', $event);

echo $createdEvent->getId();

我收到 404 not found 错误。 如果我手动与服务帐户共享我用于测试的日历,它可以工作。但我希望我的程序也能正常工作,而无需手动共享所有用户的每个日历。谁能告诉我我错过了什么?

亲切的问候,

【问题讨论】:

标签: google-calendar-api google-api-php-client


【解决方案1】:

您不能将活动添加到尚未专门与您的 Google 项目共享的日历中。您必须与服务帐户共享每个日历,或者必须将 OAuth2 与 Web 应用程序凭据一起使用,以便每个用户都可以授予您访问权限。

【讨论】:

  • 这不正是应用域中存在“服务帐户”的原因吗?
  • 服务帐户只是允许您的应用向 Google 识别自己。该帐户的所有者仍然必须授予该应用访问其日历的权限。从您要修改的日历中,转至设置 -> 日历 -> 共享此日历。输入您的服务帐户中的电子邮件地址(服务帐户名称)并授予其“更改事件”权限。请务必单击页面底部的保存按钮。如果您的代码是正确的,并且一目了然,它将添加事件。
  • 如果域管理员允许域级别访问日历,那不应该也“自动”授予服务帐户访问权限吗?有关此信息的 API 文档远非完整且几乎没有用处。
  • 理论上,您可以使用以下说明更新整个域用户列表:support.google.com/a/answer/60765?hl=en 使用目录 API 而不是供应 API 来获取用户列表。
【解决方案2】:

当我开始这个时,当前的客户端 google-php-api-client 是 1.1.0-beta。几周后,我们现在是 1.1.2。升级到这个版本解决了我的问题。 添加服务帐户使应用程序可以通过 Google 识别自己。 如果您像我一样将范围添加到谷歌管理控制台,则服务帐户可以访问域中每个用户的范围指定的所有数据。 谢谢大家的回复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    相关资源
    最近更新 更多