標籤:http os 檔案 資料 io re
放置按鈕:
如在首頁 index.php 中放如下代碼(即放按鈕)
<a href="qq/index.php">QQ登入</a>
然後跳轉到 qq/index.php 檔案中,代碼如下:
$url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=[YOUR_APPID]&redirect_uri=[YOUR_REDIRECT_URI]&scope=[THE_SCOPE]"
header("Location:" . $url);
接著會跳轉到 redirect_uri=[YOUR_REDIRECT_URI] 裡面指定的值 [YOUR_REDIRECT_URI],如 qq/callback.php
同時會帶有 ?code=value 的值
在qq/callback.php代碼如下:
$code = $_GET[‘code‘];
$url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=[YOUR_APPID]&client_secret=[APP KEY]&code=". $code ."&state=lin3615&redirect_uri=" . urlencode("http://www.xxxx.net/qq/callback.php");
// get_contents($url)用用擷取返回的資料
function get_contents($url){
if (ini_get("allow_url_fopen") == "1") {
$response = file_get_contents($url);
}else{
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
curl_close($ch);
}
return $response;
}
$response = get_contents($url);
// 解析資料,裡面有$access_token值
parse_str($response);
//callback($str)把json格式轉為 數組形式
function callback($str)
{
return json_decode($str, true);
}
$url = "https://graph.qq.com/oauth2.0/me?access_token=" . $access_token;
$callback = get_contents($url);
$callback = str_replace("(", "(‘", $callback);
$callback = str_replace(")", "‘)", $callback);
eval(‘$data=‘.$callback);
// openid
$openid = $data[‘openid‘];
$url = "https://graph.qq.com/user/get_user_info?access_token=$access_token&oauth_consumer_key=[YOUR_APPID]&openid=" . $openid;
$dd = get_contents($url);
$dd = json_decode($dd, true);
print_r($dd);
//其中 $dd 就是相關的QQ資訊數組
以下就串連資料庫;
假如如下資料表
user:使用者表,正常的非QQ登入,欄位有:
uid 自增
name 使用者名稱
password 密碼
.....
qqconnect:QQ串連表,QQ串連時用的,欄位有:
quid uid與 user表中的 uid 對應
openid $opendid
access_token $access_token
......
串連資料庫
$link = mysql_connect();
$sql = "select quid from qqconnect where openid= ‘{$openid}‘ and access_token = ‘{$access_token}‘";
$res = mysql_query($sql, $link);
// 如是如果已經存在,
if($res && mysql_num_rows($res))
{
$row = mysql_fetch_assoc($res);
$uid = $row[‘quid‘];
$query = "select * from user where uid = ‘{$uid}‘";
$rr = mysql_query($query, $link);
$rrs = mysql_fetch_assoc($rr);
$_SESSION[‘uid‘] = $rrs[‘uid‘];
$_SESSION[‘name‘] = $rrs[‘name‘];
header("Location:" . 首頁);
}else
{
// 不存在,就直接顯示綁定表單
echo "<from>";
echo ‘‘;
echo "</from>";
}