美文网首页
微信小程序---封装登录授权方法

微信小程序---封装登录授权方法

作者: 代码使劲儿搬 | 来源:发表于2020-12-14 15:06 被阅读0次
  1. 在publicMethod.js公共文件里:
const common = require('common'); // 封装的request接口请求方法
let publicMethod = {
    getUserInfo(e, t, f) {
    let that = t
    wx.setStorageSync('user_info', e.detail.userInfo)
    wx.login({
      success: function(data) {
        common.post('/member/oauth', {
          code: data.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        }).then(res => {
          console.log(res)
          if (res.data.code == 200) {
            that.setData({
              isAuthorize: false,
              pop2: false
            })
            console.log("授权成功")
            console.log(res)
            wx.showTabBar()
            that.setData({
              member_id: res.data.member_id
            })
            wx.setStorageSync('member_id', that.data.member_id);
            if (typeof f == "function") {
              return f(res)
            }
          }
        }).catch(e => {
          app.showToast({
            title: "数据异常",
          })
          console.log(e)
        })
      }
    })

  },
}
module.exports = publicMethod

2.在你要授权登录的页面js文件中 index.js:

const common = require('/assets/js/common');
const publicMethod = require('/assets/js/publicMethod');
Page({
  data: {
    member_id:'',
},
onLoad:function(options){
  let that = this;
    let member_id = wx.getStorageSync('member_id'); // 获取保存在缓存里的id
    if (!member_id) { // 判断是否登录过,如果没有登录就弹出授权登录框
      that.setData({
        pop2: true
      })
      return
    } else {
      that.setData({
        member_id: member_id,
        pop2: false
      })
    }
},
getData(){
},
//微信授权 获取个人信息,调用封装的公共方法
getUserInfo: function (e) { 
    publicMethod.getUserInfo(e,this,this.getData);
  },
})

这样就可以正常授权调用了;之后在其他页面的也有需要授权登录的直接按上面的调用即可(注意: 这边省略了在WXML页面里的登录弹框组件)

相关文章

网友评论

      本文标题:微信小程序---封装登录授权方法

      本文链接:https://www.haomeiwen.com/subject/zccvgktx.html