Case analysis of ThinkPHP connecting to QQ Internet to realize login
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
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.
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.
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('state',$state); session('state',$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('state') != session('state')){ // $this->error->showError("30001"); exit('30001'); } //-------请求参数列表 $keysArr = array( "grant_type" => "authorization_code", "client_id" => $this->appid, "redirect_uri" => urlencode($this->callback), "client_secret" => $this->appkey, "code" => $_GET['code'] ); //------构造请求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('access_token',$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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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 solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

Recently, some friends have asked me how to log in to the Kuaishou computer version. Here is the login method for the Kuaishou computer version. Friends who need it can come and learn more. Step 1: First, search Kuaishou official website on Baidu on your computer’s browser. Step 2: Select the first item in the search results list. Step 3: After entering the main page of Kuaishou official website, click on the video option. Step 4: Click on the user avatar in the upper right corner. Step 5: Click the QR code to log in in the pop-up login menu. Step 6: Then open Kuaishou on your phone and click on the icon in the upper left corner. Step 7: Click on the QR code logo. Step 8: After clicking the scan icon in the upper right corner of the My QR code interface, scan the QR code on your computer. Step 9: Finally log in to the computer version of Kuaishou

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

How to log in to two devices with Quark? Quark Browser supports logging into two devices at the same time, but most friends don’t know how to log in to two devices with Quark Browser. Next, the editor brings users Quark to log in to two devices. Method graphic tutorials, interested users come and take a look! Quark Browser usage tutorial Quark how to log in to two devices 1. First open the Quark Browser APP and click [Quark Network Disk] on the main page; 2. Then enter the Quark Network Disk interface and select the [My Backup] service function; 3. Finally, select [Switch Device] to log in to two new devices.
