Home  >  Article  >  Backend Development  >  How to implement WeChat applet login in PHP

How to implement WeChat applet login in PHP

PHPz
PHPzOriginal
2023-04-21 10:00:572517browse

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);
    }
  }
});

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!

Statement:
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