google-apps-script - 如何启用 OAuth Google 脚本,而无需每次 token 过期时都登录?

标签 google-apps-script google-sheets oauth-2.0 oauth google-oauth

此 .gs 代码检查文档是否已授权,如果是,则运行发布请求。我尝试只提供 OAuth 一次,而不是每次 token 过期时提供,任何建议都将受到赞赏!

function Gmail() {

  if (service.hasAccess()) {
  var toolKeyFinal = service.getAccessToken();

//*******request would run with token here********

   }
  else{
      var authorizationUrl = service.getAuthorizationUrl();
      var string = toolName+" Authorization (then try formula again 👍),"+authorizationUrl;
      var auth = [{}];
      return string.split(",")
  }
}

  
function getServiceGmail() {
  return OAuth2.createService('Gmail')
      .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setClientId('CLIENT-ID')
      .setClientSecret('CLIENT-SECRET')
      .setCallbackFunction('authCallback')
      .setPropertyStore(PropertiesService.getDocumentProperties())
      .setScope('https://mail.google.com/');
};

/**
 * Handles the OAuth callback.
 */
function authCallback(request) {
  var service = getServiceGmail();
  var authorized = service.handleCallback(request);
  if (authorized) {
    return HtmlService.createHtmlOutput(
    "<script>window.top.location.href='https://REDIRECT.com';</script>"
  );
    //return HtmlService.createHtmlOutput('PowerSheet authorization successful for your Google Sheet! You can close this tab.');
  } else {
    return HtmlService.createHtmlOutput('You did not provide authorization. Please close this tab and try again.');
  }
}

最佳答案

根据documentation :

A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.

因此,对于外部(又名面向用户的)应用程序,您必须升级 publishing status通过 Google 的审核和验证流程,将其更改为“正在生产中”。

此外,由于您使用的是受限范围 (https://mail.google.com/),您还必须接受安全评估,该评估可能会让您花费 8 美元起k 至 7.5 万美元(参见 Security Assessment)

关于google-apps-script - 如何启用 OAuth Google 脚本,而无需每次 token 过期时都登录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68929758/

相关文章:

google-apps-script - 如何对 Google 文档/云端硬盘文档中的标题进行编号?

google-apps-script - 如果函数已经在运行,如何防止谷歌应用程序脚本触发

google-apps-script - 通过 Google Apps 脚本的 Spotify API 授权

python - 单元格注释和颜色可以使用 gspread 查询吗?

javascript - 当 Google Script 检测到后台发生变化(例如 cron)时,它如何发送电子邮件?

ruby - 如何在使用门卫的 oauth 提供商上为我的用户预授权客户端应用程序?

javascript - 为什么方法 setValue 的输出与 Browser.msgBox 不同?

javascript - 使用 Nodejs 将行添加到 Google Sheet

node.js - 使用我的自己的Web应用程序使用passwordjs管理单点登录-共享登录

php - 使用 OAuth 2.0 登录 Facebook