You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google脚本权限每周过期,如何设置长期有效授权?

解决Google Apps Script权限每周过期问题

针对你用个人Google One账号运行GAS脚本(通过DoPost或表格变更触发)时权限每周过期的问题,可通过OAuth2库手动管理长期授权令牌来解决:

  1. 安装OAuth2库
    在GAS编辑器中,点击「扩展」>「库」,输入OAuth2库ID:1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF,选择最新版本后添加。

  2. 配置OAuth2授权流程
    编写函数获取Gmail的长期授权(包含刷新令牌),替换你的客户端ID和密钥(从Google Cloud Console的OAuth2客户端凭据中获取):

    function getGmailService() {
      return OAuth2.createService('Gmail')
        .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
        .setTokenUrl('https://accounts.google.com/o/oauth2/token')
        .setClientId('你的OAuth2客户端ID')
        .setClientSecret('你的OAuth2客户端密钥')
        .setCallbackFunction('authCallback')
        .setPropertyStore(PropertiesService.getUserProperties())
        .setScope('https://mail.google.com/') // 使用完整Gmail权限,避免权限不足
        .setAccessType('offline') // 获取刷新令牌,支持自动续期
        .setApprovalPrompt('force');
    }
    
    function authCallback(request) {
      var gmailService = getGmailService();
      var isAuthorized = gmailService.handleCallback(request);
      return HtmlService.createHtmlOutput(isAuthorized ? '授权成功' : '授权失败');
    }
    
    function authorize() {
      var gmailService = getGmailService();
      if (!gmailService.hasAccess()) {
        Logger.log('授权链接:' + gmailService.getAuthorizationUrl());
      } else {
        Logger.log('已完成授权');
      }
    }
    
  3. 替换原有Gmail调用逻辑
    把原来用GmailApp的代码,改成通过OAuth2服务调用Gmail API,示例:

    function processNewBooking() {
      var service = getGmailService();
      if (!service.hasAccess()) throw new Error('请先运行authorize函数完成授权');
    
      // 调用Gmail API发送邮件示例
      var emailRaw = Utilities.base64EncodeWebSafe(
        'To: customer@example.com\r\n' +
        'Subject: 预订确认\r\n\r\n' +
        '你的预订已确认'
      );
      var response = UrlFetchApp.fetch('https://www.googleapis.com/gmail/v1/users/me/messages/send', {
        headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
        method: 'post',
        contentType: 'application/json',
        payload: JSON.stringify({ raw: emailRaw })
      });
      Logger.log('邮件发送结果:' + response.getContentText());
    }
    
  4. 部署为Web应用并测试
    点击「发布」>「部署为Web应用」,设置:

    • 执行方式:以我自己的身份运行
    • 谁可以访问:根据需求选择(如「任何人,甚至匿名」,若仅内部使用可限制特定用户)
      部署后,第一次运行authorize函数,复制日志中的链接到浏览器完成授权,之后令牌会自动刷新,不会每周过期。

解决Python脚本手动刷新令牌问题

针对Python脚本需手动点击授权链接刷新令牌的问题,可通过获取离线刷新令牌实现自动续期:

  1. 修改OAuth2授权逻辑
    在代码中添加access_type='offline'和prompt='consent',确保第一次授权时获取刷新令牌:

    import os
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from google.auth.transport.requests import Request
    
    SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/documents']
    
    def get_credentials():
      creds = None
      # 读取本地存储的令牌
      if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
      # 自动刷新或重新授权
      if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
          creds.refresh(Request())  # 自动刷新令牌
        else:
          flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
          flow.params.update({'access_type': 'offline', 'prompt': 'consent'})
          creds = flow.run_local_server(port=0)
        # 保存令牌到本地
        with open('token.json', 'w') as token:
          token.write(creds.to_json())
      return creds
    
    # 初始化服务
    creds = get_credentials()
    gmail_service = build('gmail', 'v1', credentials=creds)
    docs_service = build('docs', 'v1', credentials=creds)
    
  2. 可选:使用服务账号(适合共享资源场景)
    若个人账号OAuth2仍有问题,可创建Google Cloud服务账号,下载密钥文件后直接授权:

    from google.oauth2.service_account import Credentials
    
    SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/documents']
    SERVICE_ACCOUNT_KEY = 'service-account-key.json'
    
    creds = Credentials.from_service_account_file(SERVICE_ACCOUNT_KEY, scopes=SCOPES)
    # 若需访问你的个人邮箱/文档,需先将资源共享给服务账号邮箱,再设置subject(个人账号需启用域范围委托,可能受限)
    # creds = creds.with_subject('your-personal-email@gmail.com')
    
    gmail_service = build('gmail', 'v1', credentials=creds)
    

注意事项

  • 确保Google Cloud Console中已启用Gmail API和Google Docs API,且客户端凭据/服务账号密钥正确。
  • GAS中使用OAuth2库后,仅需手动授权一次,后续令牌自动续期;Python脚本第一次授权后,token.json会保存刷新令牌,无需再手动操作。

内容的提问来源于stack exchange,提问作者Raphael Moras de Vasconcellos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:30:05