uniapp 微信授权登录功能实现
微信授权登录
很多app都有第三方账号登录,常见的就是 微信/QQ/支付宝/淘宝等第三方账号登录。
下面说明一下微信授权的登录的全过程。
uni.login({})
...mapActions([
'loginAction',
"userInfoAction",
"codeAction"
]),
_this = this;
uni.login({
provider: 'weixin',
success: function (loginRes) {
//通过微信授权可以拿到一些数据,如:openId,此处的contype:form代表数据请求是通过form-data的形式传递的,这个前面的博文中有提到。
_this.$store.commit("wxLoginInfoFn", loginRes.authResult);
_this.$request.urlRequest(
'/user/checkOpenId',//此处的接口是后台提供的。如果微信已经注册过,则返回为true
{
"openId": loginRes.authResult.openid,
"contype": "form"
},
'POST',
function (res) {
if(res.result){ //注册过
_this.loginAction({//此处的方法是写入到store中的action中的登录方法
"appId": "wx9b0c3683xxxxxxxx",
"openId": loginRes.authResult.openid,
"type": "1"
}).then((res) => {
if(res.code === 200){
_this.getUserInfo();
// 以下的代码可以注释掉,通过后台返回的数据来获取。因为后台没有返回已经注册过的微信信息,所以此处代码是为了再次获取微信的信息。
uni.getUserInfo({
provider: 'weixin',
success: function (infoRes) {
console.log("微信",infoRes.userInfo);
_this.$store.commit("wxUserInfoFn", infoRes.userInfo);
console.log("getUserInfo",infoRes.userInfo)
},
fail: () => {
}
});
}else{
console.log(res)
uni.showToast({
title: res.msg,
icon: 'none',
duration: 4000
});
}
});
}else{ //未注册
// 获取用户信息 获取微信授权
uni.getUserInfo({
provider: 'weixin',//供应商为微信
success: function (infoRes) {
console.log("微信",infoRes.userInfo);//此处可以获取到微信的信息
_this.$store.commit("wxUserInfoFn", infoRes.userInfo);//此处代码是将微信的信息存储到store中的state中。
_this.$store.commit("wxLoginFn", true);
console.log("getUserInfo",infoRes.userInfo)
uni.showToast({title:"授权成功!"});
},
fail: () => {
uni.showToast({title:"授权失败"});
}
});
}
}
)
},
fail: () => {
uni.showToast({title:"微信登录授权失败"});
}
});