Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Push Notification: How to use Web Push PHP Library?

I Want to add Web Notification to my website. I searched on Google and found some tutorials about it. As described in these tutorials I manage to show subscription box to the visitors and I can store their data also.

Main.js

'use strict';

const applicationServerPublicKey = 'BBw_opB12mBhg66Dc94m7pOlTTHb5oqFAafbhN-BNeazWk8woAcSeHdgbmQaroCYssUkqFfoHqEJyCKw';

const pushButton = document.querySelector('.js-push-btn');

let isSubscribed = false;
let swRegistration = null;

function urlB64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
    .replace(/_/g, '/');

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}



if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Service Worker and Push is supported');

  navigator.serviceWorker.register('sw.js')
  .then(function(swReg) {
    console.log('Service Worker is registered', swReg);

    swRegistration = swReg;
  })
  .catch(function(error) {
    console.error('Service Worker Error', error);
  });
} else {
  console.warn('Push messaging is not supported');
  pushButton.textContent = 'Push Not Supported';
}


function initialiseUI() {
  // Set the initial subscription value
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    isSubscribed = !(subscription === null);

    if (isSubscribed) {
      console.log('User IS subscribed.');
    } else {
      console.log('User is NOT subscribed.');
    }

    updateBtn();
  });
}

function updateBtn() {
  if (isSubscribed) {
    pushButton.textContent = 'Disable Push Messaging';
  } else {
    pushButton.textContent = 'Enable Push Messaging';
  }

  pushButton.disabled = false;
}

sw.js

'use strict';

self.addEventListener('push', function(event) {
  console.log('[Service Worker] Push Received.');
  console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

  const title = 'Motoroids Lab';
  const options = { 
    body: 'Motoroids',
    icon: 'images/icon.png',
    badge: 'images/badge.png'
  };

  event.waitUntil(self.registration.showNotification(title, options));
});


self.addEventListener('notificationclick', function(event) {
  console.log('[Service Worker] Notification click Received.');

  event.notification.close();

  event.waitUntil(
    clients.openWindow('https://developers.google.com/web/')
  );
});

But now I'm stuck. No matter how much I am trying, It's hard to understand how to send push messages from my server :(

I enabled SSL on my server. I installed PHP Web Push library and its dependencies on the server using composer require minishlink/web-push command.

But what's next? I can't understand their documentation also. https://github.com/web-push-libs/web-push-php

I need some help here. Please help me to understand how it works and how to it.

Thank You

like image 344
Rocky Sena Avatar asked Jun 10 '17 15:06

Rocky Sena


People also ask

How to send web push notifications using PHP?

The web-push library makes it easy to send Web Push notifications using PHP. You get an abstraction layer atop the various browser platforms that supports batching, error handling, and all Web Push features. The Web Push mechanism is an unusual browser system as it’s reliant on remote server-side components you supply yourself.

What is webpush library in PHP?

Web Push library for PHP. WebPush can be used to send notifications to endpoints which server delivers Web Push notifications as described in the Web Push protocol. As it is standardized, you don't have to worry about what server type it relies on.

What client does webpush use to send notifications?

WebPush uses Guzzle. It will use the most appropriate client it finds, and most of the time it will be MultiCurl, which allows to send multiple notifications in parallel. You can customize the default request options and timeout when instantiating WebPush: Is there any plugin/bundle/extension for my favorite PHP framework?

How do I configure default option values for web push notifications?

You can configure default option values using the second argument to the WebPush constructor: The web-push library makes it easy to send Web Push notifications using PHP. You get an abstraction layer atop the various browser platforms that supports batching, error handling, and all Web Push features.


1 Answers

Take a look at https://web-push-book.gauntface.com/ for a general introduction to Web Push. The Chapter How Push Works and Subscribing a User should be particularly interesting to you. In summary:

  • At the client side you need to create a subscription by calling pushManager.subscribe. More info here.
  • You should send this subscription to your server. For example, make an AJAX request to send the subscription (endpoint, keys.p256dh, keys.auth) to the server. More info here.
  • On the server you send a push message using the PHP Web Push library. First, you need to configure this library with your keypair. Then, you need to use the subscription (endpoint, keys.p256dh, keys.auth) to send a push message. More info here.
like image 137
Martijn Avatar answered Oct 19 '22 10:10

Martijn