微信小程序获取用户手机号
1.getPhoneNumber这个组件通过button来实现(别的标签无效)。将button中的open-type=“getPhoneNumber”,并且绑定bindgetphonenumber事件获取回调。
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
<input type='text' name='phone' value='{{phone}}'></input>
2.在使用这个组件之前必须先调用login接口,如果没有调用login点击button时会提示先调用login。
* 如果 后面的方法 getPhoneNumber 已添加login接口,这里的onlaunch方式就不用重复添加了。
onLaunch: function () { wx.login({ success: function (res) { if (res.code) { //发起网络请求 console.log(res.code) } else { console.log('获取用户登录态失败!' + res.errMsg) } } }); },
3.通过bindgetphonenumber绑定的事件来获取回调。回调的参数有三个,
errMsg:用户点击取消或授权的信息回调。
iv:加密算法的初始向量(如果用户没有同意授权则为undefined)。
encryptedData: 用户信息的加密数据(如果用户没有同意授权同样返回undefined)
getPhoneNumber:function(e){ if(e.detail.iv&&e.detail.encryptedData){ // console.log(e.detail.iv) // console.log(e.detail.encryptedData) wx.login({ success:(res)=>{ wx.request({ url:`https://SERVER/Api/Index/get_session_key` ,header:{'content-type':'application/json'} ,data:{ code:res.code } ,success:(res)=>{ console.log(res) let session_key=res.data.session_key wx.request({ url:`https://SERVER/Api/Index/decryptData2` ,header:{'content-type':'application/json'} ,data:{ 'encryptedData':encodeURIComponent(e.detail.encryptedData) ,'iv':e.detail.iv ,'session_key':session_key } ,success:(res)=>{ console.log(res.data) if(!res.data){ console.log('获取失败,请重试') wx.showToast({ title:'网络错误,请重试…' ,icon:'none' }) }else{ this.setData({ phone:res.data.purePhoneNumber }) } } }) } }) } }) }else{ console.log('拒绝获取手机号码') } }
4、后端页面代码
function get_session_key($code){ $url='https://api.weixin.qq.com/sns/jscode2session?app&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $res = json_decode($output, true); $out=[ 'session_key'=>$res[session_key], ]; $this->ajaxReturn($out); }
function decryptData2($encryptedData,$iv,$session_key){
$aesKey=base64_decode($session_key);
$aesIV=base64_decode(str_replace(' ','+',$iv));
$aesCipher=base64_decode(urldecode($encryptedData));
$result=openssl_decrypt($aesCipher,"AES-128-CBC",$aesKey,1,$aesIV);
$this->ajaxReturn(jsondecode($result));
}