uniapp授权登陆获取用户信息和code

在这里插入图片描述

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值