如何在 google 工作区插件中将 UrlFetchApp.fetchAll 与日历 API 一起使用

How to use UrlFetchApp.fetchAll with Calendar API in google workspace addon

我们的 Google 工作区插件将日历事件从 Google 日历同步到外部数据库。

作为此过程的一部分,我们使用补丁命令更新多个日历事件

Calendar.Events.patch({extendedProperties:pp},_e.calendar.calendarId,_e.calendar.id);

我们遇到的问题是我们需要在有限的时间内多次执行此操作(应用程序脚本会超时)

我们可以使用 UrlFetchApp.fetchAll 函数来实现这一点,但不幸的是,要调用它,我们需要直接调用日历 api。尽管这很容易完成 - 我们没有 AccessToken,因为它不可用并且由 API.

处理

有谁知道如何获取日历 API 正在使用的 accessToken(无需让用户通过单独的 OAuth 批准流程),以便我们可以利用它来调用 UrlFetchApp.fetchAll

只要您的附加组件中有正确的日历范围,我认为您可以将 ScriptApp.getOauthToken() 作为 UrlFetchApp 请求中的标记传递:

getOAuthToken()

Gets the OAuth 2.0 access token for the effective user. If the script's OAuth scopes are sufficient to authorize another Google API that normally requires its own OAuth flow (like Google Picker), scripts can bypass the second authorization prompt by passing this token instead. The token expires after a time (a few minutes at minimum); scripts should handle authorization failures and call this method to obtain a fresh token when needed.

The token returned by this method only includes scopes that the script currently needs. Scopes that were previously authorized but are no longer used by the script are not included in the returned token. If additional OAuth scopes are needed beyond what the script itself requires, they can be specified in the script's manifest file.

Return

String — A string representation of the OAuth 2.0 token.

示例请求:

function patchCalendarEvents() {
  const calendarId = "calendarId"
  const eventIds = [] // your event ID list
  const baseUrl = `https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events/{{eventId}}`
  const requests = []

  eventIds.forEach(function (event) {
    requests.push({
      "url": baseUrl.replace("{{eventId}}", event),
      "method": "PATCH",
      "headers": {
        "Authorization": "Bearer " + ScriptApp.getOAuthToken()
      },
      "payload": '{"extendedProperties": {"shared": {"testKey": "Test Value"}}}',
      "contentType": "application/json",
    })
  })
  console.log(requests)

  const responses = UrlFetchApp.fetchAll(requests)

  responses.forEach(function(response) {
    console.log(response.getContentText())
  })
  
}