<template>
<view class="content">
<view class="text-area" @click="handleGetUserInfo" style="background-color: #007AFF;padding: 20rpx;color: #FFFFFF;">微信授权登陆</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello',
formData:null
}
},
onLoad() {
},
methods: {
handleGetUserInfo() {
this.onGetUserInfo().catch(error => {
console.log(error)
})
},
// 微信登录
async onGetUserInfo() {
const {
options
} = this;
// 获取用户信息
const userInfo = await this.onwechatInfos();
// 获取code
const code = await this.onwechatcodes();
// 拿到用户信息和code调用后端接口
// const data = await store.dispatch('loginAuthWechat', {
// code,
// oauth: 'MP-WEIXIN',
// userInfo
// });
},
// 获取用户信息
async onwechatInfos() {
return new Promise((resolve, reject) => {
// 判断应用的 API,回调,参数,组件等是否在当前版本可用。
if (!uni.canIUse('getUserProfile')) return null;
uni.getUserProfile({
lang: 'zh_CN',
desc: '获取用户相关信息',
success: res => {
console.log('用户同意了授权',res);
this.formData = res.userInfo;
return resolve(res.userInfo);
},
fail: err => {
uni.showToast({
title: '用户拒绝了授权',
icon: 'fail'
});
return reject(err);
},
});
})
},
// 获取code
async onwechatcodes() {
// 获取服务供应商
const [providerErr, providerData] = await uni.getProvider({
service: 'oauth'
});
if (providerErr) return uni.showToast({
title: '没有获取到服务商',
icon: "none"
})
const provider = providerData.provider;
if (provider.includes('weixin')) {
const options = {
provider: provider[0] //'weixin'
};
const logodata = await uni.login(options)
const [loginErr, loginData] = logodata;
console.log(loginData.code,'获取code')
if (loginErr) return uni.showToast({
title: loginErr,
icon: 'none'
}); //判断是否支持微信登录。
return loginData.code;
}
return null;
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>