Home Backend Development PHP Problem How to implement WeChat applet login in PHP

How to implement WeChat applet login in PHP

Apr 21, 2023 am 10:00 AM

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:

How to implement WeChat applet login in PHP

The specific process is as follows:

  1. The user opens the mini program and clicks the login button.
  2. The front end calls the API through wx.login to obtain the temporary login credential code.
  3. Send the code to the backend server.
  4. The backend sends a request to the WeChat server to obtain openid and session_key.
  5. WeChat server returns openid and session_key.
  6. The backend queries the database based on openid, and if the user does not exist, adds it to the database.
  7. The backend stores user information, generates a custom login token, and returns it to the frontend.
  8. The front end stores the token locally as a user login credential.
  9. 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);
    }
  }
});
Copy after login

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

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

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

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

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

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!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
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)

How to Implement message queues (RabbitMQ, Redis) in PHP? How to Implement message queues (RabbitMQ, Redis) in PHP? Mar 10, 2025 pm 06:15 PM

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

What Are the Latest PHP Coding Standards and Best Practices? What Are the Latest PHP Coding Standards and Best Practices? Mar 10, 2025 pm 06:16 PM

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

How to Use Reflection to Analyze and Manipulate PHP Code? How to Use Reflection to Analyze and Manipulate PHP Code? Mar 10, 2025 pm 06:12 PM

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

How Do I Work with PHP Extensions and PECL? How Do I Work with PHP Extensions and PECL? Mar 10, 2025 pm 06:12 PM

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,

How to Use Asynchronous Tasks in PHP for Non-Blocking Operations? How to Use Asynchronous Tasks in PHP for Non-Blocking Operations? Mar 10, 2025 pm 04:21 PM

This article explores asynchronous task execution in PHP to enhance web application responsiveness. It details methods like message queues, asynchronous frameworks (ReactPHP, Swoole), and background processes, emphasizing best practices for efficien

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

How to Use Memory Optimization Techniques in PHP? How to Use Memory Optimization Techniques in PHP? Mar 10, 2025 pm 04:23 PM

This article addresses PHP memory optimization. It details techniques like using appropriate data structures, avoiding unnecessary object creation, and employing efficient algorithms. Common memory leak sources (e.g., unclosed connections, global v

How Do I Stay Up-to-Date with the PHP Ecosystem and Community? How Do I Stay Up-to-Date with the PHP Ecosystem and Community? Mar 10, 2025 pm 06:16 PM

This article explores strategies for staying current in the PHP ecosystem. It emphasizes utilizing official channels, community forums, conferences, and open-source contributions. The author highlights best resources for learning new features and a

See all articles