Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Certainly! Here is an example of a web push notification using a PHP backend:

  1. First, ensure that you have set up a web push service provider such as Firebase, OneSignal, or Pusher.

  2. Install the library for your chosen provider using Composer, and then include it in your PHP file:

require_once __DIR__ . '/vendor/autoload.php'; // Autoload packages

use Pusher\PushNotifications\PushNotifications; // Import Push Notifications library
  1. Set up the Push Notifications connection by creating an instance of the Pusher library:
$config = [
  "instanceId" => "<INSTANCE_ID>",
  "secretKey" => "<SECRET_KEY>",
  "dsn" => "<DB_DSN>",
];
$pushNotifications = new PushNotifications($config);
  1. Use the publishToInterests method to send a notification to all subscribers of a certain interest (e.g. "news"):
$response = $pushNotifications->publishToInterests(
  ["news"], // Array of interests to send notifications to
  [
    "fcm" => [
      "notification" => [
        "title" => "Breaking News",
        "body" => "Lorem ipsum dolor sit amet." 
      ]
    ]
  ]
);
  1. Handle the response to check if the notification was successfully sent:
if ($response->getStatusCode() == 200) {
  echo "Notification sent successfully!";
} else {
  echo "Notification failed to send. Error:" . $response->getBody();
}

And that's it! This example demonstrates how to send a simple push notification using the Push Notifications library in PHP. Remember to replace the placeholders (<INSTANCE_ID>, <SECRET_KEY>, <DB_DSN>) with your actual credentials.