w7corp/easywechat
EasyWeChat is a PHP 8+ SDK for WeChat development by w7corp. It supports Official Accounts and more, with simple configuration and server message handling, plus active maintenance, tests, and solid documentation via easywechat.com.
Installation
composer require w7corp/easywechat:^6.19
Register the service provider in config/app.php under providers:
W7Corp\EasyWeChat\Foundation\Provider::class,
Configuration Publish the config file:
php artisan vendor:publish --provider="W7Corp\EasyWeChat\Foundation\Provider" --tag=config
Edit .env with your WeChat app credentials (e.g., WECHAT_OFFICIAL_ACCOUNT_APP_ID, WECHAT_OFFICIAL_ACCOUNT_SECRET).
First Use Case: Sending a Message
use W7Corp\EasyWeChat\OfficialAccount\Application;
$app = Application::create();
$result = $app->customer_service->message->send([
'touser' => 'openid_or_user_id',
'msgtype' => 'text',
'text' => ['content' => 'Hello, WeChat!']
]);
Handling Incoming Messages Use middleware to validate and route messages:
// app/Http/Middleware/HandleWeChat.php
public function handle($request, Closure $next) {
$app = Application::create();
$message = $app->message;
if ($message->validate()) {
$event = $message->getEvent();
// Route based on event type (e.g., text, scan, subscribe)
}
return $next($request);
}
Menu Management Create/update menus dynamically:
$menu = [
'button' => [
[
'type' => 'click',
'name' => 'Click Me',
'key' => 'CLICK_EVENT'
]
]
];
$app->menu->create($menu);
User Data Access Fetch user info via OpenID:
$user = $app->user->get('openid123');
Media Handling Upload/download media (e.g., images, voice):
// Upload
$mediaId = $app->media->upload('image', fopen('path/to/image.jpg', 'r'));
// Download
$app->media->download($mediaId, 'path/to/save.jpg');
Template Messages Send templated notifications:
$result = $app->template_message->send([
'touser' => 'openid',
'template_id' => 'YOUR_TEMPLATE_ID',
'data' => [
'first' => ['value' => 'Hello!', 'color' => '#FF0000'],
// ... other fields
]
]);
event(new WeChatMessageReceived($event));
dispatch(new ProcessWeChatMedia($mediaId));
$user = Cache::remember("wechat_user_{$openid}", now()->addHours(1), fn() =>
$app->user->get($openid)
);
HttpClient, Cache) if your Laravel app uses them:
use Symfony\Component\HttpClient\HttpClient;
$client = HttpClient::create();
Token Validation
msg_signature in middleware to prevent spoofing:
if (!$app->message->validate()) {
abort(403, 'Invalid WeChat request');
}
WECHAT_OFFICIAL_ACCOUNT_TOKEN in .env matches the token set in WeChat MP.Rate Limits
WxErrorException gracefully:
try {
$result = $app->customer_service->message->send(...);
} catch (\W7Corp\EasyWeChat\Kernel\Exceptions\WxErrorException $e) {
Log::error("WeChat API error: {$e->getCode()}: {$e->getMessage()}");
// Retry or notify admin
}
OpenID Expiry
$openid = Cache::get("wechat_openid_{$sessionKey}", function() use ($app, $sessionKey) {
return $app->oauth->getUser()->getOriginal()['openid'];
});
Media Storage
media_id) expires in 3 days. Download and store permanently if needed.JS-SDK Configuration
jsapi_ticket if it expires (hourly):
$ticket = $app->jssdk->getJsApiTicket();
Symfony Dependency Conflicts
composer.json align with EasyWeChat’s updated compatibility:
"require": {
"symfony/cache": "^6.0|^7.0|^8.0",
"symfony/http-client": "^6.0|^7.0|^8.0"
}
Enable Logging
Configure logging in config/easywechat.php:
'log' => [
'level' => 'debug',
'file' => storage_path('logs/easywechat.log'),
],
Inspect Raw Responses
Use dd($result->getOriginal()) to debug API responses.
Test in Sandbox
Use WeChat’s official sandbox environment (https://mp.weixin.qq.com) for testing before going live.
PHP 8.0+ Compatibility
// Example: Use named arguments for clarity
$app->customer_service->message->send([
'touser' => 'openid',
'msgtype' => 'text',
'text' => ['content' => 'Hello'],
]);
Custom Message Handlers
Extend the Message class to handle custom message types:
class CustomMessage extends \W7Corp\EasyWeChat\OfficialAccount\Message
{
public function handleCustomEvent($event)
{
// Logic for custom events
}
}
API Wrappers Create service classes to wrap EasyWeChat methods for your domain:
class WeChatNotificationService
{
public function sendOrderConfirmation($order)
{
$app = Application::create();
$app->template_message->send([
'touser' => $order->user->openid,
'template_id' => config('wechat.templates.order_confirmation'),
'data' => [
'order_id' => ['value' => $order->id, 'color' => '#173177'],
// ...
]
]);
}
}
Symfony Integration
Use Symfony’s HttpClient or Cache components for advanced use cases:
// Example: Using Symfony HttpClient for custom API calls
use Symfony\Component\HttpClient\HttpClient;
$client = HttpClient::create();
$response = $client->request('GET', 'https://api.weixin.qq.com/cgi-bin/user/info', [
'query' => [
'access_token' => $app->access_token,
'openid' => 'user_openid',
],
]);
Webhook Validation
For custom webhook endpoints, validate the signature manually if needed:
$app = Application::create();
$signature = $app->message->getSignature();
$timestamp = $app->message->getTimestamp();
$nonce = $app->message->getNonce();
$token = config('wechat.official_account.token');
$validSignature = sha1($token . $timestamp . $nonce);
if ($validSignature !== $signature) {
abort(403);
}
How can I help you explore Laravel packages today?