qqapi.class.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. class qqapi{
  3. private $appid,$appkey,$callback,$access_token,$openid;
  4. public function __construct($appid, $appkey, $callback){
  5. $this->appid = $appid;
  6. $this->appkey = $appkey;
  7. $this->callback = $callback;
  8. $this->access_token= '';
  9. $this->openid = '';
  10. }
  11. public function redirect_to_login() {
  12. //跳转到QQ登录页的接口地址, 不要更改!!
  13. $redirect = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=$this->appid&scope=&redirect_uri=".rawurlencode($this->callback);
  14. header("Location:$redirect");
  15. }
  16. //获得登录的 openid
  17. public function get_openid($code){
  18. $url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=$this->appid&client_secret=$this->appkey&code=$code&redirect_uri=".rawurlencode($this->callback);
  19. $content = file_get_contents( $url);
  20. if (stristr($content,'access_token=')) {
  21. $params = explode('&',$content);
  22. $tokens = explode('=',$params[0]);
  23. $token = $tokens[1];
  24. $this->access_token=$token;
  25. if ($token) {
  26. $url="https://graph.qq.com/oauth2.0/me?access_token=$token";
  27. $content=file_get_contents($url);
  28. $content=str_replace('callback( ','',$content);
  29. $content=str_replace(' );','',$content);
  30. $returns = json_decode($content);
  31. $openid = $returns->openid;
  32. $this->openid = $openid;
  33. $_SESSION["token2"] = $openid;
  34. } else {
  35. $openid='';
  36. }
  37. } elseif (stristr($content,'error')) {
  38. $openid='';
  39. }
  40. return $openid;
  41. }
  42. /**
  43. * 返回用户信息
  44. *
  45. */
  46. public function get_user_info(){
  47. $url = "https://graph.qq.com/user/get_user_info?access_token=$this->access_token&oauth_consumer_key=$this->appid&openid=$this->openid";
  48. $content=file_get_contents($url);
  49. $result = json_decode($content);
  50. return $result->nickname;
  51. }
  52. }
  53. ?>