微信小程序登陆
/*** 小程序登陸*/public function wxcodelogin(){$code = $_POST['code'];$encryptedData = $_POST['encryptedData'];$iv = $_POST['iv'];if(!$iv || !$encryptedData || !$code){$this->weberror(self::THIS_ACTION_ERROR,'參數(shù)錯(cuò)誤');}// $this->websuccess(1,"data",array('iv'=>$iv,'encryptedData'=>$encryptedData));$wxAppId = "";$wxAppSecret = "";$wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';$wxLoginUrl = sprintf($wxUrl,$wxAppId,$wxAppSecret,$code);$result = $this->curl_http($wxLoginUrl);$wxResult = json_decode($result,true);if(empty($wxResult)){$this->weberror(self::THIS_ACTION_ERROR,'獲取sesssion_key及openId時(shí)異常,微信內(nèi)部錯(cuò)誤');}else{$loginFail = array_key_exists('errcode', $wxResult);if ($loginFail) {$this->weberror(self::THIS_ACTION_ERROR,"errcode");} else {//拿到openid$unionid = $wxResult['unionid'];$data = $this->WXBizDataCrypt($wxResult['session_key'],$encryptedData,$iv);if (!$data){$this->weberror(self::THIS_ACTION_ERROR,"獲取信息error1");}$phoneResult = json_decode($data,true);//到數(shù)據(jù)庫看一下這個(gè)unionid是否存在$user = M('user')->where(array('wx_unionid'=>$unionid))->find();//如果存在,則不處理,如果不存在,新增一條user記錄if($user){$this->memberlogin($user['mobile'],$user['password'],get_client_ip());}else{$user = M('user')->where(array('mobile'=>$phoneResult['phoneNumber']))->find();if($user){$save = array('wx_unionid'=>$unionid);M('user')->where(array('mobile'=>$phoneResult['phoneNumber']))->save($save);$this->memberlogin($user['mobile'],$user['password'],get_client_ip());}else{$newAdd['wx_unionid'] = $unionid;$newAdd['mobile'] = $phoneResult['phoneNumber'];$newAdd['password'] = "";$newid = M('user')->add($newAdd);if ($newid) {$newUser = M('user')->where(array('mobile'=>$phoneResult['phoneNumber']))->find();$this->get_reward_goldcoin($newid,'reg_reward');//注冊(cè)獎(jiǎng)勵(lì)$this->memberlogin($newUser['mobile'],$newUser['password'],get_client_ip());}else{$this->weberror(self::REGISTER_ERROR,'登陸失敗');}}}}}}/*** @param $sessionKey 微信端* @param $encryptedData 客戶端給的* @param $iv 客戶端端給的* @return string*/public function WXBizDataCrypt($sessionKey,$encryptedData,$iv){$appid = '';if (strlen($sessionKey) != 24) {$this->weberror(self::THIS_ACTION_ERROR,"sessionKey獲取信息error");}$aesKey=base64_decode($sessionKey);if (strlen($iv) != 24) {$this->weberror(self::THIS_ACTION_ERROR,"iv獲取信息error");}$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 ){$this->weberror(self::THIS_ACTION_ERROR,"解密信息error");}if( $dataObj->watermark->appid != $appid ){$this->weberror(self::THIS_ACTION_ERROR,"appid信息error");}return $result;}
?
總結(jié)
- 上一篇: 2021-01-14
- 下一篇: uniapp一键登陆(php)