<template>
<view class="login">
<image src="../static/icon/logo.png" mode="" class="logo"></image>
<view class="title">标题</view>
<button type="default" open-type="getUserInfo" @getUserInfo="getUserInfo" class="ac">微信账号一键登录</button>
<view class="bom">登录代表您已同意<text>《用户服务协议》《隐私权政策》</text></view>
</view>
</template>
<script>
export default {
components: {},
data() {
return {
time: null,
getSettingShow: true, //授权按钮
wxLogin: {
encrypted_data: '',
openid: '',
iv: '',
invite_code: '', //推荐人id
}
}
},
onLoad(option) {
if (option.invite_code) {
this.wxLogin.invite_code = option.invite_code;
}
},
onShow() {
//微信登录
// #ifdef MP-WEIXIN
this.time = setInterval(() => {
this.getSetting().then(res => {
this.getSettingShow = res; // true 已经授权,
if (this.getSettingShow) {
clearInterval(this.time)
uni.showLoading({
title: '正在登录',
mask: true,
});
uni.login({
provider: 'weixin',
success: (res) => {
if (res.errMsg == "login:ok") {
//微信授权
this.$http.post("/api/user/wechatuserauth", {
authcode: res.code
}).then(res => {
console.log(res);
if (res.code == 0) {
if (res.data.openid) {
console.log('1')
// 获取用户信息
uni.getUserInfo({
provider: 'weixin',
success: (val) => {
if (val.errMsg == 'getUserInfo:ok') {
this.wxLogin.iv = val.iv;
this.wxLogin.encrypted_data = val.encryptedData;
this.wxLogin.openid = res.data.openid;
// 授权登录
this.$http.post("/api/user/wechatuserinfo", {
openid: this.wxLogin.openid,
iv: this.wxLogin.iv,
encrypted_data: this.wxLogin.encrypted_data,
// invite_code: 'UYEZQT',
invite_code:this.wxLogin.invite_code,
}).then(e => {
if (e.code == 0) {
uni.setStorageSync('userInfo', e.data);
uni.setStorageSync('access_token', e.data.token);
uni.hideLoading();
this.goBack(1)
}
})
}
},
});
} else {
console.log('2')
uni.setStorageSync('userInfo', res.data);
uni.setStorageSync('access_token', res.data.token);
uni.hideLoading();
this.goBack(1)
}
}
})
}
}
});
}
})
}, 1000)
// #endif
},
methods: {
//查询是否授权
getSetting() {
return new Promise((req, rej) => {
uni.getSetting({
success(res) {
if (!res.authSetting['scope.userInfo']) {
console.log("未授权");
req(false)
} else {
console.log("已授权");
req(true)
}
}
})
})
},
//页面跳转
goBack(name) {
if (name == 1) {
uni.switchTab({
url: '/pages/index',
animationType: 'pop-out',
animationDuration: 300
})
} else {
uni.navigateTo({
url: name,
animationType: 'pop-in',
animationDuration: 300
})
}
},
},
}
</script>
<style scoped lang="scss">
.login {
.logo {
display: block;
width: 200rpx;
height: 200rpx;
margin: 120rpx auto 70rpx;
}
.title {
text-align: center;
font-size: 36rpx;
font-weight: bold;
color: #2E3155;
}
button {
display: block;
width: 690rpx;
height: 80rpx;
margin: 20rpx auto;
background: #02CF8C;
border-radius: 10rpx;
font-size: 30rpx;
font-weight: bold;
color: #fff;
}
.bom {
position: fixed;
left: 0;
bottom: 10px;
width: 100%;
text-align: center;
font-size: 30rpx;
color: #2E3155;
text {
color: #02CF8C;
}
}
}
</style>
uniapp:微信小程序:授权登录
最新推荐文章于 2024-05-08 18:39:40 发布