在开发一个需要实时通知用户的应用时,我遇到了一个问题:如何在不打扰用户的前提下,及时将重要信息推送给他们?经过一番研究和尝试,我发现使用 laravel 结合 web 推送通知是一个理想的解决方案。然而,实现这一功能并不简单,直到我找到了 laravel-notification-channels/webpush 这个包,它通过 composer 轻松地解决了我的困扰。
首先,我通过 Composer 安装了这个包:
composer require laravel-notification-channels/webpush
安装后,我按照文档的指引,对我的 User 模型进行了修改,添加了 HasPushSubscriptions trait:
use NotificationChannelsWebPushHasPushSubscriptions; class User extends Model { use HasPushSubscriptions; }
接着,我发布了迁移文件和配置文件,并运行了迁移命令来创建必要的表:
php artisan vendor:publish --provider="NotificationChannelsWebPushWebPushServiceProvider" --tag="migrations" php artisan migrate php artisan vendor:publish --provider="NotificationChannelsWebPushWebPushServiceProvider" --tag="config"
为了确保浏览器能够正确认证,我生成了 VAPID 密钥:
php artisan webpush:vapid
这个命令会在 .env 文件中设置 VAPID_PUBLIC_KEY 和 VAPID_PRIVATE_KEY,这些密钥对于使用 Push API 是必需的。需要注意的是,如果你的应用面向 safari 或 ios 2023 年后的版本,还需要设置 VAPID_SUBJECT 变量,否则会收到 BadJwtToken 错误。
接下来,我在通知类中使用了 WebPushChannel 发送推送通知:
use IlluminateNotificationsNotification; use NotificationChannelsWebPushWebPushMessage; use NotificationChannelsWebPushWebPushChannel; class AccountApproved extends Notification { public function via($notifiable) { return [WebPushChannel::class]; } public function toWebPush($notifiable, $notification) { return (new WebPushMessage) ->title('Approved!') ->icon('/approved-icon.png') ->body('Your account was approved!') ->action('View account', 'view_account') ->options(['TTL' => 1000]); } }
为了管理用户的推送订阅,我使用了 updatePushSubscription 和 deletePushSubscription 方法:
$user = AppUser::find(1); $user->updatePushSubscription($endpoint, $key, $token, $contentEncoding); $user->deletePushSubscription($endpoint);
通过这些步骤,我成功地实现了 Web 推送通知的功能。使用 Composer 安装 laravel-notification-channels/webpush 包不仅简化了整个过程,还确保了代码的可维护性和可扩展性。它的优势在于:
- 易于集成:通过 Composer 安装,快速上手。
- 高效管理:提供了简单的方法来管理用户的推送订阅。
- 跨浏览器兼容:支持多种浏览器,确保用户体验的一致性。
总的来说,使用 Composer 和 laravel-notification-channels/webpush 包让我在 Laravel 项目中轻松实现了 Web 推送通知的功能,大大提升了用户体验和应用的实时性。