订单发货后要做三件事:给用户发站内信 + 邮件、把事件推给外部 WMS、接收 WMS 的回调更新运单。前两件是"往外发",第三件是"往里收"——用错包会让验签对不上。
场景
一条发货动作引出三种通信:面向人(站内信、邮件、短信)、面向系统(推给 WMS)、被系统调用(收 WMS 回调)。
前两者看着都是"发 HTTP 请求",但语义完全不同:面向人的要模板、要偏好、要限流、要重试到成功;面向系统的要签名、要可审计、要对方能验证来源。用一个包硬做两件事,最后一定在签名或重试策略上出问题。
开始之前
composer require wiseadmin/wise-notification wiseadmin/wise-webhook
php think vendor:publish
php think migrate:run两个 worker 都要起:queue:work --queue=notification 与 queue:work --queue=webhooks。
步骤一:站内通知 + 邮件
use wise\notification\contract\Message;
use wise\notification\facade\Notification;
$user = User::find($order->user_id);
$orderNo = $order->order_no;
// 默认异步(think-queue),模板变量放 data
Notification::channel(['email', 'database'])->send($user, new Message(
title: '订单 ' . $orderNo . ' 已发货',
content: '您的订单 {order_no} 已于 {shipped_at} 发出,承运商 {carrier}。',
data: [
'order_no' => $orderNo,
'shipped_at' => $order->ship_time,
'carrier' => $order->carrier,
'message_type' => 'order_shipped',
],
));
// 关键节点:urgent 会豁免免打扰与日配额
Notification::channel('sms')->priority('urgent')->send($user, new Message(
title: '订单异常',
content: '订单 {order_no} 支付校验失败,请尽快确认。',
data: ['order_no' => $orderNo, 'type' => 'security'],
));
// 用库内模板
Notification::channel(['email', 'database'])
->template('order_shipped')
->send($user, ['order_no' => $orderNo, 'carrier' => $order->carrier]);
// 需要结果时(后台补发/重试):单通道同步
$result = Notification::channel('email')->sync()->send($user, $message);
if ($result && !$result->success) {
// $result->error 里有失败原因
}
// 延迟 30 分钟催付
Notification::channel('sms')->delay(1800)->send($user, $message);这些调用是一次性流式状态:send() 的 finally 会 resetFluentState()。所以链式调用必须一次写完,不能把 ->sync() 的结果存起来再 send() 第二次。
步骤二:推给外部 WMS
use wise\support\backoff\BackoffStrategy;
use wise\webhook\server\WebhookServer;
WebhookServer::create()
->url('https://wms.partner.example.com/hooks/wise')
->payload([
'event' => 'order.shipped',
'order_no' => $order->order_no,
'carrier' => $order->carrier,
'tracking_no' => $order->tracking_no,
'shipped_at' => $order->ship_time,
])
->maxRetries(5)
->backoffStrategy(BackoffStrategy::exponential(1000, 60000))
->queue('webhooks')
->meta(['tenant_id' => (int) $order->tenant_id])
->dispatchToQueue();
// 条件推送:金额过阈值才通知财务
WebhookServer::create()
->url('https://finance.example.com/webhook')
->payload(['order_no' => $order->order_no, 'amount' => $order->amount])
->dispatchIf((float) $order->amount >= 10000);排队发而不是同步发:对方站点慢的时候,同步发送会把你的请求一起拖住,而且失败后你在请求里没有重试的机会。
关键结论:两套 webhook 不要混用
wise-notification 也有 webhook 通道,但它和 wise-webhook 是两套实现:
| 维度 | notification 的 webhook 通道 | wise-webhook 发送侧 |
|---|---|---|
| 签名位置 | URL query(timestamp.body) | Header X-Signature(raw body) |
| HTTP 客户端 | Guzzle | 原生 curl |
| 落库 | notification_histories | webhook_sends |
| 死信 | status = 'dead' + --dead 重放 | 只有 status = 'failed' |
选择标准:
- 对外标准回调(对方要验签、要审计、要独立重试)→
wise-webhook; - 内部通知矩阵(邮件/短信/钉钉/飞书,顺带打一个自家 webhook)→ notification 的
webhook通道; - 两者互联必须自定义
SignerInterface/SignatureValidatorInterface—— 不要指望 notification 的签名能被VerifyWebhookSignature验过。
步骤三:接收 WMS 回调
① 端点配置:
'client' => [
'endpoints' => [
'wms' => [
'signing_secret' => env('WMS_WEBHOOK_SECRET'),
'signature_header' => 'X-Signature',
'processor_class' => \app\webhook\HandleWmsCallback::class,
'queue' => 'webhooks',
'tolerance_seconds' => 300,
'store_webhook_calls' => true,
],
],
],② 路由 + 中间件(fail-closed):
use wise\webhook\client\middleware\VerifyWebhookSignature;
Route::post('webhooks/:endpoint', 'webhook/Webhook@receive')
->middleware(VerifyWebhookSignature::class);端点名解析优先级:中间件参数 > 路由参数 endpoint > _endpoint;解析不到直接抛 InvalidSignatureException,端点未配置也拒绝。这是刻意的 fail-closed——配漏一个端点等于该端点不可用,而不是"跳过验签"。
③ 控制器:
namespace app\webhook;
use think\Request;
use wise\webhook\client\WebhookClient;
class Webhook
{
public function receive(Request $request, string $endpoint = '')
{
return json(WebhookClient::receiver()->receive($request, $endpoint ?: null));
}
}receive() 会做二次验签、幂等(同端点同签名只处理一次)、落 webhook_receives(status = pending)、再投队列。控制器只负责透传,不要在里面写业务。
④ Processor:
namespace app\webhook;
use think\Request;
use wise\webhook\client\contract\WebhookProcessorInterface;
use wise\webhook\client\model\WebhookReceiveModel;
class HandleWmsCallback implements WebhookProcessorInterface
{
public function handle(WebhookReceiveModel $webhookCall, Request $request): void
{
$payload = $webhookCall->payload; // 已 JSON 解码
if (($payload['event'] ?? '') !== 'order.shipped') {
return; // 未订阅事件:静默成功
}
$order = \app\admin\model\Order::where('order_no', $payload['order_no'] ?? '')->find();
if ($order === null) {
throw new \RuntimeException('订单不存在:' . ($payload['order_no'] ?? ''));
}
$order->save([
'status' => 'shipped',
'ship_time' => $payload['shipped_at'] ?? date('Y-m-d H:i:s'),
]);
// 通知逻辑复用步骤一,这里只传运单信息
notify_shipped($order, $payload['carrier'] ?? '', $payload['tracking_no'] ?? '');
}
}Processor 拿到的是重建的独立 Request,不要在里面用 request() 助手——它指向的是 worker 里的当前请求,不是回调那一份。
步骤四:失败告警
// app/event.php
return ['listen' => [
\wise\webhook\server\event\WebhookFailed::class => [\app\listener\WebhookDownAlert::class],
]];class WebhookDownAlert
{
public function handle(\wise\webhook\server\event\WebhookFailed $event): void
{
if ($event->willRetry) {
return; // 还有重试机会,先不惊动人
}
\wise\notification\facade\Notification::channel(['dingtalk', 'email'])
->priority('urgent')->sync()->send(
\app\model\User::find(1),
new \wise\notification\contract\Message(
title: 'Webhook 最终失败',
content: '目标 {url} 共尝试 {attempts} 次仍失败:{error}',
data: ['url' => $event->url, 'attempts' => $event->attempt, 'error' => $event->error],
)
);
}
}willRetry = false 才是告警时机。每次失败都告警,运维第一天就会把告警群静音。
两个包的配置对照
| 关注点 | notification | webhook |
|---|---|---|
| 重试 | retry.max_attempts = 5、backoff = [1,5,15,60,240] 分钟 | retry.max_attempts = 3、linear、1000~60000ms |
| 熔断 | 阈值 5,前缀 wise_notification:cb | 阈值 5,前缀 wise_webhook:cb,只计 5xx |
| 死信 | status = 'dead' | 只有 status = 'failed' |
| 告警 | 监听 NotificationFailed | WebhookFailed 且 willRetry = false |
notification 的 clean-history 已预置进 config/wise-crontab.php(每天 03:30),不用自己加;webhook 的发送记录没有自动清理,长期运行要自己按 webhook_sends 建清理任务。
自查
php think wise:notification:health
php think queue:work --queue=notification
php think queue:work --queue=webhooks三条同时成立:
- 触发发货后,用户收到站内信与邮件,
webhook_sends有成功记录; - 用错误签名 POST 回调端点被
VerifyWebhookSignature拒绝(而不是处理成功); - 同一回调重复投递只处理一次(幂等生效)。
两个包的完整能力见多通道通知、Webhook 发送与接收。