首页 > 解决方案 > 如何确保 OAuth2 认证成功后重新发送原始 Google Chat 消息?

问题描述

我正在使用 Google Apps 脚本编写 Google Hangouts Chat 机器人。该机器人使用应用程序脚本 OAuth2 库向第三方服务进行身份验证。如本How-To中所述,当 bot 收到消息但需要通过第三方服务进行身份验证时,bot会向REQUEST_CONFIGChat 发送包含configCompleteRedirectUrl.

var scriptProperties = PropertiesService.getScriptProperties();

function onMessage(event) {
  var service = getThirdPartyService();
  if (!service.hasAccess()) {
    return requestThirdPartyAuth(service, event);
  }
  Logger.log('execution passed authentication');
  return { text: 'Original message ' + event.message.argumentText };
}

function getThirdPartyService() {
  var clientId = scriptProperties.getProperty('CLIENT_ID');
  var clientSecret = scriptProperties.getProperty('CLIENT_SECRET');
  return OAuth2.createService('ThirdPartyApp')
      // Set the endpoint URLs.
      .setAuthorizationBaseUrl('https://...')
      .setTokenUrl('https://.../oauth/token')

      // Set the client ID and secret.
      .setClientId(clientId)
      .setClientSecret(clientSecret)

      // Set the name of the callback function that should be invoked to
      // complete the OAuth flow.
      .setCallbackFunction('authThirdPartyCallback')

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getUserProperties())
      .setCache(CacheService.getUserCache())
      .setLock(LockService.getUserLock())

      // Set the scope and other parameters.
      .setScope('...')
      .setParam('audience', '...')
      .setParam('prompt', 'consent');
}

function requestThirdPartyAuth(service, event) {
  Logger.log('Authorization requested');
  return { "actionResponse": {
    "type": "REQUEST_CONFIG",
    "url": service.getAuthorizationUrl({
        configCompleteRedirectUrl: event.configCompleteRedirectUrl
    })
  }};

/**
 * Handles the OAuth callback.
 */
function authThirdPartyCallback(request) {
  var service = getThirdPartyService();
  var authorized = service.handleCallback(request);
  if (authorized) {
    Logger.log("user authorized");
    //https://stackoverflow.com/a/48030297/9660
    return HtmlService.createHtmlOutput("<script>window.top.location.href='" + request.parameter.configCompleteRedirectUrl + "';</script>");
  } else {
    Logger.log("user denied access");
    return HtmlService.createHtmlOutput('Denied');
  }
}

该服务定义了一个回调身份验证函数,该函数又将浏览器发送到configCompleteRedirectUrl. 到达此 URL 后,应该再次发送或重新发送原始消息(请参阅操作方法步骤 7.3)。

身份验证回调成功,因为浏览器 OAuth 流中显示的最后一页是event.configCompleteRedirectUrl. 在聊天窗口中,配置提示被删除,原始消息更改为公开。但是,不会再次发送原始消息。应用程序脚本控制台中显示的最后一条日志来自身份验证回调事件。

是否有什么我做错了导致原始消息无法再次发送?

标签: javascriptgoogle-apps-scripthangouts-chat

解决方案


在与 Google 支持团队成员反复讨论之后,事实证明,在针对 V8 Apps 脚本运行时运行 Hangouts Chat 实现时存在错误。

我的appsscript.json文件已经"runtimeVersion": "V8"设置好了。在这种情况下,重新调度不起作用。"runtimeVersion": "STABLE"在我恢复appsscript.json并重新部署我的脚本后,重新调度开始工作。


推荐阅读