How to make web push notification by Row_Inserted? (v2023)

$notifications = [
    [
        'subscription' => Subscription::create([
            'endpoint' => 'https://wns2-pn1p.notify.windows.com/w/?token=BQYAAAD4J0rXZ1h2v%2fN%2fiysCBQ%2bHlszi17diHqsbIWYk1dKl%2biJydrgHpqgZhbOB%2bDCM%2btpyibIdeJLWu7%2b%2fBNuooYBdjqxs7zqF9jUIm9z5vgVpEhMY8XqFJk%2bhvH%2bm%2bttWD42waPoC%2bfhlEWds%2fH74xjXE3%2fOo1UrcfgZkOQwYngj%2f2vfgKKpFZFgSlPNk1mvUxWOYHHPghVVDvpn8M%2bu9vUopRMnDoo7Q8yje7B3LkzZDp3CB06NK28VqodVCIFFA6JE9PNoCBIRcrcvs7%2fsBvq2NpJi0tjfkQB%2f0m8x8pFWVQlByCtDWrbJx4%2b0ajDC7DMI%3d',
            'publicKey' => 'BKpo9pAQ6i4VPWumyDi73bS3K+/C7PXY0YX9hbzf0KRoDRLjXOABBS8l7kwI6nUYXOkZ/ZAqRz+jsfFNsZa0xq0=',
            'authToken' => 'BkDvU0IH0+HFwp+UL9btQw==',
            'contentEncoding' => 'aes128gcm', // one of PushManager.supportedContentEncodings
        ]),
        'payload' => '{msg:"test"}',
    ]
];

$webPush = new WebPush();

// send multiple notifications with payload
foreach ($notifications as $notification) {
    $webPush->queueNotification(
        $notification['subscription'],
        $notification['payload'] // optional (defaults null)
    );
}

/**
 * Check sent results
 * @var MessageSentReport $report
 */
foreach ($webPush->flush() as $report) {
    $endpoint = $report->getRequest()->getUri()->__toString();

    if ($report->isSuccess()) {
        echo "[v] Message sent successfully for subscription {$endpoint}.";
    } else {
        echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
    }
}

/**
 * send one notification and flush directly
 * @var MessageSentReport $report
 */
$report = $webPush->sendOneNotification(
    $notifications[0]['subscription'],
    $notifications[0]['payload'] // optional (defaults null)
);

Try to understand the above sample code and use it in your Row_Inserted event. If your code does not work, you may post your code for dicsussion.

this is my code, web push notifications can’t work.

// Row Inserted event
function Row_Inserted($rsold, &$rsnew)
{
    //Log("Row Inserted");
    if ($rsnew["NoTelp"] <> "") {
        
    $notifications = [
    [
        'subscription' => Subscription::create([
            'endpoint' => 'https://wns2-pn1p.notify.windows.com/w/?token=BQYAAAD4J0rXZ1h2v%2fN%2fiysCBQ%2bHlszi17diHqsbIWYk1dKl%2biJydrgHpqgZhbOB%2bDCM%2btpyibIdeJLWu7%2b%2fBNuooYBdjqxs7zqF9jUIm9z5vgVpEhMY8XqFJk%2bhvH%2bm%2bttWD42waPoC%2bfhlEWds%2fH74xjXE3%2fOo1UrcfgZkOQwYngj%2f2vfgKKpFZFgSlPNk1mvUxWOYHHPghVVDvpn8M%2bu9vUopRMnDoo7Q8yje7B3LkzZDp3CB06NK28VqodVCIFFA6JE9PNoCBIRcrcvs7%2fsBvq2NpJi0tjfkQB%2f0m8x8pFWVQlByCtDWrbJx4%2b0ajDC7DMI%3d',
            'publicKey' => 'BKpo9pAQ6i4VPWumyDi73bS3K+/C7PXY0YX9hbzf0KRoDRLjXOABBS8l7kwI6nUYXOkZ/ZAqRz+jsfFNsZa0xq0=',
            'authToken' => 'BkDvU0IH0+HFwp+UL9btQw==',
            'contentEncoding' => 'aes128gcm', // one of PushManager.supportedContentEncodings
        ]),
        'payload' => '{msg:"test"}',
    ]
];

$webPush = new WebPush();

// send multiple notifications with payload
foreach ($notifications as $notification) {
    $webPush->queueNotification(
        $notification['subscription'],
        $notification['payload'] // optional (defaults null)
    );
}

/**
 * Check sent results
 * @var MessageSentReport $report
 */
foreach ($webPush->flush() as $report) {
    $endpoint = $report->getRequest()->getUri()->__toString();

    if ($report->isSuccess()) {
        echo "[v] Message sent successfully for subscription {$endpoint}.";
    } else {
        echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
    }
}

/**
 * send one notification and flush directly
 * @var MessageSentReport $report
 */
$report = $webPush->sendOneNotification(
    $notifications[0]['subscription'],
    $notifications[0]['payload'] // optional (defaults null)
);
    }
}

dennyagung wrote:

$notifications = [
    [
        'subscription' => Subscription::create([
            'endpoint' => 'https://wns2-pn1p.notify.windows.com/w/?token=BQYAAAD4J0rXZ1h2v%2fN%2fiysCBQ%2bHlszi17diHqsbIWYk1dKl%2biJydrgHpqgZhbOB%2bDCM%2btpyibIdeJLWu7%2b%2fBNuooYBdjqxs7zqF9jUIm9z5vgVpEhMY8XqFJk%2bhvH%2bm%2bttWD42waPoC%2bfhlEWds%2fH74xjXE3%2fOo1UrcfgZkOQwYngj%2f2vfgKKpFZFgSlPNk1mvUxWOYHHPghVVDvpn8M%2bu9vUopRMnDoo7Q8yje7B3LkzZDp3CB06NK28VqodVCIFFA6JE9PNoCBIRcrcvs7%2fsBvq2NpJi0tjfkQB%2f0m8x8pFWVQlByCtDWrbJx4%2b0ajDC7DMI%3d',
            'publicKey' => 'BKpo9pAQ6i4VPWumyDi73bS3K+/C7PXY0YX9hbzf0KRoDRLjXOABBS8l7kwI6nUYXOkZ/ZAqRz+jsfFNsZa0xq0=',
            'authToken' => 'BkDvU0IH0+HFwp+UL9btQw==',
            'contentEncoding' => 'aes128gcm', // one of PushManager.supportedContentEncodings
        ]),
        'payload' => '{msg:"test"}',
    ]

You cannot just copy and paste and hard-code the subscriptions, you need to get the actual subscriptions from your Subscriptions table.

Error Class ‘PHPMaker2023.…\Subscription’ not found

if ($rsnew["NoTelp"] <> "") {
$row = ExecuteRow("SELECT Endpoint, PublicKey, AuthenticationToken, ContentEncoding FROM subscriptions WHERE User = 'Denny'");
    $notifications = [
    [
        'subscription' => Subscription::create([
            'endpoint' => $row["Endpoint"],
            'publicKey' => $row["PublicKey"],
            'authToken' => $row["AuthenticationToken"],
            'contentEncoding' => $row["ContentEncoding"], // one of PushManager.supportedContentEncodings
        ]),
        'payload' => 'hello !',
    ]

Read Using namespaces: Basics.

<?php

namespace PHPMaker2023\sz4;

use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;

require_once "../vendor/autoload.php";
require_once "../src/constants.php";
require_once "../src/config.php";
require_once "../src/phpfn.php";
require_once "../src/userfn.php";
// Page object
$SendPushNotification = &$Page;

$auth = [
    "VAPID" => [
        "subject" => ConvertToUtf8('Test'),
        "publicKey" => Config("PUSH_SERVER_PUBLIC_KEY"),
        "privateKey" => Config("PUSH_SERVER_PRIVATE_KEY"),
    ],
];

$webPush = new WebPush($auth);

$row = ExecuteRow("SELECT Endpoint, PublicKey, AuthenticationToken, ContentEncoding FROM subscriptions WHERE User = 'Denny'");

$notification = [
    'subscription' => Subscription::create([
        'endpoint' => $row["Endpoint"],
        'publicKey' => $row["PublicKey"],
        'authToken' => $row["AuthenticationToken"],
        'contentEncoding' => $row["ContentEncoding"],
    ]),
    'payload' => 'hello !',
];

foreach ($notifications as $notification) {
    $webPush->queueNotification(
        $notification['subscription'],
        $notification['payload'] // optional (defaults null)
    );
}

foreach ($webPush->flush() as $report) {
    $endpoint = 'https://wns2-pn1p.notify.windows.com/w/?token=BQYAAAD4J0rXZ1h2v%2fN%2fiysCBQ%2bHlszi17diHqsbIWYk1dKl%2biJydrgHpqgZhbOB%2bDCM%2btpyibIdeJLWu7%2b%2fBNuooYBdjqxs7zqF9jUIm9z5vgVpEhMY8XqFJk%2bhvH%2bm%2bttWD42waPoC%2bfhlEWds%2fH74xjXE3%2fOo1UrcfgZkOQwYngj%2f2vfgKKpFZFgSlPNk1mvUxWOYHHPghVVDvpn8M%2bu9vUopRMnDoo7Q8yje7B3LkzZDp3CB06NK28VqodVCIFFA6JE9PNoCBIRcrcvs7%2fsBvq2NpJi0tjfkQB%2f0m8x8pFWVQlByCtDWrbJx4%2b0ajDC7DMI%3d';

    if ($report->isSuccess()) {
        echo "[v] Message sent successfully for subscription {$endpoint}.";
    } else {
        echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
    }
}
//start subscription

	//end subscription
	//sending push message
		
	// end sending push message

I don’t get error. But the notification not working. Any idea ? Notification only working if i using at menu subscription

dennyagung wrote:

$notification = [
‘subscription’ => Subscription::create([
‘endpoint’ => $row[“Endpoint”],
‘publicKey’ => $row[“PublicKey”],
‘authToken’ => $row[“AuthenticationToken”],
‘contentEncoding’ => $row[“ContentEncoding”],
]),
‘payload’ => ‘hello !’,
];
foreach ($notifications as $notification) {
$webPush->queueNotification(
$notification[‘subscription’],
$notification[‘payload’] // optional (defaults null)
);
}

>

Your code did not send the notification at all.

Is the code below not used to send web push notifications?

foreach ($notifications as $notification) {
    $webPush->queueNotification(
        $notification['subscription'],
        $notification['payload'] // optional (defaults null)
    );
}

Re-read the sample code you pasted in your first post.

<?php

namespace PHPMaker2023\sz4;

use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;

require_once "../vendor/autoload.php";
require_once "../src/constants.php";
require_once "../src/config.php";
require_once "../src/phpfn.php";
require_once "../src/userfn.php";
// Page object
$SendPushNotification = &$Page;

$row = ExecuteRow("SELECT Endpoint, PublicKey, AuthenticationToken, ContentEncoding FROM subscriptions WHERE User = 'Denny'");

$notifications = [
    [
        'subscription' => Subscription::create([
            'endpoint' => $row["Endpoint"], // Firefox 43+,
            'publicKey' => $row["PublicKey"], // base 64 encoded, should be 88 chars
            'authToken' => $row["AuthenticationToken"], // base 64 encoded, should be 24 chars
            'contentEncoding' => $row["ContentEncoding"], // one of PushManager.supportedContentEncodings
        ]),
        'payload' => '{msg:"test"}',
    ]
];

$auth = [
    "VAPID" => [
        "subject" => '',
        "publicKey" => Config("PUSH_SERVER_PUBLIC_KEY"),
        "privateKey" => Config("PUSH_SERVER_PRIVATE_KEY"),
    ],
];
$webPush = new WebPush($auth);

// send multiple notifications with payload
foreach ($notifications as $notification) {
    $webPush->queueNotification(
        $notification['subscription'],
        $notification['payload'] // optional (defaults null)
    );
}

/**
 * Check sent results
 * @var MessageSentReport $report
 */
foreach ($webPush->flush() as $report) {
    $endpoint = $report->getRequest()->getUri()->__toString();

    if ($report->isSuccess()) {
        echo "[v] Message sent successfully for subscription {$endpoint}.";
    } else {
        echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
    }
}

/**
 * send one notification and flush directly
 * @var MessageSentReport $report
 */
$report = $webPush->sendOneNotification(
    $notifications[0]['subscription'],
    $notifications[0]['payload'] // optional (defaults null)
);

[v] Message sent successfully for subscription https://wns2-pn1p.notify.windows.com/w/?token=BQYAAABgS1xDFXBpLxofgluFXaah4EnvTokcMWm4DGTxVA7vXlNJOn1fvYjMCy8RwwsvGooYQFEamumU4Ay5gl7XoREjrdULZi6a3TqRNA9BZQS0tOaXPiDRpI2%2BMRebOReWzevmyqGnKW2MOgpu7wQAjS8gU0PvSP1zjCCZxgEKA5YOobLQgtggav7YJLq%2FrvpUv4c0seY1WcSp1aUAY4pgF%2BJRGrNTOnElo7hVyH0zHpOPdiPk6Uc1yYYekELMkdNpYy7SxSk1pO43kUokseOccqEqxRjzGHMlKlw4si5LCtyF%2Bp3uzZ0%2BeTzX%2FihSSdK8g%2Fw%3D.The message update code was successfully sent but there was no notification on the website

The message update code was successfully sent but there was no notification on the website

dennyagung wrote:

“subject” => ‘’,

Try add the subject in case it is required.dennyagung wrote:

$report = $webPush->sendOneNotification(

Do not send again. You have already sent by $webPush->flush().dennyagung wrote:

``[v] Message sent successfully for subscription: > https://wns2-pn1p.notify.windows.com> …

The endpoint is Edge browser, make sure you open the correct browser.

<?php

namespace PHPMaker2023\sz4;

use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;

require_once "../vendor/autoload.php";
require_once "../src/constants.php";
require_once "../src/config.php";
require_once "../src/phpfn.php";
require_once "../src/userfn.php";
// Page object
$SendPushNotification = &$Page;

$row = ExecuteRow("SELECT Endpoint, PublicKey, AuthenticationToken, ContentEncoding FROM subscriptions WHERE User = 'Denny'");

$notifications = [
    [
        'subscription' => Subscription::create([
            'endpoint' => $row["Endpoint"], // Firefox 43+,
            'publicKey' => $row["PublicKey"], // base 64 encoded, should be 88 chars
            'authToken' => $row["AuthenticationToken"], // base 64 encoded, should be 24 chars
            'contentEncoding' => $row["ContentEncoding"], // one of PushManager.supportedContentEncodings
        ]),
        'payload' => '{msg:"test"}',
    ]
];

$auth = [
    "VAPID" => [
        "subject" => ConvertToUtf8("test"),
        "publicKey" => Config("PUSH_SERVER_PUBLIC_KEY"),
        "privateKey" => Config("PUSH_SERVER_PRIVATE_KEY"),
    ],
];
$webPush = new WebPush($auth);

// send multiple notifications with payload
foreach ($notifications as $notification) {
    $webPush->queueNotification(
        $notification['subscription'],
        $notification['payload'] // optional (defaults null)
    );
}

/**
 * Check sent results
 * @var MessageSentReport $report
 */
foreach ($webPush->flush() as $report) {
    $endpoint = $report->getRequest()->getUri()->__toString();

    if ($report->isSuccess()) {
        echo "[v] Message sent successfully for subscription {$endpoint}.";
    } else {
        echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
    }
}

I follow your solution but it can’t work

dennyagung wrote:

‘payload’ => ‘{msg:“test”}’,

You have wrong payload, the properties should be those of a Notification object, e.g.‘payload’ => json_encode([“title” => “test title”, “body” => “test body”]).