用php实现QQ授权登陆

第一步:认证工作
首先登陆QQ互联首页https://connect.qq.com/进行个人/企业认证。

认证通过之后创建应用:

这里主要用到应用的APP ID 和 APP Key 这两个参数。

还要填写回调地址 就是请求qq接口获取code参数回调给你的地址

$app_id = "";
//应用的APPKEY
$app_secret = "";
//【成功授权】后的回调地址,即此地址在腾讯的信息中有储存
$my_url="";
//第一步:获取Authorization Code 获取 code
session_start();
$code = $_REQUEST["code"];//存放Authorization Code
if(empty($code))
{
    //state参数用于防止CSRF攻击,成功授权后回调时会原样带回 判断session保存的和回调过来的是否一样
    $_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'];
       header('Location:'.$dialog_url);
}


//第二步:通过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);

    //第三步:使用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);
    $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;
    }
    //第四步:使用<span >openid,</span><span >access_token来获取所接受的用户信息。</span>
    $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);//此为获取到的user信息
    $user_data = json_decode($user_data, true);

    //拿到用户信息后可以进行一系列的逻辑判断。就这么简单。
}else {
    echo("The state does not match. You may be a victim of CSRF.");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加油,明天会更好

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值