Function to send Web Push Notificatioin to single user. Copy the following code to the
Server Events → Global → All Pages → Global Code
function SendWebPushNotification($user, $title = "Notification", $body = "You have a new message") {
if (!$user) return false;
// Get config values from PHPMaker
$tableName = Config("SUBSCRIPTION_TABLE");
$fieldUser = Config("SUBSCRIPTION_FIELD_NAME_USER");
$fieldEndpoint = Config("SUBSCRIPTION_FIELD_NAME_ENDPOINT");
$fieldPublicKey = Config("SUBSCRIPTION_FIELD_NAME_PUBLIC_KEY");
$fieldAuthToken = Config("SUBSCRIPTION_FIELD_NAME_AUTH_TOKEN");
$fieldEncoding = Config("SUBSCRIPTION_FIELD_NAME_CONTENT_ENCODING");
$vapidPublicKey = Config("PUSH_SERVER_PUBLIC_KEY");
$vapidPrivateKey = Config("PUSH_SERVER_PRIVATE_KEY");
// Validate VAPID keys
if (!$vapidPublicKey || !$vapidPrivateKey) return false;
// Fetch all subscriptions for the user
$subscribers = ExecuteRows("SELECT * FROM `{$tableName}` WHERE `{$fieldUser}` = '" . AdjustSql($user) . "'");
if (!$subscribers) return false;
// VAPID auth config
$auth = [
'VAPID' => [
'subject' => 'mailto:admin@yourdomain.com',
'publicKey' => $vapidPublicKey,
'privateKey' => $vapidPrivateKey
]
];
$webPush = new \Minishlink\WebPush\WebPush($auth);
$payload = json_encode(["title" => $title, "body" => $body]);
$success = false;
foreach ($subscribers as $row) {
$subscription = \Minishlink\WebPush\Subscription::create([
'endpoint' => $row[$fieldEndpoint],
'publicKey' => $row[$fieldPublicKey],
'authToken' => $row[$fieldAuthToken],
'contentEncoding' => $row[$fieldEncoding]
]);
try {
$report = $webPush->sendOneNotification($subscription, $payload);
$success = true;
} catch (\Exception $e) {
// optionally log error: $e->getMessage()
}
}
return $success;
}
How to use - just call the function
$title = "Notification";
$body = "You have a new message"
SendWebPushNotification($user, $title, $body) ;
Note : This does not work for Anonymous Users