Home Backend Development PHP Tutorial Case sharing on the implementation of QQ third-party login function in TP5 practical project

Case sharing on the implementation of QQ third-party login function in TP5 practical project

May 28, 2018 pm 04:02 PM
Function Log in third party

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/'
],
Copy after login

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";
Copy after login

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");
}
Copy after login

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);
Copy after login

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"]);
}
Copy after login

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')
);
Copy after login

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();
 * // 拿到用户信息后的处理
 *
}
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? Mar 21, 2024 pm 09:41 PM

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the "Login" button. (2) Select "Retrieve Password". (3) Enter the mobile phone number you used when registering your account

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

The difference between vivox100s and x100: performance comparison and function analysis The difference between vivox100s and x100: performance comparison and function analysis Mar 23, 2024 pm 10:27 PM

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

What exactly is self-media? What are its main features and functions? What exactly is self-media? What are its main features and functions? Mar 21, 2024 pm 08:21 PM

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance Mar 13, 2024 pm 04:58 PM

Baidu Netdisk can not only store various software resources, but also share them with others. It supports multi-terminal synchronization. If your computer does not have a client downloaded, you can choose to enter the web version. So how to log in to Baidu Netdisk web version? Let’s take a look at the detailed introduction. Baidu Netdisk web version login entrance: https://pan.baidu.com (copy the link to open in the browser) Software introduction 1. Sharing Provides file sharing function, users can organize files and share them with friends in need. 2. Cloud: It does not take up too much memory. Most files are saved in the cloud, effectively saving computer space. 3. Photo album: Supports the cloud photo album function, import photos to the cloud disk, and then organize them for everyone to view.​

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? Mar 21, 2024 pm 04:16 PM

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? Mar 23, 2024 pm 05:31 PM

Xiaohongshu has now been integrated into the daily lives of many people, and its rich content and convenient operation methods make users enjoy it. Sometimes, we may forget the account password. It is really annoying to only remember the account but not be able to log in. 1. How to log in if Xiaohongshu only remembers the account? When we forget our password, we can log in to Xiaohongshu through the verification code on our mobile phone. The specific operations are as follows: 1. Open the Xiaohongshu App or the web version of Xiaohongshu; 2. Click the "Login" button and select "Account and Password Login"; 3. Click the "Forgot your password?" button; 4. Enter your account number. Click "Next"; 5. The system will send a verification code to your mobile phone, enter the verification code and click "OK"; 6. Set a new password and confirm. You can also use a third-party account (such as

How to solve the common problem of Laravel login time invalidation How to solve the common problem of Laravel login time invalidation Mar 06, 2024 pm 09:24 PM

How to solve the common problem of Laravel login time expiration When using Laravel to develop web applications, login authentication is a very important function. However, sometimes if a user does not operate for a long time after logging in, the page may automatically log out or the authentication may fail. This problem is relatively common. The following will introduce how to solve this problem by setting the session time and provide specific code examples. 1. Set the session expiration time in Laravel, by default sessi

See all articles