从 Google 表格调用时,getOAuthToken returns null

getOAuthToken returns null when called from Google Sheets

我正在研究使用 oAuth 规范和 AWS API 网关调用为特定用户限制某些 Google 工作表的方法,但我遇到了 ScriptApp.getOAuthToken()函数。

当我 运行 使用 Google Apps 脚本调试器编写代码时,一切正常,ScriptApp.getOAuthToken() returns 我可以将令牌传递给我的 AWS API。现在的预期结果只是收到用户名。 但是,如果我尝试在 Google 表格单元格中将我的函数用作宏,则会出现以下错误 Header:null (line 13)

这是 Code.gs 文件中的代码

function HelloW() {
  var token = ScriptApp.getOAuthToken();
  var headers = {
    'Authorization' : token
  }

  var options = {
    'headers' : headers,
    'method' : 'post',
    'contentType': 'application/json',
    'payload' : JSON.stringify(data)
  };

  var response = UrlFetchApp.fetch('https://###/demo-lambda', options);

  var txt = response.getContentText();
  var json = JSON.parse(txt);
  var name = json.Message;

  return name;
}

还有清单以防万一

{
  "timeZone": "Europe/Paris",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes": ["https://www.googleapis.com/auth/script.external_request", 
"https://www.googleapis.com/auth/spreadsheets", 
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/drive"],
  "sheets": {
    "macros": [{
      "menuName": "HelloW",
      "functionName": "HelloW"
    }]
  }
}

我有一个错误,因为 token 是空的,但我不明白为什么它在调试器上运行良好,但在表格文档中却没有。我遗漏了一些东西,但我找不到什么。

如有任何帮助,我们将不胜感激。

您不能在需要用户授权的宏中进行调用。

Unlike most other types of Apps Scripts, custom functions never ask users to authorize access to personal data. Consequently, they can only call services that do not have access to personal data.

Source