先去https://open.tencent.com/ 里面的QQ互联申请,成为开发者后添加网站应用进行审核。
应用必须在需要用到的网站先添加QQ登录图标,不然会审核失败
前端代码:
<a onclick='toQzoneLogin()' openwindowheight="350" openwindowwidth="450" data-third="qq" class="qq icon" pbtag="qq" pbflag="头部" title="QQ登录"></a>
<script type="text/javascript">
var childWindow;
function toQzoneLogin()
{
childWindow = window.location.href = "接收回调的地址"; //这个地址必须在QQ互联里面对应的应用配置好,可多个
//childWindow = window.open("接收回调的地址","TencentLogin","width=450,height=320,menubar=0,scrollbars=1, resizable=1,status=1,titlebar=0,toolbar=0,location=1"); 新窗口打开
}
</script>
后端代码:
public function qq_login()
{
header("Content-Type: text/html;charset=utf-8");
$qqConfig = C('THINK_SDK_QQ');
$appid = $qqConfig['APPID'];
$appkey = $qqConfig['APPKEY'];
$url = $qqConfig['CALLBACK'];
//1:获取code
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$ret_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=".$appid."&redirect_uri=".urlencode($url)."&state=".$_SESSION['state'];
echo("<script> top.location.href='".$ret_url."'</script>");
}
//2:通过code获取accesstoken
if($_REQUEST['state'] == $_SESSION['state'] || 1) {
$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"."client_id=".$appid."&redirect_uri=".urlencode($url)."&client_secret=".$appkey."&code=".$code;
$response = file_get_contents($token_url);
//如果用户临时改变主意取消登录,返回true!==false,否则执行step3
if (strpos($response, "callback") !== false) {
$lpos = strpos($response, "(");
$rpos = strrpos($response, ")");
$response = substr($response, $lpos + 1, $rpos - $lpos -1);
$msg = json_decode($response);
if (isset($msg->error)) {
echo "<h3>error:</h3>".$msg->error;
echo "<h3>msg :</h3>".$msg->error_description;
exit;
}
}
//3:使用accesstoken来获取用户openid
$params = array();
parse_str($response, $params);//数据参数变量化
$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token'];
$str = file_get_contents($graph_url);
if (strpos($str, "callback") !== false) {
$lpos = strpos($str, "(");
$rpos = strrpos($str, ")");
$str = substr($str, $lpos + 1, $rpos - $lpos -1);
}
$user = json_decode($str,true);//存放返回的数据 client_id ,openid
if (isset($user->error)) {
echo "<h3>error:</h3>".$user['error'];
echo "<h3>msg :</h3>".$user['error_description'];
exit;
}
//4:使用openid和accesstoken获取用户信息
$user_data_url = "https://graph.qq.com/user/get_user_info?access_token={$params['access_token']}&oauth_consumer_key={$app_id}&openid={$user['openid']}&format=json";
$userInfo = file_get_contents($user_data_url);//获取到的用户信息
$userInfo = json_decode($userInfo,true);
if($userInfo){
//以下为授权成功后的自定义操作
}else{
echo '未知错误';
}
}else{
echo("The state does not match. You may be a victim of CSRF.");
}
}