Web push notification example with PHP backend
Asked Answered
D

2

6

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

Desist answered 12/3, 2017 at 10:32 Comment(4)
If you want to use a service, check out the Pushpad PHP library. Start from the Getting started, then you can see some examples about collecting subscriptions, finally you can send notifications from your PHP backend with the PHP library.Impulsive
Thanks, i will try this, if you have any example with GCM and APN please let me know.Desist
Do you mean from scratch? Because under the hood Pushpad uses GCM, APNs and Mozilla autopush.Impulsive
Actually, i am planning to start a service similar to pushpad, thats why i am looking for the same..Desist
I
-1

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 :)

Informant answered 6/5, 2017 at 13:40 Comment(4)
This example does not work out of the box and needs more instructions.Cimino
@Cimino that would way too much for SA answer, that's why it's in a GitHub repo.Fears
@Fears you're misunderstanding me. More instructions does not mean the entire codebase.Cimino
As others said, much more context is needed. I dont consider this full answer.Fulkerson
O
-1
  • You should generate VAPID keys.
  • Than you should create "service-worker.js"
  • After that you should get keys ('endpoint', 'p256dh', 'auth') for specify user
  • And after that you may send push notification for the user using PHP.

Here you can find example "service-worker.js" and PHP script.

Ontine answered 30/3, 2023 at 15:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.