Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active January 24, 2024 07:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/d8662f35a003c979110cbc6316508930 to your computer and use it in GitHub Desktop.
Save code-boxx/d8662f35a003c979110cbc6316508930 to your computer and use it in GitHub Desktop.
PHP Push Notifications

PHP PUSH NOTIFICATIONS

https://code-boxx.com/php-push-notifications/

IMAGES

PUSH-php-A PUSH-php-B

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  1. PHP WEB PUSH LIBRARY
  • Install composer https://getcomposer.org/
  • Open command prompt or terminal, and navigate to your project folder - cd MY/PROJECT/FOLDER
  • Run composer require minishlink/web-push
  • Library will be downloaded into vendor/ folder.
  1. PHP OPEN SSL EXTENSION (LINUX)
  • sudo apt-get install openssl
  • php -i | grep -i openssl
  1. PHP OPEN SSL EXTENSION (WINDOWS)
  • Open php.ini, enable extension=php_openssl.dll
  • Hit "start" > Search for "system environment" > "Edit the system environment variables" > "Environment variables" > Add a new variable under "system"
  • Enter the name OPENSSL_CONF, and point the value to the openssl.cnf file. By default, openssl.cnf is located at C:\xampp\php\extras\openssl\openssl.cnf.
  1. Run 2-vapid-keys.php to generate your own public/private keys.
  2. Change the public key in 3-perm-sw.html to your own.
  3. Change the subject, public, and private keys to your own in 5-push-server.php.
  4. Access 3-perm-sw.html in your browser.

Take note that https:// is required for push notifications to work, http://localhost is an exception for testing.

<?php
require "vendor/autoload.php";
use Minishlink\WebPush\VAPID;
print_r(VAPID::createVapidKeys());
<!DOCTYPE html>
<html>
<head>
<title>Push Notification</title>
</head>
<body>
<script>
// (A) OBTAIN USER PERMISSION TO SHOW NOTIFICATION
window.onload = () => {
// (A1) ASK FOR PERMISSION
if (Notification.permission === "default") {
Notification.requestPermission().then(perm => {
if (Notification.permission === "granted") {
regWorker().catch(err => console.error(err));
} else {
alert("Please allow notifications.");
}
});
}
// (A2) GRANTED
else if (Notification.permission === "granted") {
regWorker().catch(err => console.error(err));
}
// (A3) DENIED
else { alert("Please allow notifications."); }
};
// (B) REGISTER SERVICE WORKER
async function regWorker () {
// (B1) YOUR PUBLIC KEY - CHANGE TO YOUR OWN!
const publicKey = "YOUR-PUBLIC-KEY";
// (B2) REGISTER SERVICE WORKER
navigator.serviceWorker.register("4-sw.js", { scope: "/" });
// (B3) SUBSCRIBE TO PUSH SERVER
navigator.serviceWorker.ready
.then(reg => {
reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicKey
}).then(
// (B3-1) OK - TEST PUSH NOTIFICATION
sub => {
var data = new FormData();
data.append("sub", JSON.stringify(sub));
fetch("5-push-server.php", { method: "POST", body : data })
.then(res => res.text())
.then(txt => console.log(txt))
.catch(err => console.error(err));
},
// (B3-2) ERROR!
err => console.error(err)
);
});
}
</script>
</body>
</html>
// (A) INSTANT WORKER ACTIVATION
self.addEventListener("install", evt => self.skipWaiting());
// (B) CLAIM CONTROL INSTANTLY
self.addEventListener("activate", evt => self.clients.claim());
// (C) LISTEN TO PUSH
self.addEventListener("push", evt => {
const data = evt.data.json();
// console.log("Push", data);
self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon,
image: data.image
});
});
<?php
// (A) LOAD WEB PUSH LIBRARY
require "vendor/autoload.php";
use Minishlink\WebPush\Subscription;
use Minishlink\WebPush\WebPush;
// (B) GET SUBSCRIPTION
$sub = Subscription::create(json_decode($_POST["sub"], true));
// (C) NEW WEB PUSH OBJECT - CHANGE TO YOUR OWN!
$push = new WebPush(["VAPID" => [
"subject" => "your@email.com",
"publicKey" => "YOUR-PUBLIC-KEY",
"privateKey" => "YOUR-PRIVATE-KEY"
]]);
// (D) SEND TEST PUSH NOTIFICATION
$result = $push->sendOneNotification($sub, json_encode([
"title" => "Welcome!",
"body" => "Yes, it works!",
"icon" => "PUSH-php-A.png",
"image" => "PUSH-php-B.png"
]));
$endpoint = $result->getRequest()->getUri()->__toString();
// (E) HANDLE RESULT - OPTIONAL
if ($result->isSuccess()) {
// echo "Successfully sent {$endpoint}.";
} else {
// echo "Send failed {$endpoint}: {$result->getReason()}";
// $result->getRequest();
// $result->getResponse();
// $result->isSubscriptionExpired();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment