Php:创建Web推送通知

时间:2017-07-24 11:09:27

标签: php push-notification web-push

我想在Php中创建一个网络推送通知,但我没有确切的程序。以下是我找到的代码,但它无效。

  <?php
   require __DIR__ . '/../vendor/autoload.php';    
   use Minishlink\WebPush\WebPush;



    $subscription = json_decode(file_get_contents('php://input'), true);

    $auth = array(
   'VAPID' => array(
    'subject' => '`enter code here`',
    'publicKey' => '**********',
    'privateKey' => '***********',
   ),
 );

    $webPush = new WebPush($auth);

    $res = $webPush->sendNotification(
    $subscription['endpoint'],
    "Hello!",
     $subscription['key'],
     $subscription['token'],
     true
   );

请建议正确的步骤。

1 个答案:

答案 0 :(得分:1)

我花了一些时间自己搞清楚这一点。我发布了适用于我的代码。从这里生成密钥https://web-push-codelab.glitch.me/

<?php

require_once './vendor/autoload.php';

use Minishlink\WebPush\WebPush;


// array of notifications
$notifications = array(
 array(
        'endpoint' => 'https://fcm.googleapis.com/fcm/send/abcd........', // Chrome
        'payload' => 'Hello',
        'userPublicKey' => 'BFHh..........',
        'userAuthToken' => 'DI............',
    )
);

$auth = array(
    'GCM' => 'AAAAKTK8bp4..............', // deprecated and optional, it's here only for compatibility reasons
    'VAPID' => array(
        'subject' => 'Some Text', // can be a mailto: or your website address
        'publicKey' => 'BGsm2vrV2AMpT.............', // (recommended) uncompressed public key P-256 encoded in Base64-URL
        'privateKey' => 'a89H............', // (recommended) in fact the secret multiplier of the private key encoded in Base64-URL

    ),
);

$defaultOptions = array(
    'TTL' => 300, // defaults to 4 weeks
    'urgency' => 'normal', // protocol defaults to "normal"
    'topic' => 'push', // not defined by default - collapse_key
);

$webPush = new WebPush($auth, $defaultOptions);

$vr = $webPush->sendNotification(
    $notifications[0]['endpoint'],
    $notifications[0]['payload'], // optional (defaults null)
    $notifications[0]['userPublicKey'], // optional (defaults null)
    $notifications[0]['userAuthToken'], // optional (defaults null)
    true // optional (defaults false)
);