web-push-php

repository·master·Indexed 23 days ago

https://github.com/web-push-libs/web-push-php

A PHP library for sending push messages to browser endpoints following the Web Push protocol (RFC 8030). It supports VAPID authentication (RFC 8292), PSR-18/PSR-17 compliance, and provides tools for queueing notifications, handling MessageSentReport for delivery tracking, and managing subscriptions. Requires PHP 8.2+ for the latest version, with legacy versions available for PHP 5.6 through 8.1.

Tokens
4.6K
Snippets
5
Records
31
Agent score
82%

What's inside web-push-php

  1. Note on Firebase Cloud Messaging (FCM) compatibility

    master

    This library does not support Firebase Cloud Messaging (FCM).

    While the Legacy HTTP protocol used by FCM and Web Push with VAPID share the same endpoint URL (https://fcm.googleapis.com/fcm/send), they are different protocols. Support for the outdated FCM subscription has been removed. Web Push with VAPID remains available at that URL and requires no action.

  2. Send push messages with WebPush

    master

    To send push notifications, you can either queue multiple notifications and then flush them all at once, or send a single notification immediately.

    1. Queueing: Use queueNotification($subscription, $payload) to add notifications to a queue. Then, call flush() to send them. flush() returns a generator of MessageSentReport objects.
    2. Single Send: Use sendOneNotification($subscription, $payload) to send a single notification and get a MessageSentReport immediately.

    Subscriptions can be created from a JSON object (the result of calling .toJSON() on a client-side PushSubscription) using Subscription::create().

  3. Framework integrations and plugins

    master

    If you are using a major PHP framework, there are existing bundles available:

    Symfony:

    • MinishlinkWebPushBundle
    • bentools/webpush-bundle (for associating users to WebPush subscriptions)

    Laravel:

    • laravel-notification-channels/webpush

    WordPress:

    • Perfecty Push Notifications plugin
  4. Generate VAPID keys

    master

    You can generate uncompressed public and secret keys using OpenSSL in a Linux bash environment:

    $ openssl ecparam -genkey -name prime256v1 -out private_key.pem
    $ openssl ec -in private_key.pem -pubout -outform DER|tail -c 65|base64|tr -d '=' |tr '/+' '_-' >> public_key.txt
    $ openssl ec -in private_key.pem -outform DER|tail -c +8|head -c 32|base64|tr -d '=' |tr '/+' '_-' >> private_key.txt

    Alternatively, you can use the PHP helper function:

    var_dump(VAPID::createVapidKeys());

    Note: On the client-side, you must subscribe using the VAPID public key as the applicationServerKey.

  5. Scale WebPush performance and throughput

    master

    To handle high volumes of push notifications, follow these scaling strategies:

    1. Enable MultiCurl: Ensure the MultiCurl extension is available on your server to allow concurrent requests.
    2. Use Async Adapters: Install an HTTPlug async adapter, such as php-http/guzzle7-adapter, to improve non-blocking request handling.
    3. Optimize Batch Sizes: Adjust the batch size via defaultOptions or by passing it as a parameter to the flush() method.
    4. Use Concurrent Requests: Use flushPooled() instead of flush(). The flushPooled() method uses concurrent requests, which can significantly accelerate the process and often double the speed of requests.
  6. Customize the HTTP client and enable concurrent sending

    master

    WebPush is PSR-18 and PSR-17 compliant. It uses php-http/discovery to auto-detect a client (like Guzzle or Symfony HttpClient) if none is provided.

    To use a specific client configuration (e.g., custom timeouts or proxies), instantiate your own PSR-18 client and pass it to the WebPush constructor.

    To enable concurrent sending via flushPooled(), you must install an HTTPlug async client adapter (e.g., php-http/guzzle7-adapter) so that an Http\Client\HttpAsyncClient is available.

  7. Configure VAPID authentication

    master

    VAPID (RFC8292) is required to authenticate your server with push services. You must provide a subject (an email starting with mailto: or an https:// URL) and your VAPID keys.

    When instantiating WebPush, you can pass authentication details in the $auth array using one of three methods:

    1. Direct Keys: Provide publicKey and privateKey (Base64-URL encoded).
    2. PEM File: Provide a path to a .pem file via pemFile.
    3. PEM Content: Provide the raw string content of a PEM file via pem.

    To improve performance when sending multiple notifications to the same service, call $webPush->setReuseVAPIDHeaders(true) to reuse the same JWT token for the session.

    $auth = [
        'VAPID' => [
            'subject' => 'mailto:me@website.com',
            'publicKey' => '~88 chars',
            'privateKey' => '~44 chars',
        ],
    ];
    
    $webPush = new WebPush($auth);
  8. System Requirements for WebPush

    master

    To use the latest version of WebPush, you must have PHP 8.2+ installed along with the following PHP extensions:

    • mbstring
    • curl
    • openssl (must have elliptic curve support)
    • bcmath and/or gmp (optional, but highly recommended for better performance)
  9. Configure notification options (TTL, Urgency, Topic, etc.)

    master

    You can set default options for all notifications via the constructor or setDefaultOptions(), or specify them for a single notification.

    Supported options:

    • TTL: Time To Live in seconds (default: 4 weeks). Set to 0 for immediate delivery only.
    • urgency: very-low, low, normal, or high.
    • topic: A string (max 32 chars) to group notifications; vendors may only show the last one of a topic.
    • batchSize: Number of notifications per batch (default: 1000). Use $webPush->flush($batchSize) to override during flush.
    • contentType: The Content-Type header (default: application/octet-stream). Use application/json for Declarative push messages.
    $defaultOptions = [
        'TTL' => 300,
        'urgency' => 'normal',
        'topic' => 'newEvent',
        'batchSize' => 200,
        'contentType' => 'application/json',
    ];
    
    $webPush = new WebPush([], $defaultOptions);
    // Or for a single notification:
    $webPush->sendOneNotification($subscription, $payload, ['TTL' => 5000]);
  10. Initialize the WebPush client

    master

    The WebPush class is the main entry point for sending notifications. You can initialize it with authentication details (like VAPID), default options, and optional PSR-compliant HTTP clients and factories. If no clients are provided, the library attempts to auto-discover them using Http//Discovery (e.g., Guzzle for PSR-18).

    Constructor Parameters

    • array $auth: Authentication details. If providing VAPID, use the VAPID key.
    • array $defaultOptions: Default settings for all notifications in this instance (TTL, urgency, topic, batchSize, etc.).
    • ?ClientInterface $client: An optional PSR-18 HTTP client. Use this to configure timeouts, proxies, or redirects.
    • ?RequestFactoryInterface $requestFactory: An optional PSR-17 request factory.
    • ?StreamFactoryInterface $streamFactory: An optional PSR-17 stream factory.
    • ?HttpAsyncClient $asyncClient: An optional HTTPlug async client, required for concurrent sending via flushPooled().
    • ?LoggerInterface $logger: An optional PSR-3 logger.