前言
前言:最近在用uni-app开发小程序,产品给到需求是默认登录绑定手机号。现在需要登录直接绑定手机号,所以研究了一下流程。看到网上有些文章写到getPhoneNumber拿回手机号,然后还需要触发wx.login拿回用户个人信息,其实给我前期造成了一些误解。自己写一篇文章记录一下。楼主用的uni-app,非此框架将相应的api换成wx开头即可
一、实现方法
调用getPhoneNumber拿回encryptedData和iv,然后静默调用uni.login拿回code,将这三个参数一起传给后台,让后台去调微信接口拿回session_key和openid,且解密出encryptedData里的手机号。 至此我们实现用户登录绑定手机号,至于用户头像、昵称,微信有开放数据,我们可以直接用代码获取。下面给出代码
二、使用步骤
1.唤起微信手机号授权
代码如下:
<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" withCredentials="true">
<div >微信用户一键登录</div>
</button>
getPhoneNumber(e){
uni.login({
success: (res) => {
this.code = res.code;
if (this.code) {
console.log("验证登陆请求");
if(e.detail.errMsg == "getPhoneNumber:ok"){
console.log("用户点击了接受", e)
this.phone = e.detail.encryptedData;
this.iv = e.detail.iv;
this.getAccessToken(); // 将code、phone、iv发给后台,让后台解密手机号,拿回openid和session
}else{
console.log("用户点击了拒绝")
}
}
},
fail: () => {
this.$refs.toast.hide();
this.$refs.toast.error("登录失败!请重新授权登录!");
},
});
},
2.获取微信开放数据: open-data
获取open-data,这里只是举个例子拿用户头像
具体可以获取open-data的类型可以去官网查看,指路: https://developers.weixin.qq.com/miniprogram/dev/component/open-data.html
<open-data type="userAvatarUrl" mode="aspectFill" v-else></open-data>
总结
以上,用户只需要一次授权,就可以实现既绑定了手机号,又显示出头像和用户昵称。
参考文章:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
https://developers.weixin.qq.com/minigame/dev/guide/open-ability/login.html