!!请查收一篇关于【微信小程序授权微信登录】的邮件

941 阅读2分钟

前言

小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系。本篇着重介绍小程序登录授权的整个实现过程。

实现目标

  • 1.实现点击授权,弹出授权弹窗;
  • 2.确认授权后,button隐藏,回显用户信息。

QQ截图20210716165128.png

基本流程

首先贴出官网给的流程图。。仔细研读一遍,大致流程就差不多了。这里从前端开发的角度大致说一下该流程:

  • 调用 wx.login() 获取 临时登录凭证 code ,并回传到开发者服务器
  • 通过调用服务端提供的接口把code传递给服务端,然后服务端会返回给前端openidsesstion_key

api-login.2fcc9f35.jpg

主要步骤

1. 授权窗口

<button type='primary' lang="zh_CN" bindtap="getUserProfile"> 登录 </button>

getUserProfile() {
    var that = this
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo
        })
        wx.setStorageSync('userInfo', this.data.userInfo)
        that.login()
      }
    })
},

2. 调用wx.login得到code,并验证

login() {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      wx.login({
        timeout: 500,
        success: (result) => {
          const { code } = result;
          user.checkLogin().catch(() => {
            user.loginByWeixin(userInfo).then(res => {
              app.globalData.hasLogin = true;
              this.onShow();
              this.setData( {
                userInfo: userInfo
              })
            }).catch((err) => {
              app.globalData.hasLogin = false;
              util.showErrorToast('微信登录失败');
            });
          });
        }
      })
    }
  }

封装的代码

为便于后续操作和使用,将用户检测和微信登录进行了封装。详细代码如下:

/**
 * 判断用户是否登录
 */
function checkLogin() {
  return new Promise(function(resolve, reject) {
    if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')) {
      checkSession().then(() => {
        resolve(true);
      }).catch(() => { 
        reject(false);
      });
    } else {
      reject(false);
    }
  });
},
/**
 * 调用微信登录
 */
function loginByWeixin(userInfo) {
  return new Promise(function(resolve, reject) {
    return login().then((res) => {
      //登录远程服务器
      util.request(api.AuthLoginByWeixin, {
        code: res.code,
        userInfo: userInfo
      }, 'POST').then(res => {
        if (res.errno === 0) {
          //存储用户信息
          wx.setStorageSync('userInfo', res.data.userInfo);
          wx.setStorageSync('token', res.data.token);
          resolve(res);
        } else {
          reject(res);
        }
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}

!需要注意的点

官方宣布2021年4月13日后发布的小程序新版本,无法通过wx.getUserInfo与< button open-type=“getUserInfo” />获取用户个人信息。现在只能通过wx.getUserPorifile接口去老实的不厌其烦的让用户授权即刻获取用户信息。同时必须通过bindtap等点击事件才能触发调用授权

总结

完整实现小程序的授权登录,需要更加详细的打磨,这里只是简单将整个流程大致走通,童鞋们还要根据自己的实际项目进行修改和完善。