search
HomePHP FrameworkThinkPHPCase analysis of ThinkPHP connecting to QQ Internet to realize login

Case analysis of ThinkPHP connecting to QQ Internet to realize login

Mar 05, 2020 am 11:35 AM
thinkphpcase analysisLog in

This article introduces the method of using ThinkPHP to access QQ Internet to realize third-party login. It is explained as a small case for you. I hope it will be helpful to you.

Case analysis of ThinkPHP connecting to QQ Internet to realize login

Case analysis of ThinkPHP connecting to QQ Internet to realize login

I want to connect to a second-level domain name project QQ third-party login function, this project is developed using the thinkphp5 framework. I searched some access cases on the Internet. I personally feel that a mixed bag of good and bad is not suitable for me. Now I am re-developing this function on the thinkphp5 framework. The following is the detailed development step.

(Recommended tutorial: thinkphp tutorial)

The first step is to download the QQ Internet SDK. We are based on the thinkphp5 framework. Of course, we need to use PHP version of the SDK, the file directory after downloading is as follows.

Case analysis of ThinkPHP connecting to QQ Internet to realize login

The second step is to upload the main directory of the SDK to the appropriate directory on the server. First, let’s talk about the main directory of the SDK being the class directory in the API folder. Originally, for To test the configuration settings, I uploaded the install folder, and then configured the APP ID, APP Key and callback_url in the development environment. After configuration, there will be an inc.php configuration file in the API/comm folder, and finally recorder This configuration file will be referenced in the class. However, during the subsequent development process, I found that this error would be reported: The state does not match. You may be a victim of CSRF. Later, I put the state in the qqlogin method into the session. I had completely lost confidence in the DEMO SDK on the official website. Instead of using QQ to connect all the files, I selected a few important class files for development. Thinking later, the official SDK is just a common PHP code format. Many things I applied to thinkphp have changed. Finally, I chose the last class file, QC.php, URL.php, and Oauth.php, and uploaded them to extend/qqlogin Under contents. In thinkphp5 projects, extension classes are generally uploaded to the extend folder, as shown in the figure below my last directory location.

Case analysis of ThinkPHP connecting to QQ Internet to realize login

The third step is to transform the above three class files. Because QC.php inherits Oauth.php, we change it from the latter, remove require_once, and add naming For a space such as namespace qqlogin, first look at the member attributes. The class constant is the address of the Tencent platform. Don't worry about it. There are three attributes originally. Recorder and error are not needed. Comment them out or delete them directly. The same is true below, because out of 5 class files we only use 3 class files, one is the error reporting class and the other is the reading configuration related class. Let’s look at the Oauth.php member attributes, qqlogin jump method, and qqcallback callback method. The other two class files have not changed much. Just change them according to the above rules.

<?php
/* PHP SDK
 * @version 2.0.0
 * @author connect@qq.com
 * @copyright © 2013, Tencent Corporation. All rights reserved.
 */
namespace qqlogin;
use qqlogin;
class Oauth{
    const VERSION = "2.0";
    const GET_AUTH_CODE_URL = "https://graph.qq.com/oauth2.0/authorize";
    const GET_ACCESS_TOKEN_URL = "https://graph.qq.com/oauth2.0/token";
    const GET_OPENID_URL = "https://graph.qq.com/oauth2.0/me";
    // protected $recorder;
    public $urlUtils;
    // protected $error;
    
    function __construct(){
        // $this->recorder = new Recorder();
        $this->urlUtils = new URL();
        // $this->error = new ErrorCase();
    }
    public function qq_login(){
        // $appid = $this->recorder->readInc("appid");
        // $callback = $this->recorder->readInc("callback");
        // $scope = $this->recorder->readInc("scope");
        $appid = $this->appid;
        $callback = $this->callback;
        $scope = $this->scope;
        //-------生成唯一随机串防CSRF攻击
        $state = md5(uniqid(rand(), TRUE));
        // $this->recorder->write(&#39;state&#39;,$state);
        session(&#39;state&#39;,$state);
        //-------构造请求参数列表
        $keysArr = array(
            "response_type" => "code",
            "client_id" => $appid,
            "redirect_uri" => $callback,
            "state" => $state,
            "scope" => $scope
        );
        $login_url =  $this->urlUtils->combineURL(self::GET_AUTH_CODE_URL, $keysArr);
        return $login_url;
    }
    public function qq_callback(){
        // $state = $this->recorder->read("state");
        //--------验证state防止CSRF攻击
        if(input(&#39;state&#39;) != session(&#39;state&#39;)){
            // $this->error->showError("30001");
            exit(&#39;30001&#39;);
        }
        //-------请求参数列表
        $keysArr = array(
            "grant_type" => "authorization_code",
            "client_id" => $this->appid,
            "redirect_uri" => urlencode($this->callback),
            "client_secret" => $this->appkey,
            "code" => $_GET[&#39;code&#39;]
        );
        //------构造请求access_token的url
        $token_url = $this->urlUtils->combineURL(self::GET_ACCESS_TOKEN_URL, $keysArr);
        $response = $this->urlUtils->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)){
            //     $this->error->showError($msg->error, $msg->error_description);
            // }
        }
        $params = array();
        parse_str($response, $params);
        // $this->recorder->write("access_token", $params["access_token"]);
        // return $params["access_token"];
        session(&#39;access_token&#39;,$params["access_token"]);
    }
}

The fourth step is to write the controller. Call the function and callback function, and check whether the callback address is correct (the callback address is the jump address returned when you add a QQ third-party login to QQ Internet. This address carries important parameters and can obtain the last user's data). Sometimes if you are The callback address filled in by QQ Internet is different from that of your controller, then it will end up stuck at the callback address filled in by QQ Internet, such as www.100txy.com/index.php?code=65B7668A4F1BBB71DD0DF52B55AC1FC1&state=804e921e18e3545ecdf690316639c067. The following is the controller method

use qqlogin\QC;
// 处理qq登录
    public function qqlogin(){
        $qq = new QC();
        $url = $qq->qq_login();
        $this->redirect($url);
    }
    // qq登录回调函数
    public function qqcallback(){
        $qq = new QC();
        $qq->qq_callback();
        $qq->get_openid();
        $qq = new QC();
        $datas = $qq->get_user_info();
        die(var_dump($datas));//为用户数据
    }

It is worth noting that QC needs to be instantiated twice in the callback function to get the user information. Only the second time it is instantiated has the two parameters openid and access_token.

For more Thinkphp tutorials, please pay attention to PHP Chinese website!

The above is the detailed content of Case analysis of ThinkPHP connecting to QQ Internet to realize login. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:www.100txy.com. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function