二维码登录实现(EggJS, 小程序)

时间:2022-07-23
本文章向大家介绍二维码登录实现(EggJS, 小程序),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

最近研究了扫码登录相关逻辑, 如有问题还望指正

流程图

二维码登录流程图

参考代码

后端相关代码

主要展示service代码

  1. 生成二维码guid

https://github.com/klren0312/ironInfoWeapp/blob/master/ApiServer/app/service/v1/user.js#L124

生成guid, 并将guid和扫码状态存入redis

genGuid: () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }
  async genLoginQrcode() {
    const { ctx } = this;
    const guid = ctx.helper.genGuid();
    await redis.set(guid, 'no', 'EX', 60);
    return guid;
  }
  1. 小程序扫码后, 后台判断是否可用

https://github.com/klren0312/ironInfoWeapp/blob/master/ApiServer/app/service/v1/user.js#L139

扫码后, 判断是否存在二维码, 若存在, 则判断是否有效, 有效则判断当前微信用户是否绑定了后管账号, 绑定则进行登录操作, 反之返回未绑定状态码

async checkLoginQrcode(guid, openId) {
    const { ctx, app } = this;
    const { wuser } = ctx.service.v1;
    const check = await redis.get(guid);
    if (check === 'no') {
      const user = await wuser.getBindUser(openId);
      if (user) {
        const token = app.getUserJson(user, ctx, 1);
        await redis.set(guid, JSON.stringify(token));
        return user;
      } else {
        await redis.set(guid, 'yes');
        return '3333'
      }
      return '1111'; // 无此用户
    }
    return '2222'; // 二维码无效
  }
  1. 用于后管前端轮询获取二维码状态

https://github.com/klren0312/ironInfoWeapp/blob/master/ApiServer/app/service/v1/user.js#L164

通过guid从redis中对应的值, 获取状态

async checkLoginQrcodeStatus(guid) {
    const tokenStr = await redis.get(guid);
    if (tokenStr && tokenStr !== 'no' && tokenStr !== 'yes') {
      console.log(tokenStr)
      const token = JSON.parse(tokenStr)
      return token;
    } else if (tokenStr && tokenStr === 'no') {
      return false;
    } else if (tokenStr && tokenStr === 'yes') {
      return 'scan'
    }
    return 'invalid';
  }

小程序相关代码

https://github.com/klren0312/ironInfoWeapp/blob/master/Weapp/pages/home/home.vue#L187

先检测是否授权获取用户信息, 有的话去进行扫码登录, 没有的话先跳小程序登录页 扫码登录后, 判断状态, 若为未绑定, 则跳绑定页

toQrcode() {
  // #ifdef MP-WEIXIN
  if (this.checkAuth()) {
    uni.scanCode({
        success: (res) => {
        if (res.result) {
          try{
            const obj = JSON.parse(res.result)
            console.log(obj.guid)
            if (obj && obj.hasOwnProperty('guid')) {
              const openId = uni.getStorageSync('openId')
              console.log(openId)
              checkQrcode(obj.guid, openId).then(res => {
                console.log(res)
                const status = res.data
                switch(status) {
                  case '1111':
                    uni.showToast({
                      icon: 'none',
                      title: '无此用户'
                    })
                    break
                  case '2222':
                    uni.showToast({
                      icon: 'none',
                      title: '二维码失效'
                    })
                    break
                  case '3333':
                    uni.showToast({
                      icon: 'none',
                      title: '未绑定用户'
                    })
                    uni.navigateTo({
                      url: '/pages/login/login'
                    })
                    break
                  default:
                    uni.showToast({
                      icon: 'success',
                      title: '扫码登录成功!'
                    })
                    break
                }
              })
            } else {
              uni.showToast({
                icon: 'none',
                title: '二维码无效'
              })
            }
          }catch(e){
            //TODO handle the exception
          }
        }
        }
    });
  }
  // #endif
}

后管前端代码

https://github.com/klren0312/ironInfoWeapp/blob/master/ServerWeb/src/pages/login/index.vue

没啥东西

演示地址

  • 绑定用户的账密:
    • 用户名: tour
    • 密码: tour520