获取用户手机号码需要6个必要条件,

1.必须是企业账号,否则是无权限获取的用户手机号码的,企业账号你需要获取到你微信小程序的appid和小程序密钥(这个后面要用到)

查看appid和小程序密钥的地址:

小程序icon-default.png?t=N7T8https://mp.weixin.qq.com/wxamp/devprofile/get_profile?token=197451409&lang=zh_CN

2.调用uni.login()获取到用户的code

3.获取到用户code值之后调用uni.request()请求微信的服务器,拿到用户的session_key

4.通过微信提供的获取微信手机号的方法getphonenumber拿到encryptedData iv两个字段的内容

5.用户授权完毕之后我们可以拿到encryptedData值和iv值(这两个值用于解密)

6.所有值全部都可以拿到之后,通过微信提供的解密方法:可以拿到最终的手机号

微信提供的方法在:

服务端获取开放数据 | 微信开放文档微信开发者平台文档icon-default.png?t=N7T8https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html

找到WXBizDataCrypt.js放入自己的文件夹中,所有条件满足之后就可以正常走通了,此下面代码可以直接拿来使用,样式随便乱写的,自己调整

<template>
	<view class="bigBox">
		<view class="box">
			<input v-model="phone" />
			<view class="useWexin">
				<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" plain="true">获取手机号</button>
			</view>
		</view>
	</view>



</template>

<script>
	import WXBizDataCrypt from "../../utils/WXBizDataCrypt.js"
	export default {
		data() {
			return {
				phone: "",
				phone_iv: "",
				js_code: "",
				session_key: "",
			}
		},
		onShow() {
			this.go()
		},
		methods: {
			go() {
				uni.login({
					provider: 'weixin',
					success: res => {
						console.log(res)
						this.js_code = res.code
						uni.request({
							url: 'https://api.weixin.qq.com/sns/jscode2session', // 请求微信服务器
							method: 'GET',
							data: {
								appid: '你的小程序的APPID', //你的小程序的APPID
								secret: '你的小程序秘钥secret, ', //你的小程序秘钥secret,  
								js_code: this.js_code, //uni.login 登录成功后的code
								grant_type: 'authorization_code' //此处为固定值
							},
							success: (res) => {
								console.log('获取信息', res.data);
								this.session_key = res.data.session_key

							}
						});
					}
				});
			},
			getPhoneNumber(res) { // 获取手机号
				this.phone_encryptedData = res.detail.encryptedData //用于解密
				this.phone_iv = res.detail.iv // 用于解密
				console.log(res, "获取手机号需要的参数");
				let pc = new WXBizDataCrypt('你的小程序的APPID', this.session_key);
				let data = pc.decryptData(this.phone_encryptedData, this.phone_iv);
				console.log(data);
				if (data.phoneNumber != '') {
					this.phone = data.phoneNumber
				}
			}
		}
	}
</script>

<style lang="less">
	.bigBox {
		width: 100vw;
		height: 100vh;
		background-color: #F1F2F6;
		display: flex;
		align-items: center;
		justify-content: center;

		.box {
			width: 70vw;
			height: 30vh;

			input {
				border: 2rpx solid black;
			}

			.useWexin {
				width: 50%;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 40rpx auto;
			}
		}

	}
</style>

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐