Roox Roox - 3 months ago 125
PHP Question

send push to chrome and encryption payload data in php

I want send push to web(chrome) with php and I use https://github.com/Minishlink/web-push lib for this work, but I don't know how to generate or give

$userPublicKey
and
$userAuthToken
.

code like this :

use Minishlink\WebPush\WebPush;

$endpoint = 'https://android.googleapis.com/gcm/send/dwh8heIRnRI:APA91bH1nKZESimKK7Oh9ttQeoRovaS4drmCTQfkpvgtyQQKZZ1htwo4e-tKjMw_cS0ozINkXxXV8-jnYmK2__ZCZbrZUVrJxb931CahVUuat08DRqg4Z7yFpserazwCzCNBEcjb2jfb'; // Chrome
$apiKeys = array(
'GCM' => 'AIzacyDV2NtiuwLZGzDaC9bEeEeisS4BANjHw9s',
);

$webPush = new WebPush($apiKeys);

$webPush->sendNotification(
"https://android.googleapis.com/gcm/send/foV7YNoaKbk:APA91bETu6fPcDHsliBIaI3R0ejFqgIUwfMGFatia1563nTXVZTACaZw3tFaHW-z0Tu7YvZLJebxiYEapyzygO_5WvONVHHNDz7G9KPyPLxl-Il3h6QdgMVJhsmWs0ENVEcFt9HJKX0U",
"hey", // optional (defaults null)
"$userPublicKey",
"$userAuthToken"
true // optional (defaults false)
);

Answer

give $userPublicKey and $userAuthToken in the client side like this :

first register service worker :

if ('serviceWorker' in navigator) {
  console.log('Service Worker is supported');
  navigator.serviceWorker.register('sw.js').then(function() {
    return navigator.serviceWorker.ready;
  }).then(function(serviceWorkerRegistration) {
    reg = serviceWorkerRegistration;
    subscribeButton.disabled = false;
    console.log('Service Worker is ready :^)', reg);
  }).catch(function(error) {
    console.log('Service Worker Error :^(', error);
  });
}

add event listener for subscribe button :

subscribeButton.addEventListener('click', function() {
  if (isSubscribed) {
    unsubscribe();
  } else {
    subscribe();
  }
});

and get $userPublicKey and $userAuthToken in pushSubscription.getKey() like this :

function subscribe() {
  reg.pushManager.subscribe({userVisibleOnly: true}).
  then(function(pushSubscription) {
    sub = pushSubscription;

    console.log(sub.getKey('auth'));
        //userPublicKey
        console.log(toBase64(sub.getKey('p256dh')));
        //userAuthToken
        console.log(toBase64(sub.getKey('auth')));


    console.log('Subscribed! Endpoint:', sub.endpoint);
    subscribeButton.textContent = 'Unsubscribe';
    isSubscribed = true;
  });
}
Comments