Example

This page provides a complete example of implementing Web Push notifications using the standalone library (without Symfony).

Complete Working Example

Step 1: Installation

composer require spomky-labs/web-push-lib
composer require symfony/http-client
composer require symfony/clock

Step 2: Generate VAPID Keys

# Generate private key
openssl ecparam -genkey -name prime256v1 -out private_key.pem

# Extract public key
openssl ec -in private_key.pem -pubout -outform DER|tail -c 65|base64|tr -d '=' |tr '/+' '_-' > public_key.txt

# Extract private key
openssl ec -in private_key.pem -outform DER|tail -c +8|head -c 32|base64|tr -d '=' |tr '/+' '_-' > private_key.txt

Step 3: Create the Web Push Service

Step 4: Create a Subscription Manager

Step 5: Handle Subscription from Browser

Step 6: Send Notifications

Step 7: Usage Example

Step 8: Client-side JavaScript

Step 9: Simple HTML Page

Running the Example

  1. Generate VAPID keys (Step 2)

  2. Create the directory structure:

  3. Save your keys in the keys/ directory

  4. Start a PHP development server:

  5. Visit http://localhost:8000 and click "Subscribe to Notifications"

  6. Send a test notification:

Notes

  • This example uses file-based storage for simplicity. In production, use a database.

  • The WebPush\Subscription class handles all the complexity of Web Push subscriptions.

  • Always handle errors when sending notifications, as subscriptions can expire.

  • The service worker must be served from the root of your domain or use the Service-Worker-Allowed header.

Last updated

Was this helpful?