WeChat SDK EasyWeChat for Laravel, based on w7corp/easywechat
Lumen is no longer supported by default starting from 7.x.
overtrue/laravel-wechat:^7.0 -> Laravel >= 8.0
overtrue/laravel-wechat:^6.0 -> Laravel/Lumen >= 7.0
overtrue/laravel-wechat:^5.1 -> Laravel/Lumen >= 5.1
composer require overtrue/laravel-wechat:^7.2
Create configuration file:
php artisan vendor:publish --provider="OvertrueLaravelWeChatServiceProvider"
Optional, add an alias
'aliases' => [// ...'EasyWeChat' => OvertrueLaravelWeChatEasyWeChat::class, ],
Each module basically supports multiple accounts, and the default is default
.
Exclude WeChat-related routes in the middleware AppHttpMiddlewareVerifyCsrfToken
, such as:
protected $except = [// ...'wechat', ];
For Laravel 11.x, you can use the $middleware->validateCsrfTokens
method in bootstrap/app.php
:
->withMiddleware(function (Middleware $middleware) {$middleware->validateCsrfTokens(except: [// ...'wechat', ]); })
Let's write an example using receiving ordinary messages as an example.
routing:
Route::any('/wechat', 'WeChatController@serve');
Note: It must be
Route::any
, because the WeChat server usesGET
when authenticating, andPOST
when receiving user messages!
Then create the controller WeChatController
:
<?phpnamespace AppHttpControllers;use Log;class WeChatController extends Controller {public function serve() { Log::info('request arrived.'); $server = app('easywechat.official_account')->getServer();$server->with(function($message){return "Welcome to follow overtrue!"; });return $server->serve(); } }
When using middleware, just fill in oauth.callback
in app/config/easywechat.php
casually (because it is no longer needed).
Add routing middleware in app/Http/Kernel.php
:
protected $routeMiddleware = [// ...'easywechat.oauth' => OvertrueLaravelWeChatMiddlewareOAuthAuthenticate::class, ];
Add middleware to the route:
//...Route::group(['middleware' => ['web', 'easywechat.oauth']], function () { Route::get('/user', function () {$user = session('easywechat.oauth_user.default'); // Get authorized user information dd($user); }); });
The middleware supports specifying the configuration name: 'easywechat.oauth:default'
. Of course, you can also specify the current scopes
in the middleware parameters:
Route::group(['middleware' => ['easywechat.oauth:snsapi_userinfo']], function () { // ...});// Or specify the account and scopes:Route::group([ 'middleware' => ['easywechat.oauth:default,snsapi_userinfo']], function () { // ...});
The above route defines that /user
requires WeChat authorization, so in the callback of this route or the corresponding method of the controller , you can get the authorized user information from session('easywechat.oauth_user.default')
.
Sometimes we want to actually go through the WeChat authorization process online after local development is completed. This will reduce our development costs. Then you need to do the following two steps:
Prepare simulation authorization information:
use IlluminateSupportArr;use OvertrueSocialiteUser as SocialiteUser;$user = new SocialiteUser(['id' => 'mock-openid','name' => 'overtrue','nickname' => 'overtrue','avatar' => ' http://example.com/avatars/overtrue.png','email' => null,'original' => [],'provider' => 'WeChat', ]);
The above fields should be configured as fully as possible when the scope is
snsapi_userinfo
. Of course, if your mode is onlysnsapi_base
, you only needopenid
.
Write data to session:
Note: Be sure to write before calling the OAuth middleware. For example, you can create a global middleware to accomplish this and enable it only in the development environment.
session(['easywechat.oauth_user.default' => $user]); // Similarly, `default` can be replaced with other configuration names corresponding to yours
You can listen to the corresponding events and perform corresponding operations after the events occur.
OAuth web authorization: OvertrueLaravelWeChatEventsWeChatUserAuthorized
// This event has the following attributes $event->user; // Same as session('easywechat.oauth_user.default') $event->isNewSession; // Is it a new session (true when the session is created for the first time) $event->account; //The account currently used by the middleware, corresponding to the configuration item name in the configuration file
You can use the built-in OvertrueLaravelWeChatTraitsHandleOpenPlatformServerEvents
to quickly complete the server-side verification of the open platform:
routes/web.php:
Route::any('/open-platform/server', OpenPlatformController::class);
app/Http/Controllers/OpenPlatformController.php:
<?phpnamespace AppHttpControllers;use OvertrueLaravelWeChatTraitsHandleOpenPlatformServerEvents;class OpenPlatformController extends Controller {use HandleOpenPlatformServerEvents; public function __invoke(Application $application): PsrHttpMessageResponseInterface{$app = app('easywechat.open_platform'); return $this->handleServerEvents($app); } }
Tips: By default, the following events will be triggered based on the push content of the WeChat open platform. You can listen to the corresponding events and process them:
The authorizer successfully authorized: OvertrueLaravelWeChatEventsOpenPlatformAuthorized
Authorizer update authorization: OvertrueLaravelWeChatEventsOpenPlatformAuthorizeUpdated
Authorizing party cancels authorization: OvertrueLaravelWeChatEventsOpenPlatformUnauthorized
Open platform pushes VerifyTicket: OvertrueLaravelWeChatEventsOpenPlatformVerifyTicketRefreshed
// The event has the following attributes $message = $event->payload; // Open platform event notification content
After configuration, http://example.com/open-platform/server
is the authorization event receiving URL set by the open platform third-party application.
For more specific use of SDK, please refer to: https://www.easywechat.com
If you like my project and want to support it, click here
Many thanks to Jetbrains for kindly providing a license for me to work on this and other open-source projects.
Wondering how to build a PHP extension package from scratch?
Please pay attention to my practical course, where I will share some extension development experience - "PHP Extension Pack Practical Tutorial - From Getting Started to Release"
MIT