腾讯接口文档地址:http://wiki.connect.qq.com/
第一步生成一个state上传给腾讯接口并保存到本地用于防止恶意攻击
如下(可自选生成方式):
$value = time().rand(100000,999999);
Cache::write('state'.$value,'xxx','r5m');
第二步带着参数请求腾讯qq快捷登录接口:
如下:参数包括申请的应用appid和设置的redirect_uri以及第一步生成的state
$this->redirect('https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id='.$app_id.'&redirect_uri='.urlencode($url_qq).'&state='.$value)
其中要对redirect_uri进行urlencode()
第三步:
在设置的第二步的redirect_uri中和腾讯进行信息交流获取数据
代码如下(本例为cakephp框架):
$code = $this->request->getQuery('code');
$state = $this->request->getQuery('state');
if(empty($code)){
$this->G->error("login_canceled");
return null;
}
$flag = 'state'.$state;
$flag_value = Cache::read($flag,'r5m');
if($flag_value != 'xxx'){
$this->G->error($state."login_state_error".$flag_value);
return null;
}
$http = new Client();
$response = $http->get('https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id='.$appid.'&client_secret='.$secret.'&code='.$code.'&redirect_uri='.$urlencode($url_qq));
if(strpos($response->body,'error') !==false){
$this->G->error("login_error");
return null;
}
$access_token = explode('&',$response->body)[0];
$response1 = $http->get('https://graph.qq.com/oauth2.0/me?'.$access_token);
if(strpos($response1->body,'error') !==false){
$this->G->error("login_error");
return null;
}
$arr = str_replace('callback( ','[',$response1->body);
$arr = str_replace(' );',']',$arr);
$arr = json_decode($arr);
$response2 = $http->get('https://graph.qq.com/user/get_user_info?'.$access_token.'&oauth_consumer_key='.$appid.'&openid='.$arr[0]->openid);
$response2->body = json_decode('['.$response2->body.']') ;
if($response2->body[0]->ret !== 0){
$this->G->error("login_userinfo_error");
return null;
}
此处$response2->body的值如下图:
return $this->redirect(成功后跳转的地址【如网站首页】);