微信小程序登录流程

399 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

微信小程序页面画好后,需要开始做一系列和用户的交互功能了,首先就是登录。

流程图如下 在这里插入图片描述 目测第一步是需要调用wx.login来获取code的,开始

      // 微信登录
      wxLogin() {
        let that = this
        wx.login({
          success(res) {
            console.log('wxLogin')
            console.log(res)
            if (res.code) {
              //发起网络请求
              that.code = res.code
            }
          }
        })
      },

当然这次做的没有那么简单,是需要用户点击登录,然后调取接口的,所以从点击开始讲起。

  1. 由于需要用户授权,才可以获取信息,所以需要用到wx.authorize接口来引导用户授权,但是每次都让用户授权很不友好,所以使用wx.getSetting来验证授权。注:由于我们是要调用用户信息,所以button的open-type需要设置成getUserInfo。 上代码
<button class="login-btn" open-type="getUserInfo" @click="toAuthorize">
 toAuthorize() {
        let that = this
        // 查看是否授权
        wx.getSetting({
          success(res) {
          //res.authSetting包含着所有允许的权限,通过这个,可以判断用户是否授权
            if (res.authSetting['scope.userInfo']) {
              that.getUserInfo()
            } else {
            //没授权就调用authorize,scope按需填好,这里是用户信息。
              wx.authorize({
                scope: 'scope.userInfo',
                success (r) {
                  console.log('未授权提示授权')
                  console.log(r)
                  that.getUserInfo()
                }
              })
            }
          }
        })
      },
  1. 进行完授权之后,就可以获取用户信息了。
 // 获取用户信息
      getUserInfo () {
        let that = this
        wx.getUserInfo({
        //可以获取用户信息
          success: function(res) {
            console.log('getUserInfo')
            console.log(res)
            that.userInfo = res.userInfo
            //拿到用户信息,去调登录接口
            that.toLogin();
            //这里是为了将userInfo长期储存,下次就可以直接使用
            try {
              wx.setStorage({key: 'userInfo', data: JSON.stringify(res.userInfo)})
            }catch (e) {
              console.log(e)
            }
          }
        })
      },
  1. 调取登录接口,这里是提前封装好了登录方法,拿来调用。
/**
   * @function 登录方法
   * @param params {Object} {query: {}, header: {contentType: 'application/x-www-form-urlencoded'}}
   * @returns {Promise<resolve>}
   * @author zs
   */
  login(params) {
    // return request(params, '/wechat/login')
    let data = params.query || {}
    return new Promise(resolve => {
      wx.request({
        url: API_MALL_LOGIN + '/wechat/login',
        method: 'POST',
        data: data,
        dataType: 'json',
        header: {
          'Content-Type': params.header.contentType
        },
        success(res) {
          resolve(res)
        },
        fail(fail) {
          console.log('fail')
          console.info(fail)
        }
      })
    })
  }
}
 // 调用登录接口
      toLogin() {
        //  登录发起网络请求
        let that = this
        // that.isLogin = true
        //这里的login就是封装好的,可以拿来用。
        Api.login({
          query: {
            code: that.code,
            nick_name:that.userInfo.nickName,
            user_sex:that.userInfo.gender
          },
          header: {
            contentType: 'application/x-www-form-urlencoded'
          }
        }).then(result => {
          console.log(result);
          let r = result.data
          if (r.code == '0') {
          //这里是用来判断,进入页面的用户是否登陆过,防止登录失效
            wx.setStorage({ key: 'userId', data: r.data.userId })
            wx.setStorage({ key: 'openId', data: r.data.openId })
            //这个就是用来判断登录,未登录就显示xx,登录就显示数据
            that.isLogin = true
          }
        })
      },
  1. 刚才第三步说了进入页面要进行一个判断。来了,开局调用wx.checkSession
      let that = this;
      // 核验登录状态
      wx.checkSession({
        success () {
          //session_key 未过期,并且在本生命周期一直有效
          //当session_key未过期,判断刚才存放的userId是否存在
          if (wx.getStorageSync('userId')) {
            // 登录有效
            //直接拿 不用登陆了
            that.userInfo = JSON.parse(wx.getStorageSync('userInfo'))
            that.isLogin = true
          } else {
          //没登陆过,清除缓存,重新来过。
            that.clearData();
          }
        },
        fail () {
          // session_key 已经失效,需要重新执行登录流程
          that.clearData();
        }
      })
// 清除登录数据
      clearData () {
        this.isLogin = false
        this.isLogin = ''
        this.userInfo = {}
        this.wxLogin() //重新登录
        try {
          wx.clearStorageSync()
        } catch(e) {
        }
      }
    },

好了,登录就此为止,总结一下:进入页面先wx.checkSession检查userId是否存在,如果存在,那就是登陆过,直接拿;如果没登陆过,清理缓存,重新调用wx.login()获取code,然后等待用户点击button。进行后续的登录操作。