php QQ登录

基本原理:
就是获取唯一的openid,此值只要与自己数据库表中的值对应,就说明是此用户,
没有,则说明是新用户,其实就是找对应关系,因为openid与QQ号是唯一对应关系
放置按钮:
如在首页 index.php 中放如下代码(即放按钮)
<a href="qq/index.php">QQ登录</a>

然后跳转到 qq/index.php 文件中,代码如下:
<?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}';
$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>";
}

  

posted @ 2014-07-22 21:45  好记性还真不如烂笔头  阅读(437)  评论(0编辑  收藏  举报