How to quickly integrate WeChat login with PHP's laravel framework

高洛峰
Release: 2023-03-04 19:10:01
Original
2198 people have browsed it

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:

How to quickly integrate WeChat login with PHPs laravel framework

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:

How to quickly integrate WeChat login with PHPs laravel framework

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:

How to quickly integrate WeChat login with PHPs laravel framework

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:

How to quickly integrate WeChat login with PHPs laravel framework

4. Register for monitoring of third-party login events

Add the following code to the project's app/Providers/EventServiceProvider.php:

How to quickly integrate WeChat login with PHPs laravel framework

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();
});
Copy after login

Socialite::with('weixin') will return an instance of php_weixin_provider, which is:

How to quickly integrate WeChat login with PHPs laravel framework

拿到这个实例之后,就可以采用链式的方式调用它提供的所有public方法,比如设置配置参数,setDevice等等。

6. 编写微信登录回调的接口

举例如下:

//登录回调
Route::get('/login/notify', function () {
 $user = null;
 try {
  $user = Socialite::with('weixin')->user();
 } catch(\Exception $e) {
  return '获取微信用户异常';
 }
 return $user->nickname;
});
Copy after login

通过Socialite::with('weixin')拿到php_weixin_provider实例后,调用user方法,就会自动跟微信调用相关接口,并把微信的返回值封装成对象返回。如果在此过程中,有任何错误都会以异常的形式抛出,比如state参数校验失败,比如code失效等。

返回的$user对象包含的有效属性有:

How to quickly integrate WeChat login with PHPs laravel framework

小结:

这个方案是基于laravel/socialite实现,并发布到composer来使用的。laravel/socialite是laravel官方提供的第三方登录的模块,基于它可以很方便的集成大部分第三方平台的认证,目前它官方已经提供很多第三方的登录实现:https://socialiteproviders.github.io/。除了国外的facebook,google,github等,国内的微信,微博,qq也都有提供。我在一开始也用的是它官方提供的默认的微信登录provider来做的,但是后来我发现了以下几个问题:

1. 不支持微信授权的代理;

2. pc端跟移动端竟然还是分两个项目来做的: 

How to quickly integrate WeChat login with PHPs laravel framework

3. 它封装的user对象里竟然不包含unionid

4. 更改配置参数的方式,实在是让人觉得难以使用: 

How to quickly integrate WeChat login with PHPs laravel framework

所以我就在它官方的微信登录provider基础上,按照自己的想法,重新实现了一个来解决我发现的这些问题。

更多How to quickly integrate WeChat login with PHPs laravel framework相关文章请关注PHP中文网!


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!