官方的SDK太复杂了,我们一起来做一个精简版的QQ登录,本人不是写博客的料,大家将就看吧,哈哈,一言不合咱就直接上代码!
首先我们先创建一个php格式的配置文件(config.php),用来存储我们的配置。
<?php //应用的APPID $app_id = "xxx"; //应用的APPKEY $app_secret = "xxx"; //成功授权后的回调地址 $my_url = "https://xxx.com/oauth/callback.php"; function getCurl($url){//get https的内容 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//不输出内容 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $result = curl_exec($ch); curl_close ($ch); return $result; } ?>
然后我们就开始了,创建一个login.php,我们完成后,QQ登录按钮直接链接到它就可以了。
<?php session_start(); require_once("config.php"); //state参数用于防止CSRF攻击,成功授权后回调时会原样带回 $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //拼接URL $dialog_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=" . $_SESSION['state']; echo("<script> top.location.href='" . $dialog_url . "'</script>"); ?>
接下来创建一个处理回调的文件 callback.php
<?php session_start(); require_once("config.php"); //Step2:通过Authorization Code获取Access Token if($_GET['state'] == $_SESSION['state']) { //拼接URL $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&". "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url). "&client_secret=" . $app_secret . "&code=" . $_GET['code']; $response = getCurl($token_url); //echo $response; 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; } } //Step3:使用Access Token来获取用户的OpenID $params = array(); parse_str($response, $params); $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token']; $str = getCurl($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); if (isset($user->error)) { echo "<h3>error:</h3>" . $user->error; echo "<h3>msg :</h3>" . $user->error_description; exit; } //echo("Hello " . $user->openid); $_SESSION["access_token"] = $params['access_token']; $_SESSION["qq_openid"] = $user->openid; header("Location:https://XXX.com/index.php");//登录成功跳转地址 } else { echo("The state does not match. You may be a victim of CSRF."); } ?>
退出页面更简单
<?php session_start(); $_SESSION["qq_openid"] = null; header("Location:https://XXX.com/index.php");//退出后跳转页面 ?>
当然了,这个写的很简单,大家可以在上边加上自己想要的东西,比官方SDK简单易懂的多。
各位大神不要喷我哈,2333