跳转到正文
wise-* 包教程 20 个可独立安装的 Composer 能力包:选包、装包、调用、扩展

多通道通知 wise-notification

1 2026-11-25 23:02:34

8 个通道(邮件、短信、钉钉、企微、飞书、通用 Webhook、公众号模板、站内信)+ 模板编译 + 偏好与节流 + 重试退避 + 死信 + 断路器 + 落库脱敏。一句话:它负责"把消息发出去并确保有记录",不负责决定"什么时候发"。

安装

composer require wiseadmin/wise-notification

composer require phpmailer/phpmailer          # 按需
composer require alibabacloud/dysmsapi
composer require tencentcloud/sms

php think migrate:run

建 5 张表:模板、历史、站内信、偏好、审计日志。extra.think.services 注册 NotificationServiceProvider;配置发布为 config/wise-notification.php。

配置里的关键默认值

键默认说明
defaultemail不指定通道时用哪个
syncfalse默认走队列,同步发送要显式 sync()
channels.*—凭证全部来自 .env,不写配置文件
channels.webhook.allow_message_endpointfalseSSRF 开关,别打开
queue.connection / queue.queueredis / notificationworker 要消费这个队列
middleware[PreferenceCheckMiddleware]偏好检查在这一层
template.engine_modeextendedallow_object_access / allow_raw_output 默认关闭
retry.max_attempts5退避 [1,5,15,60,240] 分钟
throttle开,窗口 30s / 每人 10 条critical.types = ['verify_code','security'] 豁免
quota.per_user_daily20日配额,urgent 可豁免
circuit阈值 5、超时 60s连续失败即熔断该通道
audit.mask_fields15 条落库前脱敏
history_retention_days90历史保留

throttle 与 quota 是两回事:前者防"30 秒内刷 10 条",后者防"一天发 20 条营销"。验证码、安全提醒这类消息通过 critical.types 豁免,这是它们能"必达"的原因。

Notification 门面

use wise\notification\contract\Message;
use wise\notification\facade\Notification;

Notification::channel('email')
    ->template('welcome')
    ->priority('urgent')
    ->send($user, new Message(
        title: '欢迎注册',
        content: '感谢您注册我们的平台!',
        data: ['name' => $user->name]
    ));

方法:channel()(支持数组多通道)、template()、priority()、sync()、delay(int)、batch()、dispatch()、send();扩展点 extend()、extendMiddleware()。接收者模型要实现 Notifiable,推荐同时 use NotifiableTrait。

一个容易踩的语义:这些是一次性流式状态,send() 结束时的 finally 会 resetFluentState()。所以 Notification::channel('sms')->sync() 的返回链不能存起来复用——第二次 send() 会拿到空通道。

运维命令

php think wise:notification:send --channel=email --to=... --title=... --content=... --sync
php think wise:notification:retry-failed --channel=email --date=... --max=100 --dead
php think wise:notification:health [--channel=sms]
php think wise:notification:clean-history [--days=90] [--dead-only]
php think queue:work --queue=notification

clean-history 已登记进 config/wise-crontab.php 的默认任务,每天 03:30 执行——这是与 wise-crontab 的显式衔接,不用另加。

retry-failed --dead 只重放死信(status = 'dead'),是"线上补发"的常规入口。

与 wise-support 的关系

包内复用 wise-support 的 CircuitBreaker、BackoffStrategy、RateLimiter、DistributedLock。事件有三个:NotificationSending(可 halt() 中断)、NotificationSent、NotificationFailed。

halt() 是"业务层面不该发"的最后一处拦截(比如用户已退订某类通知),比在调用前判断更稳——所有调用点都覆盖到了。

三个容易搞错的认知

一、"默认同步发送"。 默认 sync = false,走队列;没有 worker 时消息会停在"等待中"。
二、"urgent 只是文案标记"。 它同时豁免限流与日配额,是"必达通道"。
三、"allow_message_endpoint 打开更灵活"。 打开后消息内容可指定任意 URL,SSRF 风险回到你身上。

自查:php think wise:notification:health 输出各通道可用性;--channel=database --sync 发一条后 user_notifications 表有记录;retry-failed --dead 能列出死信。

框架侧概览见消息通知与 Webhook。

这篇文档对您有帮助吗?

相关文档