403 通过 Apps 脚本访问以编程方式创建的工作表项目端点

403 accessing programatically created sheets project endpoint through Apps Script

使用代码创建了一个空白电子表格并获取了它的 ID。一旦资源的 Id 可用,我想以编程方式将自定义脚本附加到它。

  [...]
  var newSpreadsheet = SpreadsheetApp.create("Опис "+dateFormated);
  
  Logger.log(newSpreadsheet.getId());

  var url = 'https://script.googleapis.com/v1/projects/'+newSpreadsheet.getId();
  var token = ScriptApp.getOAuthToken();
  var response = UrlFetchApp.fetch(url, {
    headers: {
      Authorization: 'Bearer ' + token
    },
    muteHttpExceptions: true
  });

请求导致错误(无论我为项目调用哪个端点) 错误消息中提供的 URL 没有帮助,因为它不是我管理的项目。这样做会导致

You do not have sufficient permissions to view this page

You are missing at least one of the following required permissions:

Project

resourcemanager.projects.get

serviceusage.services.get

 "error": {
    "code": 403,
    "message": "Apps Script API has not been used in project 85798724816 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/script.googleapis.com/overview?project=85798724816 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
    "status": "PERMISSION_DENIED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developers console API activation",
            "url": "https://console.developers.google.com/apis/api/script.googleapis.com/overview?project=85798724816"
          }
        ]
      }
    ]
  }

编辑: puffin 和 TheMaster 的回答都解决了问题。

TheMaster的回答是我想做的更具体

我的问题也有问题。我试图在创建电子表格之前获取电子表格的项目。所以正确的第一个请求是“POST”到“https://script.googleapis.com/v1/projects”

解决步骤:

  1. 从“默认”Google 云项目切换到“标准”云项目(查看 TheMaster 的 link)
  2. 在云控制台中为项目创建一个 API 密钥
  var url = 'https://script.googleapis.com/v1/projects?key=[YOUR_KEY_HERE]';
  var token = ScriptApp.getOAuthToken();
  var data = {
    "parentId": "16eL4PIVFO5Zdd7r-8HhQF_4OZS7G7TbTX-pg",
    "title": "autoProject"
  };
  var response = UrlFetchApp.fetch(url, {
    headers: {
      Authorization: 'Bearer ' + token
    },
    method: 'POST',
    contentType: "application/json",
    muteHttpExceptions: true,
    payload: JSON.stringify(data),
  });

这就是您从脚本本身

向脚本API执行成功请求的方式

首先,要获得点差的urlsheet,您可以简单地调用getUrl方法,其中returns一个完整的url到spreadsheet 作为一个字符串:

var ss = SpreadsheetApp.getActiveSpreadsheet();
Logger.log(ss.getUrl());

一旦你这样做了,你就有了使用 SriptApp 服务的正确想法,但是你正在处理在运行时附加脚本的细节错误。要将函数附加到 sheet,您需要创建一个新的 Trigger (which are effective just callbacks which are called given certain conditions) using the TriggerBuilder:

ScriptApp.newTrigger('myFunction')
  .forSpreadsheet(ss) // you can also use the spreadsheet id here
  .onOpen()
  .create();

请务必注意,您希望将所需的函数名称作为 字符串 而不是回调传递。

为此,您需要 https://www.googleapis.com/auth/script.scriptapp 授权范围,否则您将收到更多运行时错误,您可以在 google 脚本项目仪表板中查看这些错误。

更多信息请阅读Authorization Scopes and Authorization for Google Services