小程序手机号注册php,微信小程序授权获取用户手机号码

第一步:小程序通过调用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去解密,即可获得微信信息以及手机号码。

ebccb9ee7f891c62840cd931b9d26b04.png

相关代码:// 加密数据解密算法

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]);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值