Automated OAuth2 token not working - Google Apps Script

痞子三分冷 提交于 2019-12-25 04:17:44

问题


I am trying to run a google apps script, in a document, that sends an email with an attached google spreadsheet as an .xlsx file automatically, running every few hours.

Below is the solution that works if I use a manual OAuth2 code coming from the google OAuth2 playground :

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 })
}    

To try to auto-generate the authorization token I followed exactly all the steps here:

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

Changing on the script : .setClientId('...') .setClientSecret('...') I also put in the URI the the Project Id inside the https://script.google.com/macros/d/myprojectkey/usercallback of the google developer console

But when i run the function makeRequest() it tells me : "Access not granted or expired"

So i wonder which step i missed.

Do you have any clue on what is going on ?

Help is much appreciated, Thanks


回答1:


You need to do step 2: Direct the user to the authorization URL
When the sidebar loads you will click the link and the Oauth dialog will open. After you allow access you can use the getAccessToken() method.

EDIT: For your specific case you do not need a separate OAuth flow. You can use Apps Script to get the token you need to do that export. As you are already requesting access to drive your token will work for the export call.

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 })
}    


来源:https://stackoverflow.com/questions/30781884/automated-oauth2-token-not-working-google-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!