如何在Google Workspace插件中结合Calendar API使用UrlFetchApp.fetchAll
解决方法
你不需要额外申请OAuth授权,也不需要单独获取高级Calendar服务内部调用的AccessToken,直接调用Apps Script内置的ScriptApp.getOAuthToken()方法即可拿到当前上下文的授权令牌。该令牌和高级Calendar服务内部使用的AccessToken完全一致,已经包含了脚本清单appsscript.json中声明的所有Calendar相关权限,不会要求用户走二次授权流程。
实现步骤
- 先确认脚本清单
appsscript.json中已配置对应Calendar权限,patch事件操作至少需要https://www.googleapis.com/auth/calendar.events或更宽泛的https://www.googleapis.com/auth/calendar权限,启用高级Calendar服务时一般会自动配置该权限,可提前核对避免权限错误。 - 构造批量Patch请求,示例代码如下:
// 获取当前授权的AccessToken const accessToken = ScriptApp.getOAuthToken(); // 批量构造所有事件更新请求 const batchRequests = eventsToUpdate.map(_e => { return { url: `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(_e.calendar.calendarId)}/events/${encodeURIComponent(_e.calendar.id)}`, method: 'PATCH', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, payload: JSON.stringify({extendedProperties: pp}), muteHttpExceptions: true } });
- 调用
UrlFetchApp.fetchAll批量执行请求:
const batchResponses = UrlFetchApp.fetchAll(batchRequests); // 后续遍历返回结果处理单个请求的成功/失败逻辑即可
注意事项
ScriptApp.getOAuthToken()返回的令牌默认有效期为数分钟,足够完成单次批量请求,不需要额外处理过期逻辑UrlFetchApp.fetchAll单次最多支持100个请求,超过上限的话可把请求列表拆分多批依次调用即可
内容的提问来源于stack exchange,提问作者PNC
相关产品推荐
相关产品推荐

