php实现qq授权登录

第一步:

登录 https://connect.qq.com  qq授权管理中心开通应用,审核通过之后填写平台信息。如图:

 

 

值得一提的是网站回调域必须具体到方法,不然登录之后回调会识别错误。

 

 

第二步:

建立数据表,存储qq授权返回的用户信息(主要是存储openid,用户唯一识别标识)。我的实现方法是在用户表里添加字段存储,个人中心里面补全用户信息。

 

 

第三步:

接下来就是拿到应用的app_id 和 app_secret 来调取接口。直接上代码:

/**
 * qq授权登录
 */  
public function qqlogin(){
   $app_id = "111111111";
   //应用的APPKEY
   $app_secret = "0asd55db7745a7a946c6cfdedefgscba";
   //【成功授权】后的回调地址,即此地址在腾讯的信息中有储存
   $my_url = "http://".$_SERVER['HTTP_HOST']."/Home/User/qqlogin";

   //Step1:获取Authorization Code
   $code = $_REQUEST["code"];//存放Authorization Code
   if(empty($code))
   {
      //state参数用于防止CSRF攻击,成功授权后回调时会原样带回
      $_SESSION['qq_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['qq_state'];
      echo("<script> top.location.href='" . $dialog_url . "'</script>");
   }

   //Step2:通过Authorization Code获取Access Token
   if($_REQUEST['state'] == $_SESSION['qq_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);
      if (strpos($response, "callback") !== false)//如果登录用户临时改变主意取消了,返回true!==false,否则执行step3
      {
         $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;*/
            $this->error("非法操作,请重新登录!", U('user/login'));
         }
      }

      //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);//存放返回的数据 client_id ,openid
      if (isset($user->error))
      {
         /*echo "<h3>error:</h3>" . $user->error;
         echo "<h3>msg :</h3>" . $user->error_description;
         exit;*/
         $this->error("非法操作,请重新登录!", U('user/login'));
      }
      //echo("Hello " . $user->openid);
      //echo("Hello " . $params['access_token']);

      //Step4:使用access_token来获取所接受的用户信息。
      $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);
      $user_data['openid'] = $user->openid;
      $m = M("Member");
      $data = array();
      $data['sex']           = $user_data["gender"]=='男'?1:2;
      $data['province']      = $user_data["province"];
      $data['city']          = $user_data["city"];
      $data['person_name']   = $user_data["nickname"];
      $data['qq_openid']     = $user_data["openid"];
      $data['qq_name']       = $user_data["nickname"];
      $data['qq_img']        = $user_data["figureurl_qq_2"];
      $data['addtime']       = date("Y-m-d H:i:s", time());
      $data['person_img']    = $user_data["figureurl_qq_2"];
      $data['signtime']      = date("Y-m-d H:i:s", time());

      $user = M("Member")->where(array("qq_openid"=> $user_data['openid']))->find();
    //判断当前是否第一次登录
      if($user){
         $res = M("Member")->where(array("qq_openid"=> $user_data["openid"]))->setField("signtime", date("Y-m-d H:i:s", time()));
         if($res){
        //登录成功业务逻辑
             session("user_id", $user['id']);
                   

         }else{
            $this->error("操作异常,拒绝访问!", U('user/login'));
         }
      }else{
         $res=$m->add($data);
         if($res){
        //登录成功业务逻辑
        session("user_id", $res);         

         }else{
            $this->error("操作异常,拒绝访问!", U('user/login'));
         }
      }

   }
   else
   {
      $this->error("操作异常,拒绝访问!", U('user/login'));
   }
}

 

posted @ 2017-07-12 12:30  从此以往  阅读(1922)  评论(0编辑  收藏  举报