微信小程序授权获取用户手机号码
- 第一步:小程序通过调用wx.login()方法,来拿到用户登录凭证code。
wx.login({
success:function(res){
console.log('loginCode:', res.code)
}
});
-
第二步:将code传给后台,后台通过登录凭证code获取 session_key 和 openid
获取方法如下:用你的小程序的appid,secret,code来请求下面的api(请在后台处理)https://api.weixin.qq.com/sns/jscode2sessionappid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code在确保code没有失效的情况下后台会获的用户的openid和session_key -
第三步:用户通过getPhoneNumber组件,引导用户确认授权。拿到encryptedData和iv。
-
第四步:将encryptedData和iv传给后台,后台通过解密算法https://mp.weixin.qq.com/debug/wxadoc/dev/api/signature.html)将用户的手机号解析出来。
这个时候后台把接口解析的手机号返回给你,就拿到了~对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充。对称解密的目标密文为 Base64_Decode(encryptedData)。对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 是16字节。对称解密算法初始向量 为Base64_Decode(iv),其中iv由数据接口返回。
总结:
先通过小程序代码获取到code,然后将获取code传给后台,这个时候还没获取到phone,需要根据传过来的code获取到openid和session_key,然后根据这些参数appid和session_key去解密,即可获得微信信息以及手机号码。
相关代码
// 加密数据解密算法
public function decryption(){
$xcx['app_id'] = '';
$xcx['app_secret'] = '';
$code = input('code');
$encryptedData = input('encryptedData');
$iv = input('iv');
$unionId = '';
$unifo = [];
// expires_in,openid,session_key
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$xcx['app_id']."&secret=".$xcx['app_secret']."&js_code=".$code."&grant_type=authorization_code";
// $content = file_get_contents($url);
$content = file_get_contents_by_curl($url);
$res = object_array(json_decode($content)); //返回openid,expires_in,session_key
if(!isset($res)) return json(['code'=>1,'msg'=>'请求失败','res'=>$res,'url'=>$url,'content'=>$content,'code2'=>$code,'app_id'=>$xcx['app_id'],'secret'=>$xcx['app_secret']]);
if(isset($res['errcode'])){
return json(['code'=>1,'errmsg'=>$res['errmsg']]);
}
if(empty($res['openid'])) return json(['code'=>1,'msg'=>'获取openid错误']);
if(empty($res['session_key'])) return json(['code'=>1,'msg'=>'session_key获取失败']);
$pc = new WXBizDataCrypt($xcx['app_id'], $res['session_key']);
$errCode = $pc->decryptData($encryptedData, $iv, $data );
if ($errCode == 0) {
$arr = object_array(json_decode($data));
return json(['code'=>0,'msg'=>'解密成功','arr'=>$arr]);
} else {
return json(['code'=>1,'msg'=>'获取unionId错误','error'=>$errCode,'openid'=>$res['openid'],'app_id'=>$xcx['app_id'],'iv'=>$iv,'encryptedData'=>$encryptedData]);
}
}