1.前端按钮
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" class="btn">微信手机号</button>
2.js
getPhoneNumber (e) { var _this = this; let openid = wx.getStorageSync('openid'); let session_key = wx.getStorageSync('session_key'); App._post('wechat/get_phone' , { openid: openid, session_key: session_key, encryptedData:e.detail.encryptedData, iv:e.detail.iv, } , function (result) { if(result.status==1){ //成功 } } ) },
3.服务器后端
//-获取微信手机号 public function get_phone() { $status=0;$message='失败...';$http_status = 200;$data=[]; $post=$this->request->param(); $appid = self::$appid; //小程序ID $sessionKey = $post['session_key']; $encryptedData = $post['encryptedData']; $iv = $post['iv']; $errCode = $this->decryptData($appid, $sessionKey,$encryptedData, $iv, $data ); if ($errCode==0) { $status=1; $message='成功...'; return self::response_data($status,$http_status,$message,$data); }else{ return self::response_data($status,$http_status,$message,$errCode); } return $data; }
/** * 检验数据的真实性,并且获取解密后的明文. * @param $encryptedData string 加密的用户数据 * @param $iv string 与用户数据一同返回的初始向量 * @param $data string 解密后的原文 * * @return int 成功0,失败返回对应的错误码 */ public function decryptData($appid,$sessionKey, $encryptedData, $iv, &$data ) { if (strlen($sessionKey) != 24) { return '-41001'; } $aesKey=base64_decode($sessionKey); if (strlen($iv) != 24) { return '-41002'; } $aesIV=base64_decode($iv); $aesCipher=base64_decode($encryptedData); $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV); $dataObj=json_decode( $result ); if( $dataObj == NULL ) { return '-41003'; } if( $dataObj->watermark->appid != $appid ) { return '-41004'; } $data = $dataObj; }