我想用php将推送发送到web(chrome),我使用 https://github.com/Minishlink/web-push 库来完成这项工作,但我不知道如何生成或提供$userPublicKey
和$userAuthToken
。
像这样的代码:
use MinishlinkWebPushWebPush;
$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,如下所示:
首次注册服务工作者:
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;
});
}