使用uni 微信登录第一次失败,第二次就成功,附带解决办法,绝对好使
在开发小程序的时候 跟着api 来写的可是不知道为什么 就是要登录二次才能成功原因是 点击一次获取code 在登录与发送请求给后端的code不匹配 所以得在次登录 获取新的code 才能登录成功 解决办法就是在页面一刷新的时候 自动获取一次code 后面在点击登录的时候在获取一次 就成功了
<template>
<view class="box">
<view class="top">
<view class="logo"
><image src="../../static/196d5967566152e112a455d4c73da6b.png"></image
></view>
<view class="texts">标题</view>
</view>
<view class="bottom">
<view style="font-size: 35rpx">确认授权后将获取以下权限</view>
<view>
<u-checkbox-group
><u-checkbox
v-model="checked"
@change="checkboxChange"
:label-size="35"
>获得你的公开信息(头像,昵称等)</u-checkbox
></u-checkbox-group
>
</view>
<view @click="login" class="login">登录授权</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
encryptedData: '',
iv: '',
code: '',
miniCode: 'xiaoxin',
checked: true,
Url: ''
};
},
onLoad() {
this.logs();
this.inits();
let that = this;
setTimeout(function() {
that.logsq();
}, 2000);
},
onShow() {
setTimeout(function(){
console.log('触发')
},1200)
},
methods: {
logsq() {
if (value.userSessionId == !'')
uni.navigateTo({
url: '../../subpkg/Sharepage/Sharepage'
});
},
login() {
if (this.checked == true) {
let that = this;
uni.getUserProfile({
desc: 'weixin',
success(res) {
let login = JSON.stringify(res.userInfo);
that.encryptedData = res.encryptedData;
that.iv = res.iv;
uni.showLoading({
title: '登陆中.....'
});
that.logs();
}
});
} else {
return uni.showToast({
title: '请勾选授权框',
icon: 'none'
});
}
},
logs() {
console.log('調用');
let that = this;
uni.login({
success: res => {
console.log(res, '获取ode?');
that.code = res.code;
uni.request({
url: that.$http + '/wechat/wxUserLogin', //仅为示例,并非真实接口地址。
data: {
code: that.code
},
method: 'POST',
header: {
miniCode: that.miniCode, //自定义请求头信息
encryptedData: that.encryptedData,
iv: that.iv
},
success: res => {
if (res.data.head.code == 200) {
let usinfo = JSON.stringify(res.data.data);
let key = usinfo.userSessionId;
this.$store.commit('Userinfo', res.data.data);
uni.setStorageSync('KEY', res.data.data.userSessionId);
uni.setStorage({
key: 'usinfo',
data: usinfo,
success: function() {
console.log('success');
}
});
uni.showToast({
title: '登录成功'
});
const timi = setTimeout(() => {
console.log(that.Url, 'urs???');
if (that.Url == '/subpkg/Sharepage/Sharepage') {
uni.navigateTo({
url: '/subpkg/Sharepage/Sharepage'
});
} else {
uni.reLaunch({
url: '/pages/home/home'
});
}
}, 2000);
} else {
uni.hideLoading();
// uni.showToast({
// title: '登录失败请重新登录',
// icon: 'error'
// });
}
}
});
}
});
},
}
};
</script>