uni-app 对FastAdmin微信公众号授权登录实例
uniapp 微信公众号授权登录代码
跳转获取code 提交fastadmin 第三方登录插件 进行登录验证 存储token
onLoad() {
// 非静默授权,第一次有弹框
let local = window.location.href; // 获取页面url
console.log(local)
let appid = '********' // 公众号appid
let code = this.getUrlCode().code; // 截取code
// 获取之前的code
let oldCode = uni.getStorageSync('wechatCode')
if (code == null || code === '' || code == 'undefined' || code == oldCode) {
// 如果没有code,就去请求获取code
console.log('当前没有code,进入授权页面')
let uri = encodeURIComponent(local)
// 设置旧的code为0,避免死循环
uni.setStorageSync('wechatCode',0)
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
} else {
uni.setStorageSync('wechatCode',code)
this.$http.post('api/user/third', {
'platform':'wechat',
'code':code
} ).then(res => {
if(res.data.code==1){
uni.setStorageSync('token',res.data.data.userinfo.token)
uni.setStorageSync('userinfo',res.data.data.userinfo)
uni.switchTab({
url:"/pages/index/index"
})
}else{
//重新拉起登录
let uri = encodeURIComponent(local)
uni.setStorageSync('wechatCode',0)
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
}
}).catch(err => {
})
}
},
methods: {
getUrlCode() {
// 截取url中的code方法
var url = location.search;
// this.winUrl = url;
var theRequest = new Object();
if (url.indexOf('?') != -1) {
var str = url.substr(1);
var strs = str.split('&');
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
}
}
return theRequest;
}
}