<?php 
//应用的APPID
$app_id = "YOUR_APP_ID";
//应用的APPKEY
$app_secret = "YOUR_APP_KEY";
//成功授权后的回调地址
$my_url = "YOUR_REDIRECT_URL";

//Step1:获取Authorization Code
session_start();
$code = $_REQUEST["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']) 
{
//拼接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);
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);
if (isset($user->error))
{
echo "<h3>error:</h3>" . $user->error;
echo "<h3>msg :</h3>" . $user->error_description;
exit;
}
echo("Hello " . $user->openid);
}
else 
{
echo("The state does not match. You may be a victim of CSRF.");
}
?>

最新文章

  1. Lesson 11 One good turn deserves another
  2. 【转】Matlab练习程序(各向异性扩散)
  3. MYSQL INSERT INTO SELECT 不插入重复数据
  4. 《TCP/IP 详解 卷一》读书笔记-----Ping&amp;Traceroute
  5. 小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
  6. LeetCode Delete Node in a Linked List (删除链表中的元素)
  7. matplotlib 初使用
  8. [转]Python中的矩阵转置
  9. 在CentOS 7下ISCSI和多路径部署文档【转】
  10. [bzoj3196]Tyvj 1730 二逼平衡树——线段树套平衡树
  11. 1.python的安装
  12. plsql启动提示监听服务无法连接
  13. BZOJ1004 HNOI2008 Cards Burnside、背包
  14. 【VS2015】链接器错误link2001
  15. linux 查看机器cpu核数
  16. FMS Dev Guide学习笔记(SharedBall)
  17. javascript学习笔记(七):事件详解
  18. rbac 权限分配, 基于formset实现,批量增加
  19. centeros6.8 下安装mysql教程
  20. C 和 Object-C中的 #ifdef #ifndef

热门文章

  1. HDU 2821 Pusher
  2. 【POJ】【3071】Football
  3. 【BZOJ】【2208】【JSOI2010】连通数
  4. websphere变成英文了怎么变回中文
  5. uva 10994
  6. IIS常见错误及解决
  7. linux入门教程(八) Linux磁盘管理
  8. linux入门教程(一) 关于linux的历史
  9. 小米2S 连接Ubuntu Android Studio
  10. Play Framework 发现并没有热启动的特殊情况