0

我正在尝试使用 Google Apps Script API 方法运行 Google Apps 脚本scripts.run。但是,我收到带有以下错误消息的 403 错误:

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

以下是我发送的 POST 请求的标头:

authorization: Bearer my-oauth-token
Content-Type: application/json
Origin: http://localhost:5000
Referer: http://localhost:5000/static/test.html
User-Agent: Mozilla/5.0...

我将请求发送到 https://script.googleapis.com/v1/scripts/my_script_id:run?key=my_api_key

有任何想法吗?我已经尝试搜索示例,但是当我需要使用 REST api 时,我得到的只是谷歌 apis 客户端库。我确信我的 oauth 令牌是正确的,因为我使用相同的令牌向其他 Google api 发出请求。

这是我目前的流程:

  1. 将用户重定向到 oauth url,并获取交换码。我的重定向网址是
"https://accounts.google.com/o/oauth2/v2/auth?"
        "scope=https://www.googleapis.com/auth/drive&"
        "state=%s&"
        "redirect_uri=redirect_uri&"
        "client_id=id&"
        "response_type=code&"
        "access_type=offline&"
        "prompt=consent"
  1. 刷新令牌的交换代码
  2. 使用刷新令牌获取 oAuth 访问令牌。我发送一个 POST 请求来https://www.googleapis.com/oauth2/v4/token执行此操作。
  3. 我使用访问令牌从用户的谷歌幻灯片中获取缩略图。此请求成功。
  4. 我发送执行 Google Apps 脚本的请求。以下是此请求的摘要代码:
xhr.open("POST", "https://script.googleapis.com/v1/scripts/id:run", true);
xhr.setRequestHeader("authorization", "Bearer " + oauth_token);
xhr.onload = function() { // do stuff }
xhr.onerror = function() { // print error }
xhr.send(JSON.stringify({
   "function": "run",
    "parameters": [
       id1,
       id2
    ]
}));

这给了我 401 错误。我还收到消息“显示临时标题”。我调查了一下,它似乎与我的问题无关。在此处输入图像描述

这是我要运行的脚本:

function doGet(e) {
  if(!(e.parameter.source && e.parameter.destination)) {
    throw new Error("Not all parameters specified");
  }
  copySlides(e.parameter.source, e.parameter.destination);
}

function copySlides(sourceId, destinationId) {
  var src = SlidesApp.openById(sourceId);
  var dest =  SlidesApp.openById(destinationId);

  src.getSlides().forEach(function(slide, index) {
      dest.appendSlide(slide);
  });
  return ContentService.createTextOutput("Done Copying Slides");
}
4

1 回答 1

2

事实证明我缺少一个额外的 oAuth 范围,因为我的脚本使用了 Google SlidesApp。添加https://www.googleapis.com/auth/presentations范围固定。

于 2019-04-11T15:43:24.007 回答