向 chrome 发送推送并在 php 中加密负载数据

send push to chrome and encryption payload data in php

我想用 php 发送推送到 web(chrome) 并且我使用 https://github.com/Minishlink/web-push 库来完成这项工作,但我不知道如何生成或提供 $userPublicKey$userAuthToken.

这样的代码:

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

像这样在客户端提供 $userPublicKey 和 $userAuthToken :

首先注册 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);
  });
}

为订阅按钮添加事件侦听器:

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

并在 pushSubscription.getKey() 中获取 $userPublicKey 和 $userAuthToken,如下所示:

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;
  });
}