bhhaskin/laravel-webpush 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

bhhaskin/laravel-webpush

Composer 安装命令:

composer require bhhaskin/laravel-webpush

包简介

Web push notification channel for Laravel. VAPID-signed browser push delivered via Laravel's Notification system.

README 文档

README

Web Push notification channel for Laravel. Sends VAPID-signed browser push notifications via Laravel's standard Notification system. Subscriptions are polymorphic, so any model (not just User) can be notified.

Built on minishlink/web-push.

Installation

composer require bhhaskin/laravel-webpush

Publish and run the migration:

php artisan vendor:publish --tag=webpush-migrations
php artisan migrate

Optionally publish the config:

php artisan vendor:publish --tag=webpush-config

VAPID keys

Generate a keypair once per deployment:

vendor/bin/web-push generate-vapid-keys

Add to your .env:

VAPID_SUBJECT="mailto:you@example.com"
VAPID_PUBLIC_KEY="..."
VAPID_PRIVATE_KEY="..."

The public key is also served to the browser by GET /api/push-subscriptions/vapid-key.

Setup

Add the HasPushSubscriptions trait to any notifiable model:

use Bhhaskin\LaravelWebpush\Concerns\HasPushSubscriptions;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;
    use HasPushSubscriptions;
}

The trait adds pushSubscriptions(), addPushSubscription(), removePushSubscription(), and routeNotificationForWebpush(). The last is what Laravel's notification system calls to resolve delivery targets.

Sending a notification

Define toWebPush() on your notification and include 'webpush' in via():

use Bhhaskin\LaravelWebpush\Messages\WebPushMessage;
use Illuminate\Notifications\Notification;

class OrderShipped extends Notification
{
    public function __construct(public int $orderId) {}

    public function via($notifiable): array
    {
        return ['webpush'];
    }

    public function toWebPush($notifiable): WebPushMessage
    {
        return WebPushMessage::create('Your order shipped')
            ->body('Tracking is available in your dashboard.')
            ->icon('/icons/package.png')
            ->tag("order-{$this->orderId}")
            ->url("/orders/{$this->orderId}");
    }
}

Send it exactly like any other notification:

$user->notify(new OrderShipped($order->id));

The channel fans out to every PushSubscription attached to the notifiable.

Message builder

WebPushMessage is a fluent builder for the payload your service worker receives:

WebPushMessage::create('Title', 'Body')
    ->icon('/icons/icon-192.png')
    ->badge('/icons/badge-96.png')
    ->image('/images/hero.png')
    ->tag('unique-tag')          // replaces prior notifications with the same tag
    ->url('/path/to/open')       // read in the SW click handler via event.notification.data.url
    ->requireInteraction()
    ->renotify()
    ->vibrate([200, 100, 200])
    ->action('done', 'Done', '/icons/done.png')
    ->action('snooze', 'Snooze')
    ->withData(['conversation_id' => 42])
    ->ttl(3600)                   // sending option, not payload
    ->urgency('high')
    ->topic('chat-42');

toPayload() returns the JSON object delivered to the service worker. getOptions() returns the Web Push protocol options (TTL, urgency, topic) forwarded to the push service.

HTTP endpoints

When webpush.routes.enabled is true (the default), three routes are registered:

Method Path Purpose
GET /api/push-subscriptions/vapid-key Returns the public VAPID key
POST /api/push-subscriptions Subscribe the authenticated notifiable
DELETE /api/push-subscriptions Unsubscribe by endpoint

POST body:

{
  "endpoint": "https://fcm.googleapis.com/fcm/send/...",
  "keys": { "p256dh": "...", "auth": "..." }
}

Configure prefix, middleware, or controller in config/webpush.php. Set routes.enabled to false and mount PushSubscriptionController yourself if you need multiple guards or different paths.

Client-side

Subscribe from the browser and post the subscription to /api/push-subscriptions:

const { vapid_key } = await fetch('/api/push-subscriptions/vapid-key').then(r => r.json());

const registration = await navigator.serviceWorker.register('/sw.js');
await Notification.requestPermission();

const subscription = await registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(vapid_key),
});

await fetch('/api/push-subscriptions', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
    body: JSON.stringify(subscription.toJSON()),
});

function urlBase64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
    const raw = atob(base64);
    return Uint8Array.from([...raw].map(c => c.charCodeAt(0)));
}

A minimal service worker handler for the payload shape emitted by WebPushMessage::toPayload():

self.addEventListener('push', (event) => {
    const data = event.data?.json() ?? {};
    event.waitUntil(self.registration.showNotification(data.title ?? '', {
        body: data.body,
        icon: data.icon,
        badge: data.badge,
        image: data.image,
        tag: data.tag,
        actions: data.actions,
        requireInteraction: data.requireInteraction,
        renotify: data.renotify,
        silent: data.silent,
        vibrate: data.vibrate,
        data: { url: data.url, ...(data.data ?? {}) },
    }));
});

self.addEventListener('notificationclick', (event) => {
    event.notification.close();
    const url = event.notification.data?.url;
    if (!url) return;
    event.waitUntil(clients.openWindow(url));
});

Expired subscription handling

When a push service returns 404 or 410 for a subscription, the channel dispatches Bhhaskin\LaravelWebpush\Events\PushSubscriptionExpired and, unless webpush.prune_expired is false, deletes the row. Listen for the event if you need to log, notify, or take other action before the row is removed.

Configuration reference

See config/webpush.php after publishing. Key options:

  • vapid.subject / vapid.public_key / vapid.private_key: required
  • model / table: swap the Eloquent model or table name
  • routes.enabled / routes.prefix / routes.middleware / routes.controller
  • options.TTL / options.urgency / options.topic: per-request defaults
  • prune_expired: delete rows when push services report the subscription is gone

Testing

composer test

bhhaskin/laravel-webpush 适用场景与选型建议

bhhaskin/laravel-webpush 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 26 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 04 月 19 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 bhhaskin/laravel-webpush 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 bhhaskin/laravel-webpush 我们能提供哪些服务?
定制开发 / 二次开发

基于 bhhaskin/laravel-webpush 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 26
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 39
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-19