PHP 实现QQ登录代码
废话不多说直接上代码
我将QQ登录配置信息放在login 表里面的,登录之前先检测是否有 appid , appkey , notify 回调地址。这些需要先去 QQ互联 https://connect.qq.com/ 申请,申请好通过后就有了。
//检测QQ登录配置信息
public function qqLoginCheck()
{
$res = db('login')->where('id', 1)->find();
if ($res['status'] == 0) {
$this->error("未启用QQ登录");
}
if ($res['appid'] == "") {
$this->error("QQ登录APPID不能为空");
}
if ($res['appkey'] == "") {
$this->error("QQ登录APPKEY不能为空");
}
if ($res['notify'] == "") {
$this->error("QQ登录回调地址不能为空");
}
return $res;
}
//QQ登录
public function qqLogin()
{
$bind = input('bind');
if ($bind) {
session('bindqq', true);
}
$res = $this->qqLoginCheck();
$url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" . $res['appid'] . "&redirect_uri=" . $res['notify'] . "&scope=get_user_info&state=text";
$this->redirect($url);
}
//QQ登录回调
public function qqnotify()
{
$res = $this->qqLoginCheck();
$code = $_GET['code'];
$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" . $res['appid'] . "&redirect_uri=" . $res['notify'] . "&client_secret=" . $res['appkey'] . "&code=" . $code;
$response = file_get_contents($token_url);
$params = array();
parse_str($response, $params);
$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" . $params['access_token'] . "&unionid=1";
$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);
}
$result = json_decode($str, true);
$userinfo_url = "https://graph.qq.com/user/get_user_info?access_token=".$params['access_token']."&oauth_consumer_key=".$res['appid']."&openid=".$result['openid'];
$userinfo = json_decode(curl_get($userinfo_url),true);
$result = array_merge($result,$userinfo);
//result 里面取得了QQ用户信息和openid等信息,下面你可以继续你的业务。
if ($result['unionid'] != "") {
$res = db('threepartylogin')->where('unionid', $result['unionid'])->find();
if (empty($res)) {
//第一次授权登录
} else {
//已授权直接登录
}
}
}