public function weixinlogin()
{
//接收前端传过来的code 偏移量
$get = I('get.');
// var_dump($get);exit;
//获取session_key
$params['appid']= C("appid");
$params['secret']= C("secret");
$params['js_code']= define_str_replace($get['code']);
$params['grant_type']= 'authorization_code';
$http_key = curl_post_contents('https://api.weixin.qq.com/sns/jscode2session', $params, 'GET');
$session_key = json_decode($http_key,true);
// var_dump($session_key);exit;
if(!empty($session_key['session_key'])){
$openid=$session_key['openid'];
$encryptedData= urldecode($get['encryptedData']);
$iv = define_str_replace($get['iv']);
$errCode = decryptData($params['appid'],$session_key['session_key'],$encryptedData,$iv);//获取unioID
$unioId=$errCode['unionId']; //打印获取的数据
//查询数据库
$userinfo= getUserinfo($openid);
//判断数据库中是否有该用户的数据
if(!$userinfo){
//如果没有就添加
$insertInfo['openid'] = $openid;
$insertInfo['nickname'] = $get['nickname'];
$insertInfo['face'] = $get['face'];
$insertInfo['unionid'] = $unioId;
$insertInfo['sex'] = $get['sex'];
$insertInfo['addtime'] = date("Y-m-d H:i:s",time());
$insertInfo['updatetime'] = date("Y-m-d H:i:s",time());
$res = M("wxinfo")->add($insertInfo);
}else{
//否则就修改最后登入时间
$where['openid']=$openid;
$updatetime['updatetime'] = date("Y-m-d H:i:s",time());
M("wxinfo")->where($where)->save($updatetime);
}
session("openid",$openid);
$encryption = array("openid"=>$openid,'unionid'=>$unioId,"session_key"=>$session_key['session_key']);
$session3rd = session_3rd();
$data['session3rd'] = $session3rd;
S($session3rd,$encryption);
$this->ajaxReturn(array('status'=>200,'data'=>array("token"=>$session3rd)));
}else{
// echo '获取session_key失败!';
$this->ajaxReturn(array('status'=>400,'data'=>array("msg"=>"获取session_key失败!")));
}
}
方法
//获取unionID
function decryptData( $appid , $sessionKey, $encryptedData, $iv ){
$OK = 0;
$IllegalAesKey = -41001;
$IllegalIv = -41002;
$IllegalBuffer = -41003;
$DecodeBase64Error = -41004;
if (strlen($sessionKey) != 24) {
return $IllegalAesKey;
}
// $str = base64_decode(str_replace(" ","+",$_GET['str']));
$aesKey=base64_decode(str_replace(" ","+",$sessionKey));
// var_dump($aesKey);exit;
if (strlen($iv) != 24) {
return $IllegalIv;
}
$aesIV=base64_decode(str_replace(" ","+",$iv));
$aesCipher=base64_decode(str_replace(" ","+",$encryptedData));
$result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
$dataObj=json_decode( $result );
// var_dump($dataObj);exit;
if( $dataObj == NULL )
{
return $IllegalBuffer;
}
if( $dataObj->watermark->appid != $appid )
{
return $DecodeBase64Error;
}
$data = json_decode($result,true);
return $data;
}
//session_3rd();
function session_3rd($length = 16) {
//生成第三方3rd_session
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
//define_str_replace
function define_str_replace($data)
{
return str_replace(' ','+',$data);
}