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/clockStep 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.txtStep 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
Generate VAPID keys (Step 2)
Create the directory structure:
Save your keys in the
keys/directoryStart a PHP development server:
Visit
http://localhost:8000and click "Subscribe to Notifications"Send a test notification:
Notes
This example uses file-based storage for simplicity. In production, use a database.
The
WebPush\Subscriptionclass 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-Allowedheader.
Last updated
Was this helpful?