X
    Categories: Learn PHP Tutorials, Tips And Guides

Adding Push Notification in PHP With OneSignal and Toastr

In a previous tutorial, I developed a chat application using Pusher and discussed the process of setting up a Pusher account and testing the responses of the app. In this tutorial, I will show you how to add browser and push notifications to the PHP chat app. I will use toastr.js for browser notifications and OneSignal API for push notifications in PHP.

Chat App Follow Up

Let’s recall the previous tutorial. I included AJAX and pusher.js libraries to work with the messages and the related response. The messages were sent on the click event of the Enter key. Pusher authenticated the messages and and then pass on to the client in the AJAX request.

In the new version, when you get the messages while the app is active, you can set Toast notifications for a quick look at the message.

Here is the AJAX call which takes the PHP file URL and the message data:

// Send AJAX request to the PHP file on server

   function ajaxCall(ajax_url, ajax_data) {

       $.ajax({

           type: "POST",

           url: ajax_url,

           //dataType: "json",

           data: ajax_data,

           success: function(response) {

               //console.log(response);

           },

           error: function(msg) {}

       });

   }

Now when the message is displayed to the user, a Toast notification is also displayed.

Show a Toastr with toastr.js

Toastr is a Javascript library for non-blocking notifications. It requires jQuery (I’ve already added jQuery files in previous scripts). Now to add Toastr notifications to the chat app, first add these two scripts in the head tag.

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">

<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>

Next, I will add the Toastr method in the binding event of the received message which is my_event. Remember I have got the response in the data variable and append it to the message_display div.

// bind the server event to get the response data and append it to the message div

   channel.bind('my_event',

       function(data) {

           //console.log(data);

           $('.messages_display').append('<p class = "message_item">' + data + '</p>');

           $('.input_send_holder').html('<input type = "submit" value = "Send" class =

           "btn btn-primary btn-block input_send" />');

           $(".messages_display").scrollTop($(".messages_display")[0].scrollHeight);

// Show toastr notification here

toastr.options = {

              timeOut: 5000,

              extendedTimeOut: 0,

               fadeOut: 200,

               fadeOut: 200

           };

           toastr.info(data);

       });

Now when you send a message to anyone, it shows the Toastr to the recipient. Check out the following screencap:

Show Web Push Notification For Chat Messages

Next, I’ll setup web push notifications for the chat application. Here I’m going to use OneSignal API for this: for this, follow these steps:

  1. Setup the OneSignal account
  2. Add the application
  3. Get the app key and the API key

Since the account setup is simple, I will not cover it in this tutorial. If you need help, follow this guide.

When you have successfully created the account, OneSignal will give you a customized script that contains the appID. Add it into the head tag. Here is the script:

<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>

   <script>

           var OneSignal = window.OneSignal || [];

           OneSignal.push(function() {

               OneSignal.init({

               appId: "c7xxbca5-xxxx-4e54-xxxx-ca07exxxx013",

               autoRegister: false,

               notifyButton: {

                   enable: true,

               },

               notifyButton: {

        enable: true /* Set to false to hide */

    },

    welcomeNotification: {

      "title": "My Custom Title",

      "message": "Thanks for subscribing!",

    }

               });

           });

 </script>

 

Once the script is added, you will see the red OneSignal icon appear at the bottom right corner of the window.

Click the icon and subscribe to the notifications. Next, for sending chat notifications to the chat app users, you need to add the send notifications functionality to the app. Basically whenever an app user sends a message, OneSignal will create a notification and sends it to all subscribed persons.

For this, you need to add the following code to message.php page. This code will use the appID and API key for authentication.The function accepts $message as an argument and curl will create the notification:

function sendMessage($message){

   $content = array(

     "en" => $message

     );

   $fields = array(

     'app_id' => "cxxxbca5-xxxx-4e54-xxxx-ca07exxxx013",

     'included_segments' => array('All'),

     'contents' => $content

   );

   $fields = json_encode($fields);

   $ch = curl_init();

   curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");

   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',

                      'Authorization: Basic MmFhMDkxN2ItYTRjOC00OTg1LWJmZjItY2JhYTY4Y2RjMTQx'));

   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

   curl_setopt($ch, CURLOPT_HEADER, FALSE);

   curl_setopt($ch, CURLOPT_POST, TRUE);

   curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

   $response = curl_exec($ch);

   curl_close($ch);

   return $response;

 }

Now call this method in the trigger function of the Pusher. When Pusher sends the message, a notification will be created by the OneSignal API and send it to all subscribed users.

 // Return the received message

 if($pusher->trigger('test_channel', 'my_event', $data)) {

  $response = sendMessage($data);

  echo 'success';     

 } else {    

   echo 'error';

 }

The good thing is even when you are not online and the browser tab is also closed, you will still get chat notifications through the OneSignal push notification service. Here is the PHP chat application demo that highlights the push notification functionality.

Note: As there is no login method for the user at the moment, it will NOT authenticate the user, save or retrieve message history. I might add these features in a later version of the app.

Shahroze Nawaz :Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He’s always in search of new frameworks and methods to implement them. Besides his coding life, he loves movies and playing soccer with friends. You can email him at shahroze.nawaz@cloudways.com