首先要了解这个,得先知道微信登陆的流程在我以前的博客里面有
uniapp微信小程序登陆流程(前端详细)uniapp小程序如何做登录
uniapp微信小程序登陆流程(前端详细)uniapp小程序如何做登录
1.逻辑思路(会我上面链接以后才会理解我下面的方法)
第一次登陆的时候,将uni.getUserProfile()获取的数据缓存在本地,因为uni.getUserProfile()这个api必须通过点击按钮事件才可以调起,然后等下次在自己封装的request请求中,后端响应结果为token失效时做处理,判断本地存储里面有没有这个缓存uni.getUserProfile()得到的数据,如果有的话,直接使用uni.login()函数得到code和本地缓存uni.getUserProfile()的数据相结合向服务器发起登陆,这样就可以做到无痕登陆,最主要的操作是将uni.getUserProfile()得到的数据缓存下来
export const request = (url, method = 'get', params = {}) => { const token = uni.getStorageSync('token') || ''; //获取token uni.showLoading({ title: "加载中" }); return new Promise((resolve, reject) => { uni.request({ url: myApi.hostBaseUrl + url, method: method, header: { 'X-Token': token }, data: { ...params }, success(res) { console.log('request', res) if (res.data.msg === "登录信息已失效,请重新登录") { let loginInfo = uni.getStorageSync('loginInfo'); if (loginInfo == '') { //这里是对token失效 同时也没有缓存uni.getUserProfile()数据做的处理 uni.redirectTo({ url: '/pages/myUser/wxSign/wxSign?fromUrl=' + encodeURIComponent(getCurrentPages()[ getCurrentPages() .length - 1].$page.fullPath) }) } else { //这里是已经缓存了uni.getUserProfile()数据 直接发起调用登陆 wxlogin(loginInfo) } } else { if (res.data.code != 200) { uni.showToast({ title: res.data.msg, icon: 'none' }) return } resolve(res); } }, fail(err) { reject(err); }, complete() { uni.hideLoading(); } }); }); }; wxlogin = (loginInfo) => { let that = this; uni.showLoading({ title: '登录中' }); uni.login({ desc: 'weixin', success: res => { uni.request({ url: '请求后端登陆接口', data: { code: res.code, encryptedData: loginInfo.encryptedData, iv: loginInfo.iv }, method: 'GET', success(res) { console.log('登陆成功') //下面将从新刷新页面 var pages = getCurrentPages(); //获取所有页面的数组对象 var currPage = pages[pages.length - 1]; //当前页面 uni.reLaunch({ url: currPage.$page.fullPath }) }, fail() { that.$refs.uNotify.show({ message: '授权失败,请联系管理员', type: 'error' }); } }); } }); }