The Web Push Service

The WebPush object requires a HTTP Client and an Extension Manager.

use Symfony\Component\HttpClient\HttpClient;
use WebPush\WebPush;

$client = HttpClient::create();

$service = new WebPush($client, $extensionManager);

The service is now ready to send Notifications to the Subscriptions. The StatusReport object that is returned is explained here.

<?php

use WebPush\Subscription;
use WebPush\Notification;

$subscription = Subscription::createFromString('{"endpoint":"https://updates.push.services.mozilla.com/wpush/v2/AAAAAAAA[…]AAAAAAAAA","keys":{"auth":"XXXXXXXXXXXXXX","p256dh":"YYYYYYYY[…]YYYYYYYYYYYYY"}}');
$notification = Notification::create()
    ->withPayload('Hello world')
;

$statusReport = $service->send($notification, $subscription);

In this example, we load the Subscription object from a string, but you usually retrieve the Subscription objects from a database or a dedicated storage.

Sending to Multiple Subscriptions

The sendToMultiple() method allows you to send a notification to multiple subscriptions efficiently:

Unlike send(), the sendToMultiple() method does not throw exceptions for individual failures. It attempts to send to all subscriptions and returns a StatusReport for each one, allowing you to inspect both successes and failures.

Error Handling

The service may throw exceptions for transport or HTTP errors:

Validation Exceptions

When creating notifications with invalid properties, the library throws specific exceptions. Each exception exposes the problematic value as a public readonly property for easy debugging:

See the Exceptions documentation for complete details on error handling strategies.

Last updated

Was this helpful?