Home Backend Development PHP Problem How to implement WeChat scan code login in PHP

How to implement WeChat scan code login in PHP

Sep 23, 2021 pm 03:02 PM
php WeChat

php method to implement WeChat code scanning login: 1. Instantiate an object through js; 2. Define a div in html and contain the QR code; 3. Within $(document).ready() Just instantiate it.

How to implement WeChat scan code login in PHP

The operating environment of this article: windows10 system, php 7, thinkpad t480 computer.

WeChat has become an indispensable part of our daily lives. In order to allow more users to use WeChat and related products more conveniently, the WeChat scan function is becoming more and more common. So what should we do if we want to implement this function ourselves?

Before giving the specific implementation code, let’s first analyze the WeChat code scanning login process.

First of all, we must display the QR code on the page. The QR code has an expiration time and invalid state. Once you scan the QR code once or do not scan it within a certain period of time, the QR code will appear on the page. QR code, then this QR code will be invalid. WeChat official website provides us with two ways to display QR codes. One is to send a request in the background to return a new page, and the other is to instantiate the QR code in front-end js and embed it on its own page. Obviously the first method is simpler and more convenient, but both methods will be used in actual projects. In this case, we will explain both methods.

1. Send a request in the background to obtain the scan code page returned by WeChat

$redirect_uri="http://你的微信开放平台绑定域名下处理扫码事件的方法";
$redirect_uri=urlencode($redirect_uri);//该回调需要url编码
$appID="你的appid";
$scope="snsapi_login";//写死,微信暂时只支持这个值
//准备向微信发请求
$url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $appID."&redirect_uri=".$redirect_uri."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect";
//请求返回的结果(实际上是个html的字符串)
$result = file_get_contents($url);
//替换图片的src才能显示二维码
$result = str_replace("/connect/qrcode/", "https://open.weixin.qq.com/connect/qrcode/", $result);
return $result; //返回页面
Copy after login

This will return a page like this, and call $redirect_uri after scanning

How to implement WeChat scan code login in PHP

2. Embedded JS display:

Here is to instantiate an object through the js side. First add the following js file in the tag,

<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
Copy after login

Secondly, define a div in html to contain the QR code,

<div id="login_container"></div>
Copy after login

Finally instantiate it in $(document).ready():

$(document).ready(function()
{
    var obj = new WxLogin
    ({
        id:"login_container",//div的id
        appid: "你的appid",
        scope: "snsapi_login",//写死
        redirect_uri:encodeURI("你的处理扫码事件的方法") ,
        state: "",
        style: "black",//二维码黑白风格        
        href: "https://某个域名下的css文件"
    });
});
Copy after login

Note that the css file pointed to in the href must It can only be referenced under the https protocol, otherwise the page will have the default style (it displays a relatively large QR code, and you cannot adjust the size and position of the QR code, which is too painful). The last part of the page looks like this. The QR code here is only about 140px:

How to implement WeChat scan code login in PHP

Okay, the QR code appears on the page. Next we will roughly Let’s talk about the logic of scanning the QR code. The whole process is roughly divided into 5 steps:

How to implement WeChat scan code login in PHP

After completing these five steps, you will get all the information of the user who scanned the QR code. Then just write the code logic you need (such as redirection or login). The expression in the code is as follows:

//回调
public function codeinfo()
{
        $code = $_GET["code"];
        $appid = "你的appid";
        $secret = "你的secret";
        if (!empty($code))  //有code
        {
            //通过code获得 access_token + openid
           $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid
            . "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
            $jsonResult = file_get_contents($url);
            $resultArray = json_decode($jsonResult, true);
            $access_token = $resultArray["access_token"];
            $openid = $resultArray["openid"];

            //通过access_token + openid 获得用户所有信息,结果全部存储在$infoArray里,后面再写自己的代码逻辑
            $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid;
            $infoResult = file_get_contents($infoUrl);
            $infoArray = json_decode($infoResult, true);
     } }
Copy after login

I believe that after writing the above code, you have already scanned and logged in. The process is very clear. In fact, it is essentially just the coordinated calls of multiple WeChat interfaces.

Recommended learning: php training

The above is the detailed content of How to implement WeChat scan code login in PHP. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles