search
HomeBackend DevelopmentPHP TutorialCase sharing on the implementation of QQ third-party login function in TP5 practical project

Recently I used the thinkPHP 5 framework to make a bridal shop project. During the development process, a third-party login was required. The official case provided by Tencent was implemented by several files that included each other. When placed in tp5, it was very sad to find that in The expected functions cannot be completed through include or require in the controller. If you want to use Tencent’s officially sealed classes, you must modify them as follows:

1. Find the core in the official SDK File

When used outside the framework, it is include 'qqConnectAPI.php'. When you open this file, you can see that it contains If you have several other files, the files in the comm folder are nothing more than defining some constants and recording your APP KEY information. It doesn’t matter. Just put the several class files in the class folder into tp5. Okay, and if you look at the code carefully, you will find that you can actually implement the function as long as you get three classes.

2. Put it in the tp framework

tp5 recommends putting third-party things that are not installed by composer into the extend directory. Next, because we may need to make other extensions in the future, here we will create a separate qqlogin folder related to qq login.

You can see that there are only three categories in it, I will remove them I have created a Recorder and an ErrorCase class. As the names suggest, the function of these two is to record some information, such as access_token, and exception handling. I will delete them directly here. Also note that according to the psr4 specification, the class name must be consistent with the file name, so you need to change the file name and add the namespace extend\qqlogin, tp5 All classes must have namespaces .

In addition, in order to prevent tp5 from finding the files we need, it is best to register a root namespace in the config.php file, on line 30:

// 注册的根命名空间
'root_namespace'  => [
 'extend\qqlogin' => '../extend/qqlogin/',
 'extend\baidu' => '../extend/bdlogin/'
],

3. Transform the source code

Because QC.php inherits Oauth.php, we will change it from the latter, remove require_once, and add the namespace. I won’t go into this. First, look at Member attributes and class constants are the address of the Tencent platform. Don't worry about it. There are three attributes. Recorder and error are not needed. Comment them out or delete them directly. The same is true below. You should imagine that you have a grudge against these two words, and comment or delete them when you see them.

// protected $recorder;
public $urlUtils;
// protected $error;
public $state;
public $appid = "****";
public $callback = "http://****/index/user/qqcallback";
public $scope = "get_user_info";

The following four attributes need to be added. State is used to prevent CSRF attacks. You can know what the following three are by looking at the official documents. These are originally stored in inc.php under the comm folder. , now take it directly and turn it into a member attribute.

Then construct the function and instantiate three classes. Two of them no longer exist, and as mentioned above, there is a grudge against these two words. Comment or delete them when you see them.

Look at the first member method belowqq_login()

public function qq_login(){
 $appid = $this->recorder->readInc("appid");
 $callback = $this->recorder->readInc("callback");
 $scope = $this->recorder->readInc("scope");
 //---生成唯一随机串防CSRF攻击
 $state = md5(uniqid(rand(), TRUE));
 $this->recorder->write('state',$state);
 *
 *
 return $login_url;
 // header("Location:$login_url");
}

We have already deleted the lines with those two words, we If you need these things again, don't forget that we added three member attributes above. We already have these values ​​and use them below. Just pass $this->appid. When verifying the state, we can verify it through the session. TP5 provides an assistant function to write the session:

session('state',$this->state);

The last sentence is the header jump. I don’t know why the jump cannot be seen in TP5. The effect is that the url is returned directly, and then the redirection function $this->redirect() is implemented in the controller through the redirection function of tp5.

Look at qq_callback()

public function qq_callback(){
 // $state = $this->recorder->read("state");
 //---验证state防止CSRF攻击
 if(input('state') != session('state')){
  // $this->error("30001");
  exit('30001');
 }
 *
 *
 // return $params["access_token"];
 session('access_token',$params["access_token"]);
}

The two words that appear have been commented. We have written session in qq_login. Just compare it directly with sessio. Input() is also tp5 The helper function can obtain the parameters of get and post requests. The result is an array, but key-value pairs cannot be added dynamically. If you want to add it, you must assign it to a variable and then operate the variable. If there is an error here, exit directly and print out the error number. The official document has detailed error number descriptions. At the end, the access_token obtained is directly written into the session.

The following get_openid() method is similar. The parameter list is constructed with session, and the return value is written directly into the session.

Then modify QC.php, just modify the construction method and give values ​​to the three variables of the array.

$this->keysArr = array(
 "oauth_consumer_key" => (int)$this->appid,
 "access_token" => session('access_token'),
 "openid" => session('openid')
);

4. Controller call

The transformation is completed and can be used in the controller. Attached is the code below:

use extend\qqlogin\QC;
// 处理qq登录
public function qqlogin()
{
 $qq = new QC();
 $url = $qq->qq_login();
 $this->redirect($url);
}
// qq登录回调函数
public function qqcallback(UserModel $user)
{
 $qq = new QC();
 $qq->qq_callback();
 $qq->get_openid();
 $qq = new QC();
 $datas = $qq->get_user_info();
 * // 拿到用户信息后的处理
 *
}

Easy to forget:

In the callback function, QC must be instantiated twice to get the user information, and only during the second instantiationopenid and access_token two parameters.

The above is the detailed content of Case sharing on the implementation of QQ third-party login function in TP5 practical project. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Explain type hinting in PHPExplain type hinting in PHPApr 28, 2025 pm 04:52 PM

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.

What is PDO in PHP?What is PDO in PHP?Apr 28, 2025 pm 04:51 PM

The article discusses PHP Data Objects (PDO), an extension for database access in PHP. It highlights PDO's role in enhancing security through prepared statements and its benefits over MySQLi, including database abstraction and better error handling.

How to create API in PHP?How to create API in PHP?Apr 28, 2025 pm 04:50 PM

Article discusses creating and securing PHP APIs, detailing steps from endpoint definition to performance optimization using frameworks like Laravel and best security practices.

See all articles

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!