做这个一键获取手机号就遇到了第一次获取不到,后台解密不出
甚至做到能让第一次获取,但第二次点击却不能获取了,后台炸了
现在通过这个全给你解决掉

请添加图片描述

<button class="one" open-type="getPhoneNumber" @getphonenumber="getphone">一键获取</button>

data(){
	return{
		code:'',
	}
},
onLoad() {
	//一打开就请求code,解决第一次不能获取手机号
	var that = this;
	uni.login({
		provider: 'weixin',
		success(res) {
			that.code = res.code;
		}
	})
},
methods:{
	//获取手机号
	getphone(e){
		if (!e.detail.iv) {
			uni.showToast({
				title:'获取手机号失败',
				icon:'none'
			})
			return;
		}
		var that = this;
		//验证code值是否过期
		uni.checkSession({
			success(val){
				if(val.errMsg == 'checkSession:ok'){
					var obj = {
						code:that.code,
						iv:e.detail.iv,
						encryptedData:e.detail.encryptedData
					}
					that.decryptPhone(obj);
				}else{
					uni.login({
						provider: 'weixin',
						success(res) {
							let code = res.code;
							var obj = {
								code,
								iv:e.detail.iv,
								encryptedData:e.detail.encryptedData
							}
							that.decryptPhone(obj);
						}
					})
				}
			}
		})

	},
	//解密手机号
	decryptPhone(obj){
		var that = this;
		//传给后台解密,获得手机号
		this.$api.getPhone(obj)
		.then(ss =>{
			if(ss.code == 200){
				console.log(ss)
			}else{
				uni.showToast({
					title:'获取手机号失败,请重试',
					icon:'none'
				})
			}
		})
		.catch(ss =>{
			uni.showToast({
				title:'获取手机号失败,请重试',
				icon:'none'
			})
		})
	}
 }

获取用户信息

<button open-type="getUserInfo" @tap="getUserProfile" size="mini"> 获取头像昵称 </button>


getUserProfile(e) {
   // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
   // 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
   wx.getUserProfile({
    desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
    success: (res) => {
     console.log(res);
     console.log(res.userInfo.avatarUrl);//获取用户微信头像
     console.log(res.userInfo.nickName);//获取用户微信名
    }
   })
},
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐