【问题标题】:Automated OAuth2 token not working - Google Apps Script自动 OAuth2 令牌不起作用 - Google Apps 脚本
【发布时间】:2015-06-11 13:14:49
【问题描述】:

我正在尝试在文档中运行一个 google 应用程序脚本,该脚本会自动发送一封电子邮件,其中附有 .xlsx 文件的 Google 电子表格,每隔几个小时运行一次。

如果我使用来自 google OAuth2 游乐场的手动 OAuth2 代码,以下是可行的解决方案:

function downloadXLS() {
  var AUTH_TOKEN = "xxxx"; 
  var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";
  var file = Drive.Files.get('xxxx');
  var response = UrlFetchApp.fetch('https://docs.google.com/spreadsheets/d/xxx/export?format=xlsx',{headers: {Authorization: auth}});      
  var doc = response.getBlob();
  app = DriveApp.createFile(doc).setName(file.title + '.xls')
  MailApp.sendEmail("xxx@xxx.com", "oh man", " Body", { attachments: app })
}    

为了尝试自动生成授权令牌,我完全按照此处的所有步骤操作:

https://github.com/googlesamples/apps-script-oauth2

更改脚本: .setClientId('...') .setClientSecret('...') 我还在 URI 中放入了 Google 开发者控制台的 https://script.google.com/macros/d/myprojectkey/usercallback 中的项目 ID

但是当我运行 makeRequest() 函数时,它告诉我:“访问未授予或过期”

所以我想知道我错过了哪一步。

你有什么线索吗?

非常感谢您的帮助, 谢谢

【问题讨论】:

    标签: oauth google-apps-script google-drive-api


    【解决方案1】:

    您需要执行第 2 步:将用户定向到授权 URL
    当侧边栏加载时,您将单击该链接并打开 Oauth 对话框。允许访问后,您可以使用 getAccessToken() 方法。

    编辑: 对于您的特定情况,您不需要单独的 OAuth 流程。您可以使用 Apps 脚本来获取执行该导出所需的令牌。由于您已经请求访问驱动器,因此您的令牌将适用于导出调用。

    function downloadXLS() {
    
      var file = Drive.Files.get('xxxx');
      var response = UrlFetchApp.fetch('https://docs.google.com/spreadsheets/d/xxx/export?format=xlsx',{headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});      
      var doc = response.getBlob();
      app = DriveApp.createFile(doc).setName(file.title + '.xls')
      MailApp.sendEmail("xxx@xxx.com", "oh man", " Body", { attachments: app })
    }    
    

    【讨论】:

    • 谢谢斯宾塞。侧边栏实际上永远不会出现,即使脚本处理代码时没有错误。唯一打开的是标准授权弹出窗口,即使没有“侧边栏”代码也会发生。
    • 哦,是的。您必须手动运行该功能以显示侧边栏或添加菜单项以启动它。并且将有两个身份验证流程。一个用于脚本,一个用于 Oauth 库。也看看我的编辑。
    • 感谢您的编辑,它运行良好!其实我只需要上面的代码(然后在项目中手动授权驱动api)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    相关资源
    最近更新 更多