uniapp中微信小程序获取用户信息与手机号

这段代码展示了如何在微信小程序中实现用户信息和手机号的获取。通过`<button open-type=getUserInfo>`和`<button open-type=getPhoneNumber>`监听事件,调用`wxGetUserInfo`和`wxGetPhone`方法。用户授权后,使用`uni.getUserProfile`获取用户信息,`decryptPhone`方法用于解密获取的手机号,并与后台交互。若用户拒绝授权,会显示错误提示。
<!-- #ifdef MP-WEIXIN -->
		<view>
			<button open-type="getUserInfo" @getuserinfo="wxGetUserInfo">登录</button>
		</view>

		<view>
			<button open-type="getPhoneNumber" @getphonenumber="wxGetPhone">获取手机号</button>
		</view>
		<!-- #endif -->
	//获取手机号
			wxGetPhone(e) {
				console.log("phone", e);
				if (!e.detail.code) {
					uni.showToast({
						title: '获取手机号失败',
						icon: 'none'
					})
					return;
				}
				that.decryptPhone(e.detail.code);

			},
			//解密手机
			decryptPhone(obj) {
				var that = this;
				//传给后台解密,获得手机号
				this.$api.getPhone({code:obj})
					.then(ss => {
						if (ss.code == 200) {
							console.log(ss)
						} else {
							uni.showToast({
								title: '获取手机号失败,请重试',
								icon: 'none'
							})
						}
					})
					.catch(ss => {
						uni.showToast({
							title: '获取手机号失败,请重试',
							icon: 'none'
						})
					})
			},
			// 获取用户信息
			wxGetUserInfo(e) {
				uni.showModal({
					title: '温馨提示',
					content: '亲,授权微信登录后才能正常使用小程序功能',
					success(res) {
						console.log(0)
						console.log(res)
						//如果用户点击了确定按钮
						if (res.confirm) {
							uni.getUserProfile({
								desc: '获取你的昵称、头像、地区及性别',
								success: res => {
									console.log(res);
									console.log(1);
								},
								fail: res => {
									console.log(2);
									console.log(res)
									//拒绝授权
									uni.showToast({
										title: '您拒绝了请求,不能正常使用小程序',
										icon: 'error',
										duration: 2000
									});
									return;
								}
							});
						} else if (res.cancel) {
							//如果用户点击了取消按钮
							console.log(3);
							uni.showToast({
								title: '您拒绝了请求,不能正常使用小程序',
								icon: 'error',
								duration: 2000
							});
							return;
						}
					}
				});
			},
			
UniApp 开发的微信小程序中实现获取用户手机号的功能,主要依赖于微信小程序的官方授权机制。以下是实现该功能的完整流程和关键步骤: ### 微信小程序获取用户手机号的核心流程 1. **用户授权请求** 微信小程序中,用户需要主动授权才能获取手机号码。可以通过 `button` 组件设置 `open-type="getPhoneNumber"`,触发授权请求。当用户点击按钮时,会弹出授权窗口,用户点击“允许”后,前端将收到加密的 `encryptedData` 和 `iv`,并将其发送到后端进行解密[^2]。 ```html <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">获取手机号</button> ``` 2. **前端获取 `code` 并发送至后端** 在用户授权后,前端需要通过 `uni.login` 接口获取登录凭证 `code`,并将其发送至后端服务器。`code` 是换取用户手机号的关键参数[^4]。 ```javascript uni.login({ provider: 'weixin', success: function (loginRes) { const code = loginRes.code; // 将 code 发送到后端 uni.request({ url: 'https://yourdomain.com/api/wechat/phone', method: 'POST', data: { code: code }, success: (res) => { console.log('获取手机号成功:', res.data); } }); } }); ``` 3. **后端解密获取手机号** 后端接收到 `code` 后,首先需要通过微信接口 `https://api.weixin.qq.com/sns/jscode2session` 获取 `session_key` 和 `openid`。然后,使用 `session_key` 对前端传来的 `encryptedData` 和 `iv` 进行解密,最终获取用户的手机号码。 以 Java 为例,后端可以使用如下代码调用微信接口获取 `session_key` 和 `openid`: ```java String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code"; // 替换为实际的 AppID、AppSecret 和 code ``` 解密 `encryptedData` 时,使用 `session_key` 和 `iv` 进行 AES 解密,并提取手机号字段。 4. **安全注意事项** - 确保 `session_key` 不在前端暴露,仅在后端进行处理。 - 保证 `encryptedData` 和 `iv` 的传输安全,避免被篡改。 - 手机号属于用户敏感信息,需遵循《微信小程序用户隐私保护指引》,并确保符合相关法律法规要求[^1]。 ### 实战代码示例 #### 前端UniApp) ```javascript methods: { getPhoneNumber(e) { if (e.detail.errMsg === 'getPhoneNumber:ok') { const encryptedData = e.detail.encryptedData; const iv = e.detail.iv; uni.login({ provider: 'weixin', success: (loginRes) => { const code = loginRes.code; uni.request({ url: 'https://yourdomain.com/api/wechat/phone', method: 'POST', data: { code: code, encryptedData: encryptedData, iv: iv }, success: (res) => { console.log('手机号:', res.data.phoneNumber); } }); } }); } } } ``` #### 后端(Java Spring Boot) ```java @PostMapping("/wechat/phone") public ResponseEntity<String> getPhoneNumber(@RequestBody Map<String, String> payload) { String code = payload.get("code"); String encryptedData = payload.get("encryptedData"); String iv = payload.get("iv"); // 1. 获取 session_key String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=" + code + "&grant_type=authorization_code"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); JsonNode sessionData = objectMapper.readTree(response.getBody()); String sessionKey = sessionData.get("session_key").asText(); // 2. 使用 sessionKey 解密 encryptedData byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey); byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData); byte[] ivBytes = Base64.getDecoder().decode(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); byte[] decrypted = cipher.doFinal(encryptedDataBytes); String phoneNumberData = new String(decrypted, StandardCharsets.UTF_8); JsonNode phoneData = objectMapper.readTree(phoneNumberData); String phoneNumber = phoneData.get("phoneNumber").asText(); return ResponseEntity.ok(phoneNumber); } ``` ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这次最后一次熬夜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值