I am working on a backend PHP script to send notifications to a subscription. Here is my code:
<?php
$endpoint = "https://wns2-by3p.notify.windows.com/w/?token=BQYAAAAEycZlxsQTTp9zcqC%2fb8SosCVZv8A%2fzlCmVXBhpFZsBydTExEV7punPkvI6Iyq34EvL4DCGnq1q5iltFpbXpNfFIMFmZX5zceXuMKnxD7vfMCICw9T5j6yRyTtueWg%2fCpatXRfRTpVA3KnW2ZEW1HjcOvqY92pKLyj8Q0qNetRkyl1WUVhi46IjRRzFXqtB8zyM4jr%2fp0KUbGhhUIKodZ8QreC%2fGiw8CpVAjIFjn2F5a98zDgTyj6NHajd5OWGSQ2lzo452DmQpHgattx9bSfhfC7SrVuvBvoS7YUQ3y3lR4pfAejU9DIPc5H0iDCim9LDQ3BqfqCUJpW5l25NQNrs";
$keys = [
"p256dh" => "BA7Fcw-tgO1UZrNZPUZjntJtkBYigJNLxcGFFRyHa0my0SszwnUwu0sZaE4W-EZas7yPi9iFNIe4LG5z6PtNfXc",
"auth" => "mRmbv1KsA_Yc_sKR43KnQw"
];
$headers = [
"TTL: 60",
"Content-Encoding: aes128gcm",
"Authorization: vapid t=eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJhdWQiOiJodHRwczovL3duczItYnkzcC5ub3RpZnkud2luZG93cy5jb20iLCJleHAiOjE3Mzc0MzYwMjYsInN1YiI6Im1haWx0bzpzaW1wbGUtcHVzaC1kZW1vQGdhdW50ZmFjZS5jby51ayJ9.rtM4tswfpR4NQtgcTgO5zZBa-Hyw-7EZtQkI1z1o6VWIEcaqly7NR0-uXFJAFS1AQ406wrXlgXlOaayPXDmUnQ, k=BDd3_hVL9fZi9Ybo2UUzA284WG5FZR30_95YeZJsiApwXKpNcF1rRPF3foIiBHXRdJI2Qhumhf6_LFTeZaNndIo"
];
$message = json_encode([
"title" => "Notification Title",
"body" => "This is the body of the notification."
]);
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
throw new Exception('Curl error: ' . curl_error($ch));
}
curl_close($ch);
echo $response;
?>
The article at https://developer.chrome.com/blog/web-push-encryption/ says that messages have to be encrypted, but I’m not sure it applies to my situation.
When I visit this page in my browser, there is nothing on the page, which means it should have worked, even though I never receive a notification. Can someone please help me?
2
Answers
I don’t have a solution, but I would advise you to check possible CURL errors.
Add something like the following to your code (instead of branching on the response like you do now):
Next: If you get a blank page, first place to look is your webservers errorlog.
For Apache2 this is the standard errorlog of Apache, or in case you set up another one in your VHOST, check that one.
Yes, it applies to your situation because you are sending a message with some data (title and body).
You need to implement message encryption:
https://datatracker.ietf.org/doc/html/rfc8291
It’s not an easy task…
I recommend using a PHP library for Web Push that does that for you: