Skip to content

Core\WebPush::send

Sends one notification to one browser. send encrypts the payload for that browser and signs the request with your VAPID key, a Core\Crypto\KeyPair of kind P256. Then it posts the message to the push service of the browser.

The program needs the net.connect capability for the host of the endpoint. An endpoint on a private or link-local address throws a RuntimeError. In a web request, a loopback address such as 127.0.0.1 also throws. A payload over 3993 bytes throws a RuntimeError too. A wrong key kind, a $subject that is not a mailto: or https: URL, or a negative $ttl throws a LogicError. Each of these errors happens before send connects.

status() of the result is 201 when the push service accepted the message. isGone() returns true for the status 404 or 410. The push service has then deleted the subscription, so delete it from your database too.

The examples show a wrong subject, a payload that is too long, and a function that deletes the subscriptions that are gone.

Parameters

  • $toCore\WebPush\SubscriptionThe subscription that Core\WebPush::subscription returned.
  • $payloadbytesThe message, at most 3993 bytes. The browser's service worker receives it in its push event.
  • $vapidCore\Crypto\KeyPairYour application's VAPID key: a Core\Crypto\KeyPair of kind P256. Create it once with Core\Crypto::generateKeyPair, keep it secret, and use the same key for every message.
  • $subjectstringA way for the push service to contact you: a mailto: or an https: URL, such as mailto:admin@example.com.
  • $ttlintdefault 86400How many seconds the push service keeps the message while the browser is offline. 0 means the message is sent only if the browser is online now.

Return value

Returns Core\WebPush\Sent. The push service's answer. Its status() is 201 when the service accepted the message.

Errors

  • LogicError$vapid is not a key pair of kind P256.
  • LogicError$subject does not start with mailto: or https:, or $ttl is negative.
  • RuntimeErrorThe payload is longer than 3993 bytes, the program may not connect to the host, or the push service cannot be reached.

Examples

A subject that is not a url

<?nvs
// Shows the error you get when the subject is not a `mailto:` or `https:` URL.
// This is the JSON that the browser sent when the user allowed notifications.
string $json = '{"endpoint":"https://push.example.com/send/abc","keys":{'
. '"p256dh":"BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4",'
. '"auth":"BTBZMqHH6r4Tts7J_aSIgg"}}';
Core\WebPush\Subscription $to = Core\WebPush::subscription($json);
bytes $payload = Core\Encoding::encodeText('Your order has shipped.', Core\Charset::Utf8);
// A real program loads its VAPID key from a file. This example makes a new one.
Core\Crypto\KeyPair $vapid = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::P256);
// `admin@example.com` has no `mailto:` in front of it. The call throws a `LogicError`
// before it connects to the push service.
try {
Core\WebPush::send($to, $payload, $vapid, 'admin@example.com');
} catch (LogicError $error) {
echo $error->message, "\n";
}
Output
Core\WebPush::send(): $subject is not a `mailto:` or an `https:` URL.

A message that is too long

<?nvs
// Shows what happens when a message is longer than 3993 bytes.
string $json = '{"endpoint":"https://push.example.com/send/abc","keys":{'
. '"p256dh":"BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4",'
. '"auth":"BTBZMqHH6r4Tts7J_aSIgg"}}';
Core\WebPush\Subscription $to = Core\WebPush::subscription($json);
Core\Crypto\KeyPair $vapid = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::P256);
// This payload is 4000 bytes. The call throws a `RuntimeError` before it connects.
bytes $payload = Core\Encoding::encodeText(Core\Str::repeat('a', 4000), Core\Charset::Utf8);
try {
Core\WebPush::send($to, $payload, $vapid, 'mailto:admin@example.com');
} catch (RuntimeError $error) {
echo $error->message, "\n";
}
// Send a short text, such as a title and an ID. The service worker can load the rest.
echo Core\Bytes::length(Core\Encoding::encodeText('{"title":"New order","id":4711}', Core\Charset::Utf8)), " bytes\n";
Output
Core\WebPush::send(): the payload is 4000 bytes, and one message holds at most 3993.
31 bytes

Delete gone subscriptions

<?nvs
// Shows a function that sends a message to every browser of a user, and deletes each
// subscription that the push service no longer knows.
class Notifier
{
// Sends the message to each subscription and returns the ones to keep. A failed
// send keeps its subscription. Only a send whose `isGone()` is `true` deletes it.
public static function notify(array<string> $stored, string $text, Core\Crypto\KeyPair $vapid): array<string>
{
bytes $payload = Core\Encoding::encodeText($text, Core\Charset::Utf8);
array<string> $keep = [];
foreach ($stored as string $json) {
Core\WebPush\Subscription $to = Core\WebPush::subscription($json);
try {
Core\WebPush\Sent $sent = Core\WebPush::send($to, $payload, $vapid, 'mailto:admin@example.com');
if (!$sent->isGone()) {
$keep[] = $json;
}
} catch (RuntimeError $error) {
echo 'not sent: ', Core\Str::before($error->message, "\n"), "\n";
$keep[] = $json;
}
}
return $keep;
}
// Returns the JSON of one subscription with the given endpoint.
public static function subscription(string $endpoint): string
{
return '{"endpoint":"' . $endpoint . '","keys":{'
. '"p256dh":"BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4",'
. '"auth":"BTBZMqHH6r4Tts7J_aSIgg"}}';
}
}
Core\Crypto\KeyPair $vapid = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::P256);
// A real endpoint is a URL of the browser's push service. These two are private addresses,
// so each send throws a `RuntimeError` and connects to nothing. Both subscriptions are kept.
array<string> $stored = [Notifier::subscription('https://10.0.0.12/send/phone'), Notifier::subscription('https://10.0.0.13/send/laptop')];
array<string> $kept = Notifier::notify($stored, 'Your order has shipped.', $vapid);
echo Core\Arr::count($kept), " subscriptions kept\n";
Output
not sent: Core\WebPush::send cannot connect to 10.0.0.12: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not except
not sent: Core\WebPush::send cannot connect to 10.0.0.13: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not except
2 subscriptions kept