You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Google Batch API返回404,Apps Script批量授权失败求助

解决Google Apps Script批量权限请求404错误的方案

核心问题分析

你遇到的404错误主要来自两个关键疏漏:

  • Google Batch API的端点已更新,不再支持通用的https://www.googleapis.com/batch,必须指定具体服务的批量端点
  • 请求格式的收尾部分存在不规范,同时可能缺少必要的权限配置

具体修复步骤

1. 修正Batch API端点

Google Drive API的批量请求必须使用服务专属端点,替换为:
https://www.googleapis.com/batch/drive/v3
旧的通用batch端点已逐步废弃,直接调用会返回404错误。

2. 确认OAuth权限范围

脚本需要获取Drive API的权限才能修改文件共享设置:

  • 在脚本编辑器中,点击「扩展程序」→「Apps Script API」,确保API已启用
  • 首次运行脚本时,授权弹窗会请求Drive相关权限,必须授予修改文件权限的权限(对应范围https://www.googleapis.com/auth/drive,若仅操作脚本自身创建的文件,可使用更窄的https://www.googleapis.com/auth/drive.file)

3. 修正Batch请求格式

原代码中批量请求的收尾部分未正确闭合boundary,需要在payload末尾追加--标记,否则会被视为无效请求。

修正后的完整代码

var userEmailsArray = ["email@mail.com"]; // 替换为实际目标邮箱数组
var fileId = "File-ID"; // 替换为实际文件ID
function changePermissionBatch(role = "reader", type = "user") {
    const resources = userEmailsArray.map(e => ({role: role, type: type, emailAddress: e}));
    const boundary = "xxxxxxxxxx";
    // 构建payload并确保最后正确闭合boundary
    const payload = resources.reduce((s, e, i) => {
      s += "Content-Type: application/http\r\n" +
        "Content-ID: " + i + "\r\n\r\n" +
        "POST https://www.googleapis.com/drive/v3/files/" + fileId + "/permissions?sendNotificationEmails=false\r\n" +
        "Content-Type: application/json; charset=utf-8\r\n\r\n" +
        JSON.stringify(e) + "\r\n" +
        "--" + boundary + "\r\n";
      return s;
    }, "--" + boundary + "\r\n") + "--"; // 追加结尾的闭合标记

    const params = {
      method: "post",
      contentType: "multipart/mixed; boundary=" + boundary,
      payload: payload,
      headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions: true // 启用后可获取完整错误响应,便于调试
    };
    const res = UrlFetchApp.fetch("https://www.googleapis.com/batch/drive/v3", params);
    console.log(res.getContentText())
  }

额外调试建议

  • 启用muteHttpExceptions: true后,即使请求失败也能获取完整的响应内容,可帮助定位具体错误(比如文件不存在、权限不足等)
  • 验证fileId有效性:在浏览器中访问https://www.googleapis.com/drive/v3/files/{fileId}?fields=id,name,确认文件存在且当前用户有权限访问

内容的提问来源于stack exchange,提问作者AAng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 19:57:33