Web push notification example with PHP backend

kapilkarda picture kapilkarda · Mar 12, 2017 · Viewed 10.9k times · Source

I am looking for an example for web push notification with JS code and PHP backend. Can anyone share example code or a tutorial?

Answer

Minishlink picture Minishlink · May 6, 2017

Here's a basic example that uses web-push-php : https://github.com/Minishlink/web-push-php-example

Main PHP code is:

<?php
require __DIR__ . '/vendor/autoload.php';
use Minishlink\WebPush\WebPush;

$auth = array(
    'VAPID' => array(
        'subject' => 'https://github.com/Minishlink/web-push-php-example/',
        'publicKey' => 'BCmti7ScwxxVAlB7WAyxoOXtV7J8vVCXwEDIFXjKvD-ma-yJx_eHJLdADyyzzTKRGb395bSAtxlh4wuDycO3Ih4',
        'privateKey' => 'HJweeF64L35gw5YLECa-K7hwp3LLfcKtpdRNK8C_fPQ', // in the real world, this would be in a secret file
    ),
);

$webPush = new WebPush($auth);
$res = $webPush->sendNotification(
    $subscription['endpoint'],
    "Hello!", // payload
    $subscription['key'],
    $subscription['token'],
    true // flush
);
// handle eventual errors here, and remove the subscription from your server if it is expired

Hope this helps :)