PHP調用QQ互聯接口實現QQ登錄網站功能示例
更新時間:2019年10月24日 10:12:54 作者:李維山
這篇文章主要介紹了PHP調用QQ互聯接口實現QQ登錄網站功能,結合實例形式分析php調用QQ互聯接口實現QQ登錄網站的相關操作技巧,需要的朋友可以參考下
本文實例講述了PHP調用QQ互聯接口實現QQ登錄網站功能。分享給大家供大家參考,具體如下:
調用QQ登錄接口,首先要到QQ互聯完善開發(fā)者認證信息,并通過審核,然后創(chuàng)建一個網站應用,獲得APP ID和APP Key,通過審核后即可調用基本接口get_user_info(獲得用戶信息),實現QQ登錄網站功能。


廢話不多,上示例代碼(QQ登錄李維山博客):
<?php
header("Content-Type: text/html;charset=utf-8");
//應用APP ID
$app_id = "101486017";
//應用APP Key
$app_secret = "13a1811780f29d7a5b64e598c38a4494";
//應用填寫的網站回調域
$my_url = "http://www.msllws.top/qqlogin";
//Step1:獲取Authorization Code
session_start();
$code = $_REQUEST["code"];//存放Authorization Code
if(empty($code)) {
//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>");
}
//Step2:通過Authorization Code獲取Access Token
if($_REQUEST['state'] == $_SESSION['state'] || 1) {
//拼接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=".$code;
$response = file_get_contents($token_url);
//如果用戶臨時改變主意取消登錄,返回true!==false,否則執(zhí)行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;
}
}
//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 = 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);//存放返回的數據 client_id ,openid
if (isset($user->error)) {
echo "<h3>error:</h3>".$user->error;
echo "<h3>msg :</h3>".$user->error_description;
exit;
}
//Step4:使用openid和access_token獲取用戶信息
$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";
$user_data = file_get_contents($user_data_url);//獲取到的用戶信息
//以下為授權成功后的自定義操作
if($user_data){
// ......
echo("<script> top.location.);
}else{
echo '未知錯誤';
}
}else{
echo("The state does not match. You may be a victim of CSRF.");
}
登錄效果:

更多關于PHP相關內容感興趣的讀者可查看本站專題:《php curl用法總結》、《PHP網絡編程技巧總結》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《PHP數據結構與算法教程》及《PHP中json格式數據操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。

