Giter VIP home page Giter VIP logo

web-push-php-example's Introduction

Web Push example in PHP

Navigating through the commits and files will help you build:

  • on the client
    • a user friendly opt-in push notification button
  • on the server
    • an endpoint for managing your push notification subscriptions
    • an endpoint that triggers push notification thanks to web-push-php

Requirements

  • Chrome or Firefox
  • composer
  • PHP 8.0+
    • gmp
    • mbstring
    • curl
    • openssl

PHP 7.2 is no longer maintained, but you can checkout the v3.x tags. PHP 7.1 is no longer maintained, but you can checkout the v2.x tags. PHP 5.6+ is no longer maintained, but you can checkout the v1.x tags.

Installation

$ composer create-project minishlink/web-push-php-example
$ cd web-push-php-example

You can change the VAPID keys in the keys folder with this guide. Don't forget to update the public key in app.js too.

Usage

$ php -S localhost:8000 router.php

And open localhost:8000.

web-push-php-example's People

Contributors

codeistalk avatar minishlink avatar tbl0605 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web-push-php-example's Issues

I can work on local perfect . But on real SSL site How can i get PublicKey using openssl

How can i create '~88 chars', // (recommended) uncompressed public key P-256 encoded in Base64-URL

Centos 7.5 (Linux version 4.1.12-124.18.6.el7uek.x86_64 ) php 7.2.12 Apache 2.4

app.js

const applicationServerKey = "BCmti7Sc________????________EDIFXjKvD-ma-";

send_push_notification.php

'VAPID' => array(
'subject' => 'https://www.REALSERVER.com/',
'publicKey' => 'BCmti7Sc____????___4wuDycO3Ih4',
'privateKey' => 'HJweeF64L35gw
????_______RNK8C_fPQ', // in the real world, this would be in a secret file

OPENSSL
I have create for Apache 2.4 using openssl like

REALSERVER.key
REALSERVER.crs
REALSERVER.crt

openssl genrsa -des3 -out REALSERVER.key 2048
Password:xxxx

openssl req -new -key REALSERVER.key -out REALSERVER.csr -subj "/C=TR/ST=Istanbul/L=Istanbul/O=realserver/CN=realserver.com"

openssl rsa -in /var/www/ssl/REALSERVER.key -out /var/www/ssl/REALSERVER_nopassword.key

comes from SSL provider
REALSERVER.crt

Uncaught exception 'RuntimeException' with message 'Curve curve ... does not contain point ...'

Hi. Please help.
Not working example

USER_ERROR Uncaught exception 'RuntimeException' with message 'Curve curve(-3, 41058363725152142129326129780047268409114441015993725554835256314039467401291, 115792089210356248762697446949407573530086143415290314195533631308867097853951) does not contain point (115792089210356248762697446949407573530086143415290314195533631308867097853949, 115792089210356248762697446949407573530086143415290314195533631308867097853950)' in /vendor/mdanter/ecc/src/Primitives/Point.php:100
Stack trace:
#0 /vendor/mdanter/ecc/src/Primitives/CurveFp.php(85): Mdanter\Ecc\Primitives\Point->__construct(Object(Mdanter\Ecc\Math\GmpMath), Object(Mdanter\Ecc\Curves\NamedCurveFp), Resource id #1161, Resource id #1167, true)
#1 /vendor/mdanter/ecc/src/Primitives/Point.php(375): Mdanter\Ecc\Primitives\CurveFp->getPoint(Resource id #1161, Resource id #1167, true)
#2 /vendor/mdanter/ecc/src/Primitives/Point.php(282): Mdanter\Ecc\Primitives\Point->getDouble()
#3 /vendor/mdant
On line 100 in file /vendor/mdanter/ecc/src/Primitives/Point.php

Not Working when Browser is closed!!!

Hello,
This is the best push notification script I ever Found. But I got a problem with this. The problem is - The notification is not sending when the browser is closed.

Waiting to hear back in a short time.

Thanks

Adding link to payload

Right now I am using this very example for a small project of mine and have a small issue.
I added a clickListener on the notification, so that the user follows a certain link upon clicking the notification. Looks like this and works fine:

from my serviceWorker.js

self.addEventListener('notificationclick', function(event) {  
  event.notification.close();

  // This looks to see if the current is already open and  
  // focuses if it is  
  event.waitUntil(
    clients.matchAll({  
      type: "window"  
    })
    .then(function(clientList) { 
	  console.log(clientList); 
      for (var i = 0; i < clientList.length; i++) {  
        var client = clientList[i];  
        if (client.url == '/' && 'focus' in client)  
          return client.focus();  
      }  
      if (clients.openWindow) {
	     console.log(clients.openWindow);
        return clients.openWindow(LINK);  
      }
    })
  );
}

My problem is that the link is a variable in serviceWorker.js but I'd like it to be sent from the backend, therefore I'd like to attach the data (link) in the file send_push_notification.php at this part:

$res = $webPush->sendNotification( $subscription, "Hello!", true );

and then read it somewhere here in the serviceWorker.js

self.addEventListener('push', function (event) {
	eventData = event.data;
    if (!(self.Notification && self.Notification.permission === 'granted')) {
        return;
    }

    const sendNotification = body => {
        // you could refresh a notification badge here with postMessage API
        const title = "Web Push example";

        return self.registration.showNotification(title, {
            body,
        });
    };

    if (event.data) {
        const message = event.data.text();
        event.waitUntil(sendNotification(message));
    }
});

Could you please explain me how exactly this would be done? I am somewhat confused since I am not fit in php (need it though), tried some stuff, nothing really seemed to do the trick.

Thank you!

Problem with Chrome Version 64.0.3282.140 (Official Build) (64-bit)

First..thank you for taking the time to make this available.
I have installed the project per your instructions and am having a few problems
After navigating to the home directory web-push-php-example and excuting php -S localhost 8000 router.php I am getting the following messages on the console

[Thu Feb 8 10:58:51 2018] PHP Warning: readfile(\C:\ProjectFiles\webpushphp\web-push-php-example\src\app.js): failed to open stream: No such file or directory in C:\ProjectFiles\webpushphp\web-push-php-example\router.php on line 31

If I prefix the reference to app.js to src/app.js in the index file, then Chrome complains about line 1 of app.js with
Uncaught SyntaxError: Unexpected token <

Additional information : I was able to get the index page to successfully load by changing the directory one level down to src and then : php -S localhost 8000
I was then able to navigate to localhost:8000/index.html and it loaded successfully.
It allowed me to subscribe. But when I tried to send a push notification the following php errors were thrown. (I'm using PHP 7.2) -

[Thu Feb  8 11:28:46 2018] ::1:60660 [200]: /push_subscription.php
[Thu Feb  8 11:28:51 2018] PHP Fatal error:  Cannot use FG\ASN1\Object as Object because 'Object' is a special class name in C:\ProjectFiles\webpushphp\web-push-php-example\vendor\mdanter\ecc\src\Serializer\PrivateKey\DerPrivateKeySerializer.php on line 5
[Thu Feb  8 11:28:51 2018] ::1:60666 [200]: /send_push_notification.php - Cannot use FG\ASN1\Object as Object because 'Object' is a special class name in C:\ProjectFiles\webpushphp\web-push-php-example\vendor\mdanter\ecc\src\Serializer\PrivateKey\DerPrivateKeySerializer.php on line 5

I guess I'm back to asking for any help you might give please ?
TIA - Jim

GMP Extension

I get the following error:
[WebPush] gmp extension is not loaded but is required for sending push notifications with payload or for VAPID authentication. You can fix this in your php.ini.

I uncommented it from both the development and production php.ini file and still get that error.

Works with your router.php and localhost, doesn't with my own local server

Hi, thanks for this great example!

When running from your router.php and localhost:8000, the example works just fine. But when I try to run it inside my own (local) server environment, it doesn't work and I get this error when fetching send_push_notification.php:

<b>Fatal error</b>:  Call to undefined function Mdanter\Ecc\Curves\gmp_init() in <b>[...my_apache_path...]/web-push-php-example/vendor/mdanter/ecc/src/Curves/NistCurve.php</b> on line <b>133</b><br />

I'm not chaning any of the folder structure, just accessing it differently. Any idea what could be causing this? Also, do you know if this should work with self-signed SSL certificates?

image and link in message and title is not working

i tried to add link and images to my notification but its not working. i have seen one thread and changed to json format but then also its showing raw html.

i tried several things to change the title but its not working and tried to add image like this its not working either.

it will be great if u add image, link and title option is example. here is my code

self.addEventListener('push', function (event) {
if (!(self.Notification && self.Notification.permission === 'granted')) {
return;
}

const sendNotification = body => {
    // you could refresh a notification badge here with postMessage API
  const title = "test Request";
    const options = {
     icon: "/icon.png"
          };
    return self.registration.showNotification(title, options, {
        body,
    });
};

if (event.data) {

  const message = event.data.json();
    event.waitUntil(sendNotification(message));
}

});

in php i send like this

$webPush = new WebPush($auth);

$res = $webPush->sendNotification(
$subscription2,
"You have a new message!\n$chatlink ",
true
);

How do you set Options ?

I've seen some options can be set like 'icon, badge, vibrate etc', but i cant find any way of adding them to the sender. It uses part the serviceworker and part the php...where do you set them ?

security issues of having :8000 open

I'm concerned about letting this port through our firewall.

Can we change the port number or what security issues should we be concerned about?

require __DIR__ . '/../vendor/autoload.php';

the first line in send_push_notification.php have this line
require DIR . '/../vendor/autoload.php';
where is that file, the send push notification button is not doing any thing

No notification receive

I get in response "Message sent successfully for subscription" but I don't get any message!
I create my own VAPID but still, nothing changed.
What's going wrong in this?

can't change the message title

thanks, Louis for your great effort I did some tweak to split the client area and save the subscription in the database, but still couldn't find out how the change the notification title dynamically
her is my code in the (send_push_notification.php)
`foreach ($notifications as $notification) {

$webPush->sendNotification(
    $notification['subscription'],
    $notification['payload'],
    false,
    array('topic'=>'my topic')
);

}
$webPush->flush();
and this is how i try to get the title in (serviceWorker.js)return self.registration.showNotification(event.data.topic, {
body: body,
icon: 'https://vignette.wikia.nocookie.net/plantsvszombies/images/9/9c/Pvz2_icon.png/revision/latest?cb=20140621162342',
vibrate: [200, 100, 200, 100, 200, 100, 200],
tag: 'vibration-sample'
});`

PHP 5.5.9 Ubuntu 14.04 vs PHP 7.0.15 Ubuntu 16.04

Hi Minishlink.

I have a strange situation trying to send notifications.
Same code over two differents servers.

In PHP 7.0.15 Ubuntu 16.04 works great.
However, in PHP 5.5.9 Ubuntu 14.04 I get HTTP/1.1 401 Unauthorized from Mozilla and Chrome.

Any idea?

Getting undefined in URL

I am getting "undefined" in url when clicking on notification after a few minutes have passed (can't tell how many). Any suggestions?

Push notifications are not compatible with this browser

The browser shows me this message "Push notifications are not compatible with this browser". I have a Mac with Mamp Pro and Chrome version 65.0.3325.181 (official Build) (64-bit).

I have configured a VirtualHost http://xxxxx.xx pointing to /Applications/MAMP/htdocs/web-push-php-example/src


When I run php-S localhost: 8000 router. php
And I go to the link localhost: 8000 botton for "Enable notifications" is enabled, however the button "Send a push notification" not working or no appear notification

syntax error, unexpected '?', expecting variable (T_VARIABLE)

im getting this error and im not sure why.

we

Below is the code that i used :

`$sub_endpoint = $endpoint;
$sub_publicKey = 'BDASezNQ-********************';
$sub_authToken = $authToken;
$sub_contentEncoding ='aesgcm';
$notifications = [
[
'subscription' => Subscription::create([
'endpoint' => $sub_endpoint,
'publicKey' => $sub_publicKey,
'authToken' => $sub_authToken,
'contentEncoding' => $sub_contentEncoding,
]),
'payload' => '{msg:"test"}',
],
];

            $auth = array(
                'VAPID' => array(
                    'subject' => 'web.example.com', 
                    'publicKey' => 'BDASezNQ-*********', 
                    'privateKey' => 'CqPxWr_*******' 
                    //'pemFile' => './keys/private_key.pem' // if you have a PEM file and can link to it on your filesystem        
                ),
            );
            $defaultOptions = array(
                'TTL' => 300, // defaults to 4 weeks
                'urgency' => 'normal', // protocol defaults to "normal"
                'topic' => 'push', // not defined by default - collapse_key
            );

            $webPush = new WebPush($auth, $defaultOptions);

            // send multiple notifications with payload

            $webPush->flush();

            // send one notification and flush directly
            $webPush->sendNotification(
                $notifications[0]['subscription'],
                $notifications[0]['payload'], // optional (defaults null)
                true // optional (defaults false)
            );`

NotificationClick Event on Opera not working

Hi,
When I add a simple notificationclick event in your service worker, on Opera, when I click on the notification, the event is not getting triggered.

self.addEventListener('notificationclick', function(event) {
    var notificationURL;
    console.log('notification clicled.');
    event.notification.close();
});

Do we need to do something here?
Opera Desktop v 47.

notification blocked for your security

I run the code on my xampp localhost and I tried to access my localhost website from another computer using the same network, but another computer cannot allow the notification because it's blocked for my security. How can I solve this issue?

Illegal instruction

Hi!

I just tried this example repository, when I try to send a push notification, my server crashes with "Illegal instruction: 4"
Tested on a macOS 10.12.6 with PHP7.3.8

Any ideas ?

Push does not arrive

Hello,
it was very easy installing you demo app

Unfortunately, after clicking "Send notification" nothing is happening in the browser.
I;m using PHP 7.1.12 (cli) on windows with (latest) Chrome Version 69.0.3497.100

I added some logs to sendNotification which might help you to debug.

subscription: Minishlink\WebPush\Subscription Object ( [endpoint:Minishlink\WebPush\Subscription:private] => https://fcm.googleapis.com/fcm/send/cfIDjGLRER0:APA91bFq7aPUHUOPlneOcO0zauX2K4byaEEdd9ge5VBFZ77-y1K5IRJSQFPqOquKk0rZLGUZBd_nlK1p-66i50_kf_hJZe7pydLeHfsDhagDdLTwN1jHJHJ-Rb-l4Y9Razw1MajUqWcX [publicKey:Minishlink\WebPush\Subscription:private] => BL9nvphgzIwCxn3ar2OaMj6IYtJtWoq5x7qnLhHvGvVh3djJxOVOfCuqKpnbtBFEGjFBOLQOGczQbnI0pCF9OWI= [authToken:Minishlink\WebPush\Subscription:private] => QTy6ZYhnXMNsU+HQ0IC8HA== [contentEncoding:Minishlink\WebPush\Subscription:private] => aes128gcm ) payload: Payload Hello� auth: Array ( ) notifications: flush: 1

Best regards,
Stefan

Why push_updateSubscription() after registering service worker?

Hi,
I'm new to the Push API.
I'm wondering why it is necessary to update something at the server side after having registered the service worker (see call of push_updateSubscription() in line 47 of app.js) and what to update?
From my impression the endpoint, token and key seem to be always the same, even after closing and restarting the browser.
Thanks and best regards
R0byn

Mozilla on android | Not working?

Hi,
I tried to execute this on mozilla android browser. Though the subscription is successful, notifications are not getting delivered.

Does firefox on android not support VAPID? Is FCM essential for it?

V. 54.0.1

I am confused. What role does FCM plays with mobile browsers?

Terminal - 4 Problems Listed

When using composer create-project minishlink/web-push-php-example in the terminal I get 4 problems.

They include the following:

Problem 1
- minishlink/web-push is locked to version v6.0.0 and an update of this package was not requested.
- minishlink/web-push v6.0.0 requires ext-gmp * -> it is missing from your system. Install or enable PHP's gmp extension.
Problem 2
- paragonie/random_compat is locked to version v9.99.99 and an update of this package was not requested.
- paragonie/random_compat v9.99.99 requires php ^7 -> your php version (8.0.9) does not satisfy that requirement.
Problem 3
- web-token/jwt-util-ecc is locked to version v2.1.9 and an update of this package was not requested.
- web-token/jwt-util-ecc v2.1.9 requires ext-gmp * -> it is missing from your system. Install or enable PHP's gmp extension.
Problem 4
- paragonie/random_compat v9.99.99 requires php ^7 -> your php version (8.0.9) does not satisfy that requirement.
- symfony/polyfill-php70 v1.18.0 requires paragonie/random_compat ~1.0|~2.0|~9.99 -> satisfiable by paragonie/random_compat[v9.99.99].
- symfony/polyfill-php70 is locked to version v1.18.0 and an update of this package was not requested.

Has anyone else experienced these problems? I am trying to solve them but to no avail. Any help would be greatly appreciated.

Deprecated/Removed extension and functions

Hi, in the library there is a function that will be removed in PHP 7.2.0, how will this affect the work?

I mean
mcrypt_create_iv ()
in ".../random_bytes_mcrypt.php" file...

By the way, this also applies to the entire mcrypt extension

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.