Home Backend Development PHP Tutorial Detailed steps to implement WeChat login function using PHP

Detailed steps to implement WeChat login function using PHP

Apr 04, 2023 am 10:40 AM

In recent years, with the rise of social networks and the popularity of smartphones, WeChat has become an indispensable part of people's daily lives. In the field of Internet applications, implementing the WeChat login function is a very necessary part. As we all know, WeChat's authorization mechanism uses the OAuth 2.0 authorization mechanism, which brings great convenience to the implementation of our WeChat login function. Below we will introduce in detail how to implement the WeChat login function through PHP language.

1. WeChat development platform configuration

  1. Log in to [WeChat Open Platform](https://open.weixin.qq.com) to register an account. After registration is completed, enter WeChat Open Platform management center.
  2. Click the "Manage Official Account" menu on the center page and enter the WeChat official account information that needs to be accessed.
  3. After being authenticated by the WeChat Open Platform, we need to obtain the AppID and AppSecret of the WeChat Open Platform and record them in the login code. Log in to [WeChat Open Platform](https://open.weixin.qq.com), enter the management center, select "Mobile Application", and then select "Add Mobile Application".
  4. Fill in the basic information of the mobile application and submit it for review. After review and approval, you can obtain the AppID and AppSecret.

2. PHP code implementation

  1. Build WeChat login link
<?php
$appid = “your_appid”; //appid
$redirect_uri = urlencode(&#39;http://yourdomain.com/login.php&#39;); //登录成功回调网址,请确保此地址跟公众号设置的授权回调页面路径一致。
$scope = &#39;snsapi_userinfo&#39;; //snsapi_base 或 snsapi_userinfo
$url = &#39;https://open.weixin.qq.com/connect/oauth2/authorize?appid=&#39; . $appid . &#39;&redirect_uri=&#39; . $redirect_uri . &#39;&response_type=code&scope=&#39; . $scope . &#39;&state=STATE#wechat_redirect&#39;;
header(&#39;Location:&#39; . $url);
exit;
?>
Copy after login

In the above code, we need to fill in $appid, $redirect_uri and $scope parameter. Among them, $appid is the AppID assigned to us by the WeChat open platform; $redirect_uri is the callback URL after user authorization, which needs to be consistent with the authorization callback page set by the official account; $scope is divided into snsapi_base and snsapi_userinfo, the former can only obtain the user's openid , and the latter can obtain the user's basic information.

  1. Get access_token and openid
<?php
$appid = &#39;your_appid&#39;; //appid
$secret = &#39;your_appsecret&#39;; //appsecret
$code = $_GET[&#39;code&#39;]; //网页授权code
$access_token_url = &#39;https://api.weixin.qq.com/sns/oauth2/access_token?appid=&#39; . $appid . &#39;&secret=&#39; . $secret . &#39;&code=&#39; . $code . &#39;&grant_type=authorization_code&#39;; //获取access_token和openid的链接
$access_token = file_get_contents($access_token_url);
$access_token_arr = json_decode($access_token, true); //将返回的json字符串转为数组
?>
Copy after login

In this code, we pass the code returned by the user after successful authorization, and then pass the code to the WeChat server to obtain the access_token and openid.

  1. Get the user’s basic information
<?php
$access_token = $access_token_arr[&#39;access_token&#39;];
$openid = $access_token_arr[&#39;openid&#39;];
$user_info_url = &#39;https://api.weixin.qq.com/sns/userinfo?access_token=&#39; . $access_token . &#39;&openid=&#39; . $openid . &#39;&lang=zh_CN&#39;; //获取用户信息的链接
$user_info = file_get_contents($user_info_url);
$user_info_arr = json_decode($user_info, true); //将返回的json字符串转为数组
?>
Copy after login

In this code, we use access_token and openid to obtain the user’s basic information, such as user nickname, gender, city, etc. It should be noted that before obtaining the user's basic information, we need to ensure that the user has authorized the scope to snsapi_userinfo.

  1. Complete login example code
<?php
if (!isset($_GET[&#39;code&#39;]) || empty($_GET[&#39;code&#39;])) {
    //第一步:用户同意授权,获取code
    $appid = &#39;your_appid&#39;;
    $redirect_uri = urlencode(&#39;http://yourdomain.com/login.php&#39;);
    $scope = &#39;snsapi_userinfo&#39;;
    $url = &#39;https://open.weixin.qq.com/connect/oauth2/authorize?appid=&#39; . $appid . &#39;&redirect_uri=&#39; . $redirect_uri . &#39;&response_type=code&scope=&#39; . $scope . &#39;&state=STATE#wechat_redirect&#39;;
    header(&#39;Location:&#39; . $url);
    exit;
} else {
    //第二步:通过code换取网页授权access_token以及openid,再获取用户信息
    $appid = &#39;your_appid&#39;;
    $secret = &#39;your_appsecret&#39;;
    $code = $_GET[&#39;code&#39;];
    $access_token_url = &#39;https://api.weixin.qq.com/sns/oauth2/access_token?appid=&#39; . $appid . &#39;&secret=&#39; . $secret . &#39;&code=&#39; . $code . &#39;&grant_type=authorization_code&#39;;
    $access_token = file_get_contents($access_token_url);
    $access_token_arr = json_decode($access_token, true);
    $access_token = $access_token_arr[&#39;access_token&#39;];
    $openid = $access_token_arr[&#39;openid&#39;];
    $user_info_url = &#39;https://api.weixin.qq.com/sns/userinfo?access_token=&#39; . $access_token . &#39;&openid=&#39; . $openid . &#39;&lang=zh_CN&#39;;
    $user_info = file_get_contents($user_info_url);
    $user_info_arr = json_decode($user_info, true);

    //TODO:在这里可以将用户信息存入数据库,供之后使用
    //......
}
?>
Copy after login

3. Summary

As mentioned above, in a few simple steps, we can use PHP language to Implement WeChat login function. This article only introduces the most basic WeChat login implementation method. In actual application, there are more issues that need attention, such as the judgment of user permissions, the validity period of authorization, etc. I hope this article can provide some help to developers who need to implement WeChat login.

The above is the detailed content of Detailed steps to implement WeChat login function using 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 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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles