0

Our Google Workspace Addon synchronises calendar events from Google Calendar to an external database.

As part of this process we update multiple Calendar Events using the patch command

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

The problem we have is that we need to perform this operation multiple times within a limited amount of time (app script will time-out)

We could achieve this with the UrlFetchApp.fetchAll function but unfortunately to call this we would need to call the calendar api directly. Although this is easily done - we do not have the AccessToken as this is not available and is handled by the API.

Does anybody know how to get the accessToken (without pushing the user through a separate OAuth approval process) that is being used by the Calendar API so that we can utilise it to call UrlFetchApp.fetchAll

4

1 回答 1

1

只要您的插件中有正确的日历范围,我认为您可以在请求ScriptApp.getOauthToken()中作为令牌传递:UrlFetchApp

getOAuthToken()

获取有效用户的 OAuth 2.0访问令牌。如果脚本的 OAuth 范围足以授权另一个通常需要其自己的 OAuth 流的 Google API(如Google Picker),则脚本可以通过传递此令牌来绕过第二个授权提示。令牌在一段时间后过期(至少几分钟);脚本应处理授权失败并在需要时调用此方法以获取新令牌。

此方法返回的令牌仅包含脚本当前需要的范围。先前已授权但脚本不再使用的范围不包含在返回的令牌中。如果需要超出脚本本身所需的其他 OAuth 范围,则可以在脚本的清单文件中指定它们。

返回

String— OAuth 2.0 令牌的字符串表示形式。

示例请求:

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())
  })
  
}
于 2021-12-09T16:09:38.303 回答