小程序登录

登录界面

设计图如下
登陆界面.png

布局

  • 布局上只需要添加“进入答题”按钮即可,按钮添加触发方法
bindgetuserinfo="bindGetUserInfo"
  • 微信新的规定,无法直接从JS中调用wx.getUserInfo()api,需要使用按钮引导用户登录,在按钮中添加
open-type="getUserInfo"
  • 详情使用scroll-view标签实现,需要添加属性允许其滚动
scroll-y='true'

初始化模块

/**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //缓存token
    let that = this;
    var introduction = that.data.introduction;
    var localtoken = wx.getStorageSync ('logintoken');
    if (localtoken != '') {
      
      that.setData({
        token : localtoken
      })
    };
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          console.log('用户已经授权过')
        }
      }
    }),
  wx.request({
    url: '',
      url: app.globalData.url + '/index.php?s=/Api/Jiwei/getBrainIntroduction',
      data: {
        id: app.globalData.id
      },
      header: { 'Content-Type': 'application/json' },
      success: function (res) {
        console.log(res)
        that.setData({
          introduction: res.data.resData.introduction,
          title: res.data.resData.title,
        })

      },
  })

  },
  • 在生命周期onLoad的时通过wx.getStorageSync 获取本地缓存,以供后续页面调用接口的时候使用
  • 通过wx.getSetting获取用户是否授权过

登陆模块

  bindGetUserInfo: function (e) {
    let that =this;
    var code=that.data.code;
    wx.login({
      success: function (loginRes) {
        if (loginRes.code) {
          console.log('获取code成功');
          code = loginRes.code;
          wx.getUserInfo({
            //获取到的地点是中文形式
            lang: "zh_CN",
            success: function (infoRes) {
              wx.request({
                url: app.globalData.url + '/index.php?s=/Api/Jiwei/login',
                data: {
                  code: code,
                  rawData: infoRes.rawData,
                  signature: infoRes.signature,
                  encryptedData: infoRes.encryptedData,
                  iv: infoRes.iv,
                  token: that.data.token
                },
                header: { 'Content-Type': 'application/json' },
                success: function (res) {
                  //登陆成功
                  if (res.data.resCode==1000){
                    wx.setStorageSync('logintoken', res.data.resData.token)
                    //跳转
                    wx.redirectTo({
                      url: '../personal/personal'
                    })
                  }else{
                    console.log("登陆失败");
                  }
                }
              })
            }
          })
        }
        else{
          console.log('获取code失败');
          return;
        }
      }
    })   
  },

传入指定参数获取token,其中

  • code通过wx.login获取
  • rawData,signature,encryptedData,iv通过wx.getUserInfo获取
  • 第一次登陆时通过wx.setStorageSync()本地缓存token

你可能感兴趣的:(小程序登录)