记录下,之前一直拿到code后就不管了,后来加上iv、encryptedData 给后台,但是有时候解密会报错,就会显示授权登录失败,最后找到原因是先获取用户信息导致的
1.点击之后先登录获取code
2.获取code后再获取用户信息
3.传递数据
备注:先调用了getUserInfo获取了解密数据,然后又调用的login,就会刷新登录态,导致登录失败
<template>
<view class="page">
<view class="tk-column ">
<view class="title">
<image src="../../static/logo.jpg" class="logo" mode="aspectFill"></image>
</view>
<view class="login-btn-box tk-column">
<button class="btn-tk" @getuserinfo="do_login" open-type="getUserInfo">登录</button>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
wx_code: '',
}
},
methods: {
do_login(e) {
let infoRes = e.detail;
var that = this;
//获取用户授权
uni.getProvider({
service: 'oauth',
success: function(res) {
// console.log(res);
//微信端
if (~res.provider.indexOf('weixin')) {
console.log("weixin login");
//微信登录
uni.login({
provider: 'weixin',
success: function(loginRes) {
console.log('loginRes.code---------' + loginRes.code);
that.wx_code = loginRes.code;
uni.getUserInfo({
provider: 'weixin',
withCredentials: true,
success: function(userRes) {
console.log(userRes);
that.post_login(userRes);//这里拿最新一次获取的
},
fail: function(userRes) {
}
})
},
fail: function(loginRes) {
console.log(loginRes);
}
});
}
}
});
},
post_login(e) {
// console.log(e);
var that = this;
let data = {
method: 'user.nflogin',
code: this.wx_code,
edata: e.encryptedData,
iv: e.iv
};
that.$api.post('', data).then(res => {
let data = res.data;
// console.log(res);
uni.showToast({
title: data.msg,
icon: "none"
});
if (data.status) {
// console.log(data.code);
// console.log(data.data.token)
// that.wx_getuser_show=false
//保存登录状态
// this.$store.state.hasLogin = true;
uni.setStorageSync('token', data.data.token);
uni.setStorageSync('hasLogin', true);
that.get_userinfo();
}
})
},
//获取用户信息
get_userinfo() {
// console.log('get user info');
var that = this;
let data = {
method:login,
token: token,
};
that.$api.post('', data).then(res => {
let data = res.data.data;
uni.setStorageSync('userInfo', data);
// console.log(data);
uni.navigateBack({
})
})
}
}
}
</script>
<style scoped lang="scss">
.page {
padding: 15upx;
height: 100%;
}
.title {
font-weight: bold;
font-size: 46upx;
text-align: center;
line-height: 4rem;
}
.tk-column {}
.login-btn-box {
width: 100%;
height: 300upx;
align-self: center;
justify-content: center;
.btn-tk {
align-items: center;
}
}
.logo {
width: 100%;
}
</style>