微信小程序获取手机号码相关的

微信小程序获取手机号码有两种方式:
1.通过sessionKey,encryptedData,iv进行解密,可在前端和后端解密
2.可以通过传code,调api获取https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN

在onLoad中获取SessionKey可避免使用方法1第一次报错的情况。
方法2使用到了access_token,体验版和正式版都会去刷新access_token会使一端失效。可以将access_token存在redis,两个版本都连同一个redis。

<template>
	<view class="content">
		<button  class="btn-login" @getphonenumber="getPhoneNumber" open-type="getPhoneNumber">微信获取手机号码</button>
	</view>
</template>
<script>
/* 调后端的方法 start*/
import { getOpenIdAndSessionKey, getPhone} from "@/api/login.js"
/* 调后端的方法 end*/
	import { mapState } from 'vuex'
export default {
		data() {
			return {
				params:{
					encryptedData:'',
					iv:'',
					sessionkey:'',
					openid:'',
					code:'',
					phone:''
				}
			}
		},
		computed: {
			...mapState({
				phone:state => {
					return state.phone
				}
			})
		},
		onLoad: async function () {
		    this.getSessionKey()
		},
		methods: {
			async getSessionKey() {
				const _this = this
				uni.login({
					provider:'weixin',
					success(data) {
						getOpenIdAndSessionKey(data.code)
						.then(res => {
							_this.params.sessionkey = res.data.sessionKey
							_this.params.openid = res.data.openid
						})
					}
				})
			},
			getPhoneNumber(e){
				const _this = this
				if(e.detail.errMsg=='getPhoneNumber:ok'){
					this.params.code = e.detail.code;
					const { encryptedData, iv } = e.mp.detail;
					this.params.encryptedData = encryptedData
					this.params.iv = iv
					_this.getPhoneNum()
				}
			},
			getPhoneNum(){
				getPhone(this.params).then(res => {
					console.log(res)
					this.params.phone = res.data
				}).catch(error => {
				});
			}
		}
	}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值