微信SDK EasyWeChat for Laravel, 基於w7corp/easywechat
7.x 起不再默認支援Lumen。
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
建立設定檔:
php artisan vendor:publish --provider="OvertrueLaravelWeChatServiceProvider"
可選,新增別名
'aliases' => [// ...'EasyWeChat' => OvertrueLaravelWeChatEasyWeChat::class, ],
每個模組基本上都支援多帳號,預設為default
。
在中介軟體AppHttpMiddlewareVerifyCsrfToken
排除微信相關的路由,如:
protected $except = [// ...'wechat', ];
對於Laravel 11.x 可以使用bootstrap/app.php
中的$middleware->validateCsrfTokens
方法:
->withMiddleware(function (Middleware $middleware) {$middleware->validateCsrfTokens(except: [// ...'wechat', ]); })
下面以接收普通訊息為例寫一個例子。
路由:
Route::any('/wechat', 'WeChatController@serve');
注意:一定是
Route::any
, 因為微信服務端認證的時候是GET
, 接收用戶訊息時是POST
!
然後建立控制器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 "歡迎追蹤 overtrue!"; });return $server->serve(); } }
使用中間件的情況下app/config/easywechat.php
中的oauth.callback
就隨便填寫吧(因為用不著了)。
在app/Http/Kernel.php
中加入路由中間件:
protected $routeMiddleware = [// ...'easywechat.oauth' => OvertrueLaravelWeChatMiddlewareOAuthAuthenticate::class, ];
在路由中新增中間件:
//...Route::group(['middleware' => ['web', 'easywechat.oauth']], function () { Route::get('/user', function () {$user = session('easywechat.oauth_user.default'); // 取得授權使用者資料dd($user); }); });
中間件支援指定配置名稱: 'easywechat.oauth:default'
,當然,你也可以在中間件參數指定目前的scopes
:
Route::group(['middleware' => ['easywechat.oauth:snsapi_userinfo']], function () { // ...});// 或指定帳戶的同時指定scopes:Route::group([ 'middleware' => ['easywechat.oauth:default,snsapi_userinfo']], function () { // ...});
上面的路由定義了/user
是需要微信授權的,那麼在這條路由的回調或控制器對應的方法裡, 你就可以從session('easywechat.oauth_user.default')
拿到已經授權的用戶資訊了。
有時候我們希望在本地開發完成後線上才真實的走微信授權流程,這將減少我們的開發成本,那麼你需要做以下兩步:
準備模擬授權資料:
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', ]);
以上欄位在scope 為
snsapi_userinfo
時盡可能配置齊全哦,當然,如果你的模式只是snsapi_base
的話只需要openid
就好了。
將資料寫入session:
注意:一定要在呼叫OAuth 中間件之前寫入,例如你可以建立一個全域中間件來完成這件事兒,只在開發環境啟用即可。
session(['easywechat.oauth_user.default' => $user]); // 同理,`default` 可以更換為您對應的其它配置名
你可以監聽對應的事件,並對事件發生後執行對應的操作。
OAuth 網頁授權: OvertrueLaravelWeChatEventsWeChatUserAuthorized
// 事件有以下屬性$event->user; // 同session('easywechat.oauth_user.default') 一樣$event->isNewSession; // 是不是新的會話(第一次建立session 時為true) $event->account; // 目前中間件所使用的帳號,對應於設定檔中的設定項名稱
您可以適用內建的OvertrueLaravelWeChatTraitsHandleOpenPlatformServerEvents
來快速完成開放平台的服務端驗證工作:
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: 預設會根據微信開放平台的推送內容觸發如下事件,你可以監聽對應的事件並進行處理:
授權方成功授權: OvertrueLaravelWeChatEventsOpenPlatformAuthorized
授權方更新授權: OvertrueLaravelWeChatEventsOpenPlatformAuthorizeUpdated
授權者取消授權: OvertrueLaravelWeChatEventsOpenPlatformUnauthorized
開放平台推送VerifyTicket: OvertrueLaravelWeChatEventsOpenPlatformVerifyTicketRefreshed
// 事件有以下屬性$message = $event->payload; // 開放平台事件通知內容
配置後http://example.com/open-platform/server
則為開放平台第三方應用設定的授權事件接收URL。
更多SDK 的具體使用請參考:https://www.easywechat.com
如果你喜歡我的專案並想支持它,請點擊這裡
Many thanks to Jetbrains for kindly providing a license for me to work on this and other open-source projects.
想知道如何從零開始建立PHP 擴充包?
請關注我的實戰課程,我會在此課程中分享一些擴展開發經驗—— 《PHP 擴展包實戰教程- 從入門到發布》
MIT