【问题标题】:Google Client for Calendar service responding with a 404Google 日历服务客户端以 404 响应
【发布时间】:2021-02-03 02:57:10
【问题描述】:

目标

我正在尝试将 Google Calendar API 集成到我的公司网站,以便根据某些事件自动创建事件。

事件将被添加到公司日历并显示给用户,所以我不需要用户进行身份验证,我不会在他们自己的日历上工作。

我做了什么

  • 按照 Google OAuth 2.0 for Server to Server Applications 文档中的说明创建了 OAuth 2.0 服务帐户

  • 创建、下载并添加凭据文件到我的项目,并将其路径添加到环境变量GOOGLE_APPLICATION_CREDENTIALS

  • 关注docs example to authorize my requests using the service accountdocs to create events
    这是我的源代码的简短版本:

    $client = new Google_Client();
    $client->setApplicationName("XXX");
    $client->addScope(Google_Service_Calendar::CALENDAR); // "https://www.googleapis.com/auth/calendar"
    $client->useApplicationDefaultCredentials();
    
    $service = new Google_Service_Calendar($client);
    
    $event = new Google_Service_Calendar_Event(/* array with event data */);
    $calendarId = /* calendar id taken from calendar Settings and Sharing on calendar.google.com*/;
    
    $event      = $service->events->insert($calendarId, $event);
    

    与示例(第 43:52 行)相比,我没有手动检查凭据文件,而是直接查找 useApplicationDefaultCredentials()

错误

我的代码记录的错误是

[2020-10-19 14:29:19] local.ERROR: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "Not Found"
   }
  ],
  "code": 404,
  "message": "Not Found"
 }
}
 {"userId":2,"exception":"[object] (Google_Service_Exception(code: 404): {
 \"error\": {
  \"errors\": [
   {
    \"domain\": \"global\",
    \"reason\": \"notFound\",
    \"message\": \"Not Found\"
   }
  ],
  \"code\": 404,
  \"message\": \"Not Found\"
 }
}
 at /var/www/vendor/google/apiclient/src/Google/Http/REST.php:123)
[stacktrace]

看起来它调用了错误的 api 端点,因为 404page not found 响应。

日历 ID
为了清楚起见,这是我获取日历 ID 的地方

【问题讨论】:

    标签: php http-status-code-404 google-calendar-api google-client


    【解决方案1】:

    据我所知,服务帐户没有自己的日历,因此需要授予他们对特定组织的访问权限才能创建/读取事件。

    如果这是针对内部应用程序(并且您是组织的管理员),您可以按照Delegating Authority 下的步骤授予您的服务帐户访问组织日历的权限:

    然后,G Suite 域的超级管理员必须完成以下步骤:

    1. 从您的 G Suite 域的 Admin console,转到主菜单菜单 > 安全 > API 控制。
    2. 在“域范围委派”窗格中,选择“管理域范围委派”。 点击新增。
    3. 在“客户 ID”字段中,输入服务帐户的客户 ID。您可以在 Service accounts page 中找到您的服务帐号的客户端 ID。
    4. 在 OAuth 范围(逗号分隔)字段中,输入应授予您的应用程序访问权限的范围列表。例如,如果您的应用程序需要在域范围内完全访问 Google Drive API 和 Google Calendar API,请输入:https://www.googleapis.com/auth/drive, https://www.googleapis.com/auth/calendar
    5. 点击授权。

    您还需要按照步骤模拟Preparing to make an authorized API call 下的特定用户,以便为有权访问相关日历的用户检索令牌。

    如果这是针对打算由多个组织安装的应用程序,您应该考虑使用托管 OAuth 服务,例如 Xkit我工作的地方)。特别是 Xkit 有一个 Google Calendar Service Account connector,它从您作为开发人员那里抽象出所有这些步骤(包括 IT 管理员的分步指南),以便在一次 API 调用中为您提供工作访问令牌。

    作为旁注,您引用的服务帐户示例使用来自 Books API 的公共数据,因此它不需要用户授权,只需将自己标识为应用程序。

    【讨论】:

    • 是的,我发现了here,所以我回答了我自己的问题,但方法不对,所以我自己的答案被否决并取消了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    相关资源
    最近更新 更多