Installation:
composer require overtrue/laravel-wechat
Publish the config file:
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider" --tag="wechat-config"
Configuration:
Edit .env with your WeChat app credentials (e.g., WECHAT_OFFICIAL_ACCOUNT_APP_ID, WECHAT_OFFICIAL_ACCOUNT_APP_SECRET).
Update config/wechat.php to match your use case (Official Account, Mini Program, etc.).
First Use Case: Send a welcome message to a user via the Official Account API:
use Overtrue\LaravelWeChat\Facades\WeChat;
$result = WeChat::official_account->message->send([
'touser' => 'openid_or_user_id',
'msgtype' => 'text',
'text' => ['content' => 'Welcome to our service!'],
]);
config/wechat.php for service-specific settings (e.g., official_account, mini_program).Overtrue\LaravelWeChat\Facades\WeChat for quick access to all services.tests/ for real-world usage patterns (e.g., OfficialAccountTest.php).Service Initialization:
Bind services in AppServiceProvider or use facades directly:
WeChat::official_account->user->get('openid'); // Fetch user info
Event Handling:
Use middleware to validate and process WeChat requests (e.g., VerifyMiddleware for Official Accounts):
Route::middleware(['wechat.official_account.verify'])->group(function () {
Route::post('/server', 'WeChatController@server');
});
Menu Management: Dynamically update menus via the facade:
WeChat::official_account->menu->create([
'button' => [
['type' => 'click', 'name' => 'Help', 'key' => 'HELP'],
],
]);
Mini Program Integration: Handle auth and user sessions:
$code = request('code'); // From redirect
$user = WeChat::mini_program->auth->getUserByCode($code);
Template Messages: Send transactional messages with placeholders:
WeChat::official_account->template->send([
'touser' => 'openid',
'template_id' => 'YOUR_TEMPLATE_ID',
'data' => ['first' => ['value' => 'Hello'], 'keyword1' => ['value' => 'World']],
]);
wechat.message.sent).$user = cache()->remember("wechat_user_{$openid}", now()->addHours(1), fn() =>
WeChat::official_account->user->get($openid)
);
dispatch(new UploadMediaJob($mediaPath));
throttle middleware for WeChat API endpoints.Token Mismatch:
VerifyMiddleware requires the token in config/wechat.php to match WeChat’s server settings..env and config values; test with WECHAT_OFFICIAL_ACCOUNT_TOKEN=test123.OpenID vs. UserID:
openid, while Mini Programs use unionid or openid. Mixing them causes errors.dd(WeChat::official_account->user->get('openid'));
Media Uploads:
Signature Validation:
login endpoints require appid, timestamp, and nonce validation. Use the facade’s built-in helpers:
WeChat::mini_program->auth->validateSignature();
Async Processing:
event_push) may time out. Use Laravel queues or return 200 OK immediately:
return response()->json(['success' => true]);
dispatch(new ProcessWeChatEventJob($event));
WECHAT_LOG_LEVEL=debug in .env to log API requests/responses to storage/logs/wechat.log.WeChat::setMock(true) in tests to bypass real API calls:
WeChat::setMock(true);
WeChat::official_account->user->get('openid'); // Returns mock data
Custom Services:
Extend the base Service class to add domain-specific logic:
class CustomService extends \Overtrue\LaravelWeChat\Support\Service
{
public function customMethod()
{
return $this->callApi('/custom/endpoint', []);
}
}
Register in AppServiceProvider:
WeChat::extend('custom', function () {
return new CustomService(config('wechat.custom'));
});
Middleware Overrides:
Override default middleware (e.g., VerifyMiddleware) in app/Http/Kernel.php:
protected $middlewareGroups = [
'wechat' => [
\App\Http\Middleware\CustomVerifyMiddleware::class,
],
];
API Response Handling:
Modify response parsing in app/Providers/WeChatServiceProvider.php:
WeChat::extend('official_account', function ($app) {
$config = $app['config']['wechat.official_account'];
$service = new \Overtrue\EasyWeChat\OfficialAccount($config);
$service->setResponseCallback(function ($response) {
// Custom logic (e.g., error handling)
return $response;
});
return $service;
});
WECHAT_ (e.g., WECHAT_OFFICIAL_ACCOUNT_APP_ID). The package auto-loads them.official_account, mini_program, etc.) has its own config block in config/wechat.php. Ensure you’re editing the correct one.language). Override only what’s necessary.How can I help you explore Laravel packages today?