亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Backend Development PHP Tutorial How to quickly integrate WeChat login with PHP's laravel framework

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

Jan 14, 2017 am 11:44 AM

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:

//采用代理跳轉(zhuǎn),從PC端微信登錄
Route::get('/login', function () {
 return Socialite::with('weixin')
  ->setProxyUrl('http://proxy.your.com')
  ->setRedirectUrl(url('/login/notify'))
  ->redirect();
});
//采用代理跳轉(zhuǎn),從手機端微信登錄
Route::get('/login2', function () {
 return Socialite::with('weixin')
  ->setProxyUrl('http://proxy.your.com')
  ->setDevice('')
  ->setRedirectUrl(url('/login/notify'))
  ->redirect();
});
//不采用代理跳轉(zhuǎn),從PC端微信登錄
Route::get('/login', function () {
 return Socialite::with('weixin')
  ->setRedirectUrl(url('/login/notify'))
  ->redirect();
});
//不采用代理跳轉(zhuǎn),從手機端微信登錄
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:

How to quickly integrate WeChat login with PHPs laravel framework

拿到這個實例之后,就可以采用鏈?zhǔn)降姆绞秸{(diào)用它提供的所有public方法,比如設(shè)置配置參數(shù),setDevice等等。

6. 編寫微信登錄回調(diào)的接口

舉例如下:

//登錄回調(diào)
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實例后,調(diào)用user方法,就會自動跟微信調(diào)用相關(guān)接口,并把微信的返回值封裝成對象返回。如果在此過程中,有任何錯誤都會以異常的形式拋出,比如state參數(shù)校驗失敗,比如code失效等。

返回的$user對象包含的有效屬性有:

How to quickly integrate WeChat login with PHPs laravel framework

小結(jié):

這個方案是基于laravel/socialite實現(xiàn),并發(fā)布到composer來使用的。laravel/socialite是laravel官方提供的第三方登錄的模塊,基于它可以很方便的集成大部分第三方平臺的認(rèn)證,目前它官方已經(jīng)提供很多第三方的登錄實現(xiàn):https://socialiteproviders.github.io/。除了國外的facebook,google,github等,國內(nèi)的微信,微博,qq也都有提供。我在一開始也用的是它官方提供的默認(rèn)的微信登錄provider來做的,但是后來我發(fā)現(xiàn)了以下幾個問題:

1. 不支持微信授權(quán)的代理;

2. pc端跟移動端竟然還是分兩個項目來做的:?

How to quickly integrate WeChat login with PHPs laravel framework

3. 它封裝的user對象里竟然不包含unionid

4. 更改配置參數(shù)的方式,實在是讓人覺得難以使用:?

How to quickly integrate WeChat login with PHPs laravel framework

所以我就在它官方的微信登錄provider基礎(chǔ)上,按照自己的想法,重新實現(xiàn)了一個來解決我發(fā)現(xiàn)的這些問題。

更多How to quickly integrate WeChat login with PHPs laravel framework相關(guān)文章請關(guān)注PHP中文網(wǎng)!


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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

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)

Hot Topics

How to check if an email address is valid in PHP? How to check if an email address is valid in PHP? Sep 21, 2025 am 04:07 AM

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

MySQL conditional aggregation: Use CASE statement to implement condition summing and counting of fields MySQL conditional aggregation: Use CASE statement to implement condition summing and counting of fields Sep 16, 2025 pm 02:39 PM

This article discusses in depth how to use CASE statements to perform conditional aggregation in MySQL to achieve conditional summation and counting of specific fields. Through a practical subscription system case, it demonstrates how to dynamically calculate the total duration and number of events based on record status (such as "end" and "cancel"), thereby overcoming the limitations of traditional SUM functions that cannot meet the needs of complex conditional aggregation. The tutorial analyzes the application of CASE statements in SUM functions in detail and emphasizes the importance of COALESCE when dealing with the possible NULL values ??of LEFT JOIN.

How to make a deep copy or clone of an object in PHP? How to make a deep copy or clone of an object in PHP? Sep 21, 2025 am 12:30 AM

Useunserialize(serialize($obj))fordeepcopyingwhenalldataisserializable;otherwise,implement__clone()tomanuallyduplicatenestedobjectsandavoidsharedreferences.

How to merge two arrays in PHP? How to merge two arrays in PHP? Sep 21, 2025 am 12:26 AM

Usearray_merge()tocombinearrays,overwritingduplicatestringkeysandreindexingnumerickeys;forsimplerconcatenation,especiallyinPHP5.6 ,usethesplatoperator[...$array1,...$array2].

How to use namespaces in a PHP project? How to use namespaces in a PHP project? Sep 21, 2025 am 01:28 AM

NamespacesinPHPorganizecodeandpreventnamingconflictsbygroupingclasses,interfaces,functions,andconstantsunderaspecificname.2.Defineanamespaceusingthenamespacekeywordatthetopofafile,followedbythenamespacename,suchasApp\Controllers.3.Usetheusekeywordtoi

How to update a record in a database with PHP? How to update a record in a database with PHP? Sep 21, 2025 am 04:47 AM

ToupdateadatabaserecordinPHP,firstconnectusingPDOorMySQLi,thenusepreparedstatementstoexecuteasecureSQLUPDATEquery.Example:$pdo=newPDO("mysql:host=localhost;dbname=your_database",$username,$password);$sql="UPDATEusersSETemail=:emailWHER

What are magic methods in PHP and provide an example of `__call()` and `__get()`. What are magic methods in PHP and provide an example of `__call()` and `__get()`. Sep 20, 2025 am 12:50 AM

The__call()methodistriggeredwhenaninaccessibleorundefinedmethodiscalledonanobject,allowingcustomhandlingbyacceptingthemethodnameandarguments,asshownwhencallingundefinedmethodslikesayHello().2.The__get()methodisinvokedwhenaccessinginaccessibleornon-ex

How to get the file extension in PHP? How to get the file extension in PHP? Sep 20, 2025 am 05:11 AM

Usepathinfo($filename,PATHINFO_EXTENSION)togetthefileextension;itreliablyhandlesmultipledotsandedgecases,returningtheextension(e.g.,"pdf")oranemptystringifnoneexists.

See all articles