WeChat mini program is a very popular application type in recent years. Because of its convenience, ease of use and ecological integrity, it is widely used in various scenarios. When developing WeChat applet, it is often necessary to implement user login function, which is as difficult to implement as traditional website login. This article will introduce the implementation process of WeChat applet login, which mainly includes the front-end calling API to obtain the code, the back-end receiving the code and requesting the WeChat server to obtain the user's openid and session_key, and finally storing the user information in its own database.
1. WeChat mini program login process
The WeChat mini program login process is as shown in the figure below:
The specific process is as follows:
- The user opens the mini program and clicks the login button.
- The front end calls the API through wx.login to obtain the temporary login credential code.
- Send the code to the backend server.
- The backend sends a request to the WeChat server to obtain openid and session_key.
- WeChat server returns openid and session_key.
- The backend queries the database based on openid, and if the user does not exist, adds it to the database.
- The backend stores user information, generates a custom login token, and returns it to the frontend.
- The front end stores the token locally as a user login credential.
- The next time the user logs in, the front end carries the token and sends a request to the back end. The back end verifies the validity of the token. If it is valid, the login is successful, otherwise a not logged in error is returned.
2. The front-end obtains the temporary login credential code
The front-end uses wx.login to call the API to obtain the temporary login credential code. The code returned by this API is only valid for 5 minutes, so the request needs to be sent to the backend in time.
wx.login({ success: function(res) { if (res.code) { // 发送code至后端服务器 wx.request({ url: 'https://example.com/login.php', method: 'POST', data: {'code': res.code}, success: function(resp) { // 获取后端返回的token并存储至本地 wx.setStorageSync('token', resp.data.token); } }); } else { console.log('获取登录态失败!' + res.errMsg); } } });
3. The backend obtains openid and session_key
The backend receives the temporary login credential code sent by the frontend, and sends a request to the WeChat server to obtain openid and session_key. The requested URL is: https://api.weixin.qq.com/sns/jscode2session. The parameters that need to be carried include appid, secret, js_code and grant_type, where appid and secret are the developer ID and corresponding key of the applet, js_code is the code obtained by the front end, grant_type is the authorization type, and the value is authorization_code.
$appid = "Your AppID"; $secret = "Your AppSecret"; $code = $_POST['code']; $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $res = curl_exec($ch); curl_close($ch); $data = json_decode($res, true); $openid = $data['openid']; $session_key = $data['session_key'];
4. Backend processing of user information
The backend queries the database based on openid, and if the user does not exist, it is added to the database. In this example, MySQL is used as the database management system. The user data table is named user and includes the fields id, openid and create_time. Among them, id is the user ID (self-increasing), openid is the user's unique identifier, and create_time is the user creation time.
// 连接数据库 $con = mysqli_connect('localhost', 'root', 'password', 'database'); mysqli_set_charset($con, 'utf8'); // 查询用户 $result = mysqli_query($con, "SELECT * FROM user WHERE openid='$openid' LIMIT 1"); if(mysqli_num_rows($result) == 0) { // 添加新用户 $now = date('Y-m-d H:i:s'); mysqli_query($con, "INSERT INTO user (openid, create_time) VALUES ('$openid', '$now')"); // 获取用户ID $user_id = mysqli_insert_id($con); } else { // 获取用户ID $row = mysqli_fetch_assoc($result); $user_id = $row['id']; }
After the user ID is successfully obtained, the backend can generate a custom login token and store the user information.
// 生成token $token = md5($user_id . time() . mt_rand()); // 存储token和用户信息 $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis->setex($token, 3600 * 24 * 7, $user_id); // 返回token echo json_encode(array('token' => $token));
5. Front-end storage token
After the front-end obtains the token returned by the back-end, it stores it locally. Generally, LocalStorage or SessionStorage is used for storage so that it can be retrieved on demand during the next visit.
wx.request({ url: 'https://example.com/login.php', method: 'POST', data: {'code': res.code}, success: function(resp) { // 获取后端返回的token并存储至本地 wx.setStorageSync('token', resp.data.token); } });
6. Verification of token validity for the user’s next visit
When the user visits next time, the front-end needs to carry the previously obtained and stored token to send a request to the back-end, and the back-end verifies the validity of the token. . If the token is valid, the login is successful, otherwise a not logged in error is returned.
// 验证token有效性 $token = $_POST['token']; $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $user_id = $redis->get($token); if($user_id) { // 验证成功,返回用户信息 // ... } else { // 验证失败,返回未登录错误 echo json_encode(array('errcode' => 40001, 'errmsg' => 'user not logged in')); }
7. Summary
To implement WeChat applet login, the front-end and back-end need to cooperate to complete multiple steps, including the front-end obtaining the temporary login credential code, the back-end obtaining openid and session_key, and back-end processing User information, generate a custom login token, and return it to the front end. The front end stores the token locally as a login credential for the next visit. After receiving the user request, the backend needs to verify whether the token is valid. If it is valid, it will return the corresponding user information, otherwise it will return a not logged in error. Through the above steps, the user login function of the WeChat applet can be implemented relatively stably.
The above is the detailed content of How to implement WeChat applet login in PHP. For more information, please follow other related articles on the PHP Chinese website!

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!
