


How to quickly integrate WeChat login with PHP's laravel framework
This article is aimed at users of the PHP language laravel framework. It introduces a simple integrated WeChat login method based on this framework. How to use it:
1. Install php_weixin_provider
Run composer require thirdproviders/weixin under the project to complete the installation. After successful installation, you should be able to see the php_weixin_provider library file in the project's vendor directory:
2. Configure WeChat login parameters
There are a total of 7 parameters that can be configured, namely:
client_id: corresponding to the application appid created by the official account
client_secret: corresponding to the application appid created by the public account
redirect: Corresponds to the callback address after successful WeChat authorization
proxy_url: corresponds to the proxy service address authorized by WeChat (you can read this article to understand its function)
device: The difference is between WeChat login on PC and WeChat login on mobile. The default value is PC. If it is mobile, it can be set to empty.
state_cookie_name: The authorization link will contain a random state parameter. This parameter will be returned intact when WeChat calls back. At that time, you can determine whether the request is valid by verifying whether the state parameter is the same as the parameter passed in the authorization link. Prevent CSRF attacks. This solution will first save the state parameter into the cookie during authorization, so this parameter is used to specify the name of the cookie where the state parameter is stored. The default value is wx_state_cookie
state_cookie_time: Specifies the validity period of wx_state_cookie, the default is 5 minutes
There are 2 setting methods for these seven parameters.
The first is to configure these parameters in uppercase letters in the .env configuration file:
Note: 1. Each configuration item is capitalized and starts with WEIXIN_; 2. The first three configuration items are not exactly the same as the parameter names introduced earlier. KEY corresponds to client_id, SECRET corresponds to client_secret, and REDIRECT_URI corresponds to redirect; 3. Others are consistent with the parameter names introduced previously.
The second is to configure these parameters into the config/services.php file:
For configuration in this way, the name of each configuration item is consistent with that introduced previously.
Things to note:
Since php_weixin_provider is implemented based on laravel/socialite, it requires that client_id, client_secret and redirect must be configured, otherwise an error will occur during the instantiation process of php_weixin_provider; for client_id and client_secret, I think it is no problem to configure them in one place, but for redirect, If configured uniformly, it may not meet the needs of all scenarios, because not every place where WeChat login is used, the final callback address is the same; so it is recommended to configure the redirect to a valid or invalid non-empty callback address; anyway When using php_weixin_provider later, you can also change the value of this parameter when calling.
If proxy_url exists, it is recommended to configure it in a public place;
Since state_cookie_name and state_cookie_time both have default values, there is basically no need to reconfigure them;
The device can be specified when using it.
All configuration parameters can be respecified during use.
3. Register php_weixin_provider
In the project's config/app.php file, find the providers configuration section and add the following code to its configuration array:
4. Register for monitoring of third-party login events
Add the following code to the project's app/Providers/EventServiceProvider.php:
The laravel framework as a whole is an IOC and event-driven idea. If you are familiar with js, you will be very familiar with event-driven. If you are familiar with design patterns, you will be familiar with IOC (Inversion of Control, also known as DI: Dependency Injection). This is The key to understanding the role of configuration in steps 3 and 4.
5. Write an interface for WeChat login
Examples are as follows:
//采用代理跳转,从PC端微信登录 Route::get('/login', function () { return Socialite::with('weixin') ->setProxyUrl('http://proxy.your.com') ->setRedirectUrl(url('/login/notify')) ->redirect(); }); //采用代理跳转,从手机端微信登录 Route::get('/login2', function () { return Socialite::with('weixin') ->setProxyUrl('http://proxy.your.com') ->setDevice('') ->setRedirectUrl(url('/login/notify')) ->redirect(); }); //不采用代理跳转,从PC端微信登录 Route::get('/login', function () { return Socialite::with('weixin') ->setRedirectUrl(url('/login/notify')) ->redirect(); }); //不采用代理跳转,从手机端微信登录 Route::get('/login4', function () { return Socialite::with('weixin') ->setDevice('') ->setRedirectUrl(url('/login/notify')) ->redirect(); });
Socialite::with('weixin') will return an instance of php_weixin_provider, which is:
拿到这个实例之后,就可以采用链式的方式调用它提供的所有public方法,比如设置配置参数,setDevice等等。
6. 编写微信登录回调的接口
举例如下:
//登录回调 Route::get('/login/notify', function () { $user = null; try { $user = Socialite::with('weixin')->user(); } catch(\Exception $e) { return '获取微信用户异常'; } return $user->nickname; });
通过Socialite::with('weixin')拿到php_weixin_provider实例后,调用user方法,就会自动跟微信调用相关接口,并把微信的返回值封装成对象返回。如果在此过程中,有任何错误都会以异常的形式抛出,比如state参数校验失败,比如code失效等。
返回的$user对象包含的有效属性有:
小结:
这个方案是基于laravel/socialite实现,并发布到composer来使用的。laravel/socialite是laravel官方提供的第三方登录的模块,基于它可以很方便的集成大部分第三方平台的认证,目前它官方已经提供很多第三方的登录实现:https://socialiteproviders.github.io/。除了国外的facebook,google,github等,国内的微信,微博,qq也都有提供。我在一开始也用的是它官方提供的默认的微信登录provider来做的,但是后来我发现了以下几个问题:
1. 不支持微信授权的代理;
2. pc端跟移动端竟然还是分两个项目来做的:
3. 它封装的user对象里竟然不包含unionid
4. 更改配置参数的方式,实在是让人觉得难以使用:
所以我就在它官方的微信登录provider基础上,按照自己的想法,重新实现了一个来解决我发现的这些问题。
更多How to quickly integrate WeChat login with PHPs laravel framework相关文章请关注PHP中文网!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

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,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

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.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

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

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...

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.
