微信公眾號授權登錄方法
01.先請求后台接口獲取回調鏈接地址,使用window.location.href進行跳轉。
1 // 授權登錄
2 login() {
3 uni.request({ 4 url: '后台給的接口地址', 5 method: 'post', 6 data: {} 7 }).then(res => { 8 window.location.href = res.data.data; 9 }) 10 },
02.在onLoad()方法中接收參數對code進行賦值,然后通過getUserInfo()方法獲取用戶信息。
1 onLoad(option) {
2 console.log('授權登錄頁面的option', option) 3 this.code = option.code 4 if (this.code) { 5 this.getUserInfo() 6 } else { 7 this.login() 8 } 9 },
1 // 獲取用戶信息
2 getUserInfo() {
3 var that = this; 4 uni.request({ 5 url: '獲取用戶信息接口', 6 method: 'post', 7 data: { 8 code: that.code, 9 openid: uni.getStorageSync('openId') || "", 10 userId: uni.getStorageSync('parentId') || '', 11 } 12 }).then(res => { 13 if (res.data.code == 200) { 14 console.log("獲取用戶信息"); 15 uni.setStorageSync('userInfo', res.data.data) 16 uni.setStorageSync('openId', res.data.data.wechatOpenId) 17 that.getToken(res.data.data.id); 18 } 19 }) 20 },
03.最后調用getToken()方法,獲取token。
1 // 獲取Token
2 getToken(userId) {
3 var that = this; 4 uni.request({ 5 url: '獲取token接口', 6 method: 'POST', 7 data: { 8 id: userId 9 } 10 }).then(res => { 11 if (res.data.code == 200) { 12 uni.setStorageSync('token', res.data.data) 13 //獲取到token之后就可以跳轉到項目首頁了 14 } 15 }) 16 },
前端小白剛開通博客,如若有好的修改建議歡迎大家評論留言交流。