Current Location: Home> Latest Articles> Complete PHP Tutorial for Implementing WeChat QR Code Login

Complete PHP Tutorial for Implementing WeChat QR Code Login

M66 2025-10-24

Introduction

WeChat QR code login is a convenient user authentication method, allowing users to quickly log in by scanning a QR code. This article explains how to implement WeChat QR code login using PHP, covering QR code generation, callback handling, and user information retrieval.

Preparation

Before getting started, you need to prepare the following:

  • A WeChat developer account to create an application and obtain AppID and AppSecret.
  • A website or application to integrate WeChat QR code login.
  • Familiarity with OAuth2.0 protocol and WeChat Open Platform API documentation.

Generating the WeChat QR Code

Create an Application and Obtain AppID and AppSecret

First, create an application on the WeChat Open Platform and obtain the AppID and AppSecret, which are required for API calls.

Obtain the QR Code Ticket

Use the following code to get the QR code ticket for WeChat login:

$access_token = 'YOUR_ACCESS_TOKEN';
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$access_token";
$data = [
    'expire_seconds' => 600,
    'action_name' => 'QR_LIMIT_STR_SCENE',
    'action_info' => [
        'scene' => [
            'scene_str' => 'login'
        ]
    ]
];
$response = httpPost($url, json_encode($data));
$result = json_decode($response, true);
$ticket = urlencode($result['ticket']);

Generate the QR Code Image Using the Ticket

Use the ticket to generate the QR code image. Users can scan it to log in:

$qrCodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=$ticket";
echo "QR code generated successfully";

Handling Callback After User Scans QR Code

After scanning, WeChat sends callback information to the pre-configured callback URL. You need to handle this information to retrieve the user's openid and other data.

Get User OpenID

$code = $_GET['code'];
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=YOUR_APPID&secret=YOUR_APPSECRET&code=$code&grant_type=authorization_code";
$response = httpGet($url);
$result = json_decode($response, true);
$openid = $result['openid'];

Get User Information

$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$result['access_token']}&openid=$openid";
$response = httpGet($url);
$userInfo = json_decode($response, true);

Conclusion

This article demonstrated the complete process of implementing WeChat QR code login using PHP, including QR code generation, callback handling, and user information retrieval. Following these steps, you can quickly set up a basic WeChat QR code login system to enhance user login experience.