微信小程序授權獲取用戶手機號碼

微信小程序授權獲取用戶手機號碼

  1. 第一步:小程序通過調用wx.login()方法,來拿到用戶登錄憑證code。
wx.login({    
    success:function(res){
        console.log('loginCode:', res.code)
    } 
});
  1. 第二步:將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沒有失效的情況下後臺會獲的用戶的openidsession_key

  2. 第三步:用戶通過getPhoneNumber組件,引導用戶確認授權。拿到encryptedDataiv

  3. 第四步:將encryptedDataiv傳給後臺,後臺通過解密算法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]);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章