PHP 实现QQ登录代码

编程知识 更新时间:2023-05-01 23:10:09

PHP 实现QQ登录代码

废话不多说直接上代码

我将QQ登录配置信息放在login 表里面的,登录之前先检测是否有 appid , appkey , notify 回调地址。这些需要先去 QQ互联 https://connect.qq/ 申请,申请好通过后就有了。

//检测QQ登录配置信息
  public function qqLoginCheck()
  {
    $res = db('login')->where('id', 1)->find();
    if ($res['status'] == 0) {
      $this->error("未启用QQ登录");
    }
    if ($res['appid'] == "") {
      $this->error("QQ登录APPID不能为空");
    }
    if ($res['appkey'] == "") {
      $this->error("QQ登录APPKEY不能为空");
    }
    if ($res['notify'] == "") {
      $this->error("QQ登录回调地址不能为空");
    }
    return $res;
  }

//QQ登录
  public function qqLogin()
  {
    $bind = input('bind');
    if ($bind) {
      session('bindqq', true);
    }
    $res = $this->qqLoginCheck();
    $url = "https://graph.qq/oauth2.0/authorize?response_type=code&client_id=" . $res['appid'] . "&redirect_uri=" . $res['notify'] . "&scope=get_user_info&state=text";
    $this->redirect($url);
  }

  //QQ登录回调
  public function qqnotify()
  {
    $res = $this->qqLoginCheck();
    $code = $_GET['code'];
    $token_url = "https://graph.qq/oauth2.0/token?grant_type=authorization_code&client_id=" . $res['appid'] . "&redirect_uri=" . $res['notify'] . "&client_secret=" . $res['appkey'] . "&code=" . $code;
    $response = file_get_contents($token_url);
    $params = array();
    parse_str($response, $params);
    $graph_url = "https://graph.qq/oauth2.0/me?access_token=" . $params['access_token'] . "&unionid=1";
    $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);
    }
    $result = json_decode($str, true);
    $userinfo_url = "https://graph.qq/user/get_user_info?access_token=".$params['access_token']."&oauth_consumer_key=".$res['appid']."&openid=".$result['openid'];
    $userinfo = json_decode(curl_get($userinfo_url),true);
    $result = array_merge($result,$userinfo);
    
    //result 里面取得了QQ用户信息和openid等信息,下面你可以继续你的业务。
    if ($result['unionid'] != "") {
      $res = db('threepartylogin')->where('unionid', $result['unionid'])->find();
      if (empty($res)) {
        //第一次授权登录
      
      } else {
        //已授权直接登录
       
      }
    }
  }

 

更多推荐

PHP 实现QQ登录代码

本文发布于:2023-04-24 11:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/10828e333b6204fc70f16df0d238cc03.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   PHP   QQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 100380文章数
  • 26040阅读数
  • 0评论数