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。
配置里的关键默认值
| 键 | 默认 | 说明 |
|---|---|---|
default | email | 不指定通道时用哪个 |
sync | false | 默认走队列,同步发送要显式 sync() |
channels.* | — | 凭证全部来自 .env,不写配置文件 |
channels.webhook.allow_message_endpoint | false | SSRF 开关,别打开 |
queue.connection / queue.queue | redis / notification | worker 要消费这个队列 |
middleware | [PreferenceCheckMiddleware] | 偏好检查在这一层 |
template.engine_mode | extended | allow_object_access / allow_raw_output 默认关闭 |
retry.max_attempts | 5 | 退避 [1,5,15,60,240] 分钟 |
throttle | 开,窗口 30s / 每人 10 条 | critical.types = ['verify_code','security'] 豁免 |
quota.per_user_daily | 20 | 日配额,urgent 可豁免 |
circuit | 阈值 5、超时 60s | 连续失败即熔断该通道 |
audit.mask_fields | 15 条 | 落库前脱敏 |
history_retention_days | 90 | 历史保留 |
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=notificationclean-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。