
首先,看一下微信的登入流程圖 (推薦學習:PHP視訊教程)
步驟:在用戶端擷取目前登入微信使用者的登入憑證(code)。使用該憑證向微信伺服器換取該微信使用者的唯一辨別(openid)和會話密鑰(session_key)。引用微信加解密,擷取使用者資訊。
注意:
1.未進行登入驗證。
2.引用加解密是,路徑要正确。//未授權使用者,請求微信接口,進行授權,擷取使用者資訊
public function saveUser()
{
$appid = "自己的appid" ;
$code = $this->input->post('code');
if (empty($code)){
return $this->fail('','code不能為空');
}
$encryptedData = $this->input->post('encryptedData');
if (empty($encryptedData)){
return $this->fail('','encryptedData不能為空');
}
$iv = $this->input->post('iv');
if (empty($iv)){
return $this->fail('','iv不能為空');
}
$apiData = $this->getApiData($code);
if(!isset($apiData['errcode'])){
$sessionKey = $apiData['session_key'];
//擷取sessionKey 進行解密
$userifo = new WXBizDataCrypt($appid, $sessionKey);
$errCode = $userifo->decryptData($encryptedData, $iv, $data );
//儲存
if ($errCode == 0) {
$data = json_decode($data,true);
$userData = [
'nickname' =>$data['nickName'],
'headimg' =>$data['avatarUrl'],
'unionid' =>$data['unionId'],
'openid' =>$data['openId'],
'c_time' =>time(),
];
$result = $this->AppUserModel->get(['openid'=>$data['openId']]);
if ($result){
$this->AppUserModel->update($userData,['openid'=>$data['openId']]);
$returnData['uid']=$result['id'];
return $this->success($returnData,'已授權');
}else{
$userDataId = $this->AppUserModel->add($userData);
if ($userDataId){
$returnData['uid']=$userDataId;
return $this->success($returnData,'已授權');
}else{
return $this->fail('','授權失敗');
}
}
}
}else{
return $this->fail($apiData,'擷取使用者資訊失敗');
}
}//擷取openid
public function getApiData($code)
{
$appid = "自己的appid" ;
$secret = "自己的secret";
$URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
$apiData=file_get_contents($URL);
return json_decode($apiData,true);
}
未避免多次擷取。在登入之前先進行驗證。//擷取使用者是否已經授權
public function userId()
{
$code = $this->input->get('code');
if (empty($code)){
return $this->fail('','code不能為空');
}
$apiData = $this->getApiData($code);
if (!isset($apiData['errcode'])){
$openID= $apiData['openid'];
$userData = $this->AppUserModel->get(['openid'=>$openID]);
if (empty($userData)) {
return $this->fail('','未授權');
}else{
//這邊儲存sessionKey ,友善後面手機号碼授權
$sessionKey = $apiData['session_key'];
$mc = &load_cache('redis');
$mc->save('session_key', $sessionKey, 3600);
$returnData = [
'uid'=>$userData['id'],
'type'=>$userData['type']
];
return $this->success($returnData,'已授權');
}
}else {
return $this->fail('','擷取openid失敗');
}
}