


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











There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.
