thinkPHP3.2.3 第三方登录(QQ登录)

注意:这个方法不需要下载什么sdk 

代码如下

控制器

/*
     *
     * 第三方QQ接口登录
     *
     *
     * */

    public $app_id="自己的appid";
    public $app_key="自己的APP Key";

    //回调地址
    public $callBackUrl="http://网站域名/index.php/Home/Login/userinfo";

    public function index()
    {
        header('Location:https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101543075&redirect_uri=http://网站域名/index.php/Home/Login/userinfo&state=state&scope=get_user_info,list_album,upload_pic,do_like');

    }


    public function userinfo(){

    //第一步,获取code(访问index即可)
        $code=$_GET['code'];
    //echo $code;
        $state=$_GET['state'];

    //第二步,获取access_token
        $access_token=$this->getAccessToken($code);


    //第三步,获取openid
        $openid=$this->get_openid($access_token);


    //第四步,获取用户信息
        $app_id=$this->app_id;
        $userinfo=$this->get_user_info($app_id,$access_token,$openid);

        $User = D("User"); // 实例化User对象

        $data['username'] = $userinfo['nickname'];
        $data['tel'] = $userinfo['province'];
        $data['portrait'] = $userinfo['figureurl_qq_2'];
        $data['time'] = time();

        $insert = $User->add($data);
        $info=$User->where("id=$insert")->find();

        if($insert){
            session('id',$insert);

            session('username',$info['username']);
            session('tel',$info['tel']);
            session('userip',get_client_ip());
            session('portrait',$info['portrait']);
            
            $this->redirect('Index/index');
        }

    }

    /**
     * 获取access_token值
     * @return array 返回包含access_token,过期时间的数组
     * */


    public function getAccessToken($code)
    {


        $url = "https://graph.qq.com/oauth2.0/token";

        $param = array(
            "grant_type"    =>    "authorization_code",

            "client_id"     =>    $this->app_id,
            "client_secret" =>    $this->app_key,
            "code"          =>    $code,
            "state"         =>    "state",
            "redirect_uri"  =>    $this->callBackUrl

            );

        $response = $this->get_url($url, $param);
        if($response == false) {
            return false;
        }
        $params = array();
        parse_str($response, $params);
        return $params["access_token"];

    }

    /**
     * 获取client_id 和 openid
     * @param $access_token access_token验证码
     * @return array 返回包含 openid的数组
     * */


    private  function get_openid($access_token) {
        $url = "https://graph.qq.com/oauth2.0/me";

        $param = array(
            "access_token"    => $access_token
        );
        $response  = $this->get_url($url, $param);
        if($response == false) {
            return false;
        }
        if (strpos($response, "callback") !== false) {
            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response = substr($response, $lpos + 1, $rpos - $lpos -1);


        }
        $user = json_decode($response);
        if (isset($user->error) || $user->openid == "") {
            return false;
        }

        return $user->openid;

    }

    /**
     * 获取用户信息
     * @param $client_id
     * @param $access_token
     * @param $openid
     * @return array 用户的信息数组
     * */


    public function get_user_info($app_id,$token,$openid){
        $url = 'https://graph.qq.com/user/get_user_info?oauth_consumer_key='.$app_id.'&access_token='.$token.'&openid='.$openid.'&format=json';
        $str = $this->get_url($url);
        if($str == false) {
            return false;
        }
        $arr = json_decode($str,true);
        return $arr;
    }

    //CURL GET
    public function get_url($url, $param = null) {
        if($param != null) {
            $query = http_build_query($param);
            $url = $url . '?' . $query;
        }
        $ch = curl_init();
        if(stripos($url, "https://") !== false){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        $content = curl_exec($ch);
        $status = curl_getinfo($ch);
        curl_close($ch);
        if(intval($status["http_code"]) == 200) {
            return $content;
        }else{
            echo $status["http_code"];
            return false;
        }
    }


    /*
     * HTTP POST Request
    */
    public function post_url($url, $params) {
        $ch = curl_init();
        if(stripos($url, "https://") !== false) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $content = curl_exec($ch);
        $status = curl_getinfo($ch);
        curl_close($ch);
        if(intval($status["http_code"]) == 200) {
            return $content;
        } else {
            return false;
        }
    }

    //json_encode转换中文解决方法


    public function encode_json($str){
        $code = json_encode($str);
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
            create_function(
                '$matches',
                'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
            ),
            $code);
}

模板中url

<div class="other_login">
                    <div class="left other_left"> <span>其它登录方式</span> </div>
                    <div class="right other_right">
                        <a href="{:U('Login/index')}"><i class="fa fa-qq fa-2x"></i></a>
                        <a href="#"><i class="fa fa-weixin fa-2x"></i></a>
                        <a href="#"><i class="fa fa-weibo fa-2x"></i></a> </div>
                </div>

前台首页用户信息调用

 <li style="margin:0 0 0 1rem;">

                <h3>用户头像:<img src="<?php echo session('portrait')?>" style="width:70px;height: 70px;border-radius:50%; vertical-align:middle;"></h3>
                <h3>用户账号:<?php echo session('tel') ?></h3>
                <h3>用户名称:<?php echo session('username') ?></h3>
            </li>

猜你喜欢

转载自blog.csdn.net/qq_40270754/article/details/86630921