Skip to content

监听与输入企业微信登录验证码 #267

Open
@hcfw007

Description

@hcfw007

监听与输入企业微信登录验证码

近期,企业微信在一些账号首次登录设备时,会要求输入验证码。形式如下:

image

为了尽快适配此功能,我们在 @juzi/wechaty 包中率先实现了验证码事件和输入验证码的方法。我们也会接下来推动这一方法在社区版实现。需要注意的是,我们目前只能保证 node 版 wechaty 的使用体验,暂时没有多余的人手推动其他版本的迭代,为了更好的使用 token ,请尽量使用 node 版本的 wechaty。 ( @juzi/wechaty 只提供了 node 版本)

依赖版本

@juzi/[email protected]

@juzi/[email protected]

@juzi/[email protected]

类型定义

export enum VerifyCodeStatus {
  UNKNOWN = 0,
  WAITING = 1, // 待输入
  EXPIRED = 2, // 过期,尚未实装,目前应该根据接口返回抛错来判断是否过期
}

export enum VerifyCodeScene {
  UNKNOWN = 0,
  LOGIN = 1, // 登录验证码
}

type WechatyEventListenerVerifyCode = (
  id: string, // 验证码 id ,在登录场景下,与登录链接中的 key 对应
  message: string, // 验证码附带文字消息,目前固定为 请输入企业微信手机端展示的验证码,以继续登录
  scene: PUPPET.types.VerifyCodeScene, // 验证码场景,目前只有 登录
  status: PUPPET.types.VerifyCodeStatus // 验证码状态,目前只实现了 待输入
 ) => void | Promise<void>
 
 // 监听事件
bot.on('verify-code', async (id: string, message: string, scene: types.VerifyCodeScene, status: types.VerifyCodeStatus) => {
  // code here
})

相关方法

async enterVerifyCode (
  id: string,
  code: string,
): Promise<void> // 输入验证码
  
async cancelVerifyCode (
  id: string,
): Promise<void> // 取消验证码 (会导致二维码刷新)

async refreshQrCode (): Promise<void> // 强制刷新二维码

使用说明

在验证码事件 verify-code 推送的过程中,扫码事件 scan 也会继续推送 ( status 为 4 Confirmed )。bot 开发者应该关注 verify-code 事件的 id 字段,并将其与 scan 事件的 qrcode 字段进行比较。qrcode 字段是形式如 https://wx.work.weixin.qq.com/cgi-bin/crtx_auth?key=${qrcodeKey}&wx=1 的字符串,我们应该比较其中的 qrcodeKeyverify-code 事件的 id,如果两个不相同,说明出了新的二维码,需要重新扫码。

示例

输入验证码

const store = {}

bot.on('scan', (qrcode: string, status: types.ScanStatus) => {
  if (status === types.ScanStatus.Waiting) {
    // 新二维码
    store.qrcodeKey= getQrcodeKey(qrcode)
  }
}).on('verify-code', async (id: string, message: string, scene: types.VerifyCodeScene, status: types.VerifyCodeStatus) => {
  if (status === types.VerifyCodeStatus.WAITING && scene === types.VerifyCodeScene.LOGIN && id === store.qrcodeKey) {
    const verifyCode = await getVerifyCode() // 通过一些途径输入验证码
    try {
      await bot.enterVerifyCode(id, verifyCode) // 如果没抛错,则说明输入成功,会推送登录事件
      return
    } catch (e) {
      console.log(e.message)
      // 如果抛错,请根据 message 处理,目前发现可以输错3次,超过3次错误需要重新扫码。
      // 错误关键词: 验证码错误输入错误,请重新输入
      // 错误关键词:验证码错误次数超过阈值,请重新扫码'
      // 目前不会推送 EXPIRED 事件,需要根据错误内容判断
    }
  }
})

刷新验证码

await bot.cancelVerifyCode(store.qrcodeKey) // 根据 key 取消验证码 (需要重新扫码,不是更换验证码),但必须要在等待验证码状态才可以使用。

await bot.refreshQrCode() // 刷新二维码,任何情况都可使用

其他

请注意,相关文档可能会变化,但此 Issue 不一定能即时更新。请关注相关飞书文档,后期在我们的 token 自助系统上线后也会有 @juzi/wechaty 包的文档。

可运行实例

请使用这个 codespace

示例代码

请查看这个 repo workpro-getting-started.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions