1

我正在使用 Minishlink ( https://github.com/web-push-libs/web-push-php ) 的 web-push-php 库向用户发送推送通知。推送通知成功到达客户端,但有效负载始终为空。

这是我的代码:

serviceWorker.js

self.addEventListener('push', function(event) {
  console.log('[SW] push received');
  console.log(event.data);
  const title = 'Test-Push-Notification';
  const options = {
    body: 'Yay it works.'/*,
    icon: 'images/icon.png',
    badge: 'images/badge.png'*/
  };

  console.log("Notification is about to be shown...");
  event.waitUntil(self.registration.showNotification(title, options));
});

sendPushNotification.php

    $auth = [
            'VAPID' => [
                'subject' => 'https://myurl:myport',
                'publicKey' => '***',
                'privateKey' => '***' // in the real world, this would be in a secret file
            ],
        ];

    while($result = sqlsrv_fetch_object($getEndpoints)){

        $subscription = [
            'subscription' => Subscription::create([
                'endpoint' => $result->endpoint,
                'publicKey' => $result->publicKey,
                'authToken' => $result->authToken
            ], true),
            'payload' => '{"msg":"Hello!"}'

        ];

        $webPush = new WebPush($auth);
        $res = $webPush->sendNotification(
            $subscription['subscription'],
            $subscription['payload'],
            true
        );
}

订阅数据正确存储在 db 中。推送通知与我的占位符文本一起到达。当我查看控制台时,我看到 event.data 为空。即使我输入console.log(event)orconsole.log(event.data.text())console.log(event.data.json()),我也没有得到该 PushMessageData-Object 中数据属性的任何数据。

在这里查看我在chrome 控制台中的输出

我认为,我的密钥是正确的,因为推送通知仅通过有效密钥到达。

还有什么可以查的吗?

4

1 回答 1

0

实际上,您可以尝试一些事情:

A.添加contentEncodingSubscription对象:

$sub = Subscription::create([
    'endpoint' => $result->endpoint,
    'publicKey' => $result->publicKey,
    'authToken' => $result->authToken,
    'contentEncoding' => $result->getEncoding(), // from browser, see example link
]);

B.将 VAPID auth 显式设置为sendNotification

$webPush->sendNotification($sub, \json_encode($payload), !$stack, $options, $auth);

从浏览器获取编码的示例链接:https ://github.com/Minishlink/web-push-php-example/blob/master/src/app.js#L178

希望有帮助。

于 2018-10-15T13:31:47.547 回答