Tutorials

Article Content:Push Notification PHP via Onesignal

Push Notification PHP via Onesignal

Last week I had worked with my friend to publish a new Android application, the application process started with adding the quotes through the back-end -which created by CodeIgniter- once the admin adds a new quote users notified with the updates across multiple platforms, also the admin should have the ability to notify specific users, this better than opening the application to check if there were a new quotes or not, it should be via push notifications API.

Quite simple, is it?!

Important note:
This Part For Android Notifications,So if You Are Not Going To Integrate Android Platform With OneSignal Skip This Part.
Why Onesignal over firebase for push notifications?

After some discussion we chose Onesignal as a great option over firebase for some reasons:

1- Firebase not completely free, but Onesignal is a full Free API at least until now.

2- Firebase is specified to Android devices, so you could not apply the cloud messaging Aka (FCM) to other platforms like iPhone or Windows phone, although the client has not released the quotes application on other platforms, but if he did that in the future We would stick with this task again and again to support the new platforms rather than changing some lines of code to tie the new platforms to Onesignal API, because Onesignal API supported many platforms, it's like doing it once run everywhere.

3-Onesignal has a very clear documentation, step by step instructions, that helped me a lot.

 

Important note:
 google has integrated the old cloud messaging service (GCM) to their firebase services package (FCM).

 

The Push notifications cycle through PHP

1-When you integrate Onesignal SDK with your any platform like (Android, iPhone,,etc.) or your website, the SDK will detect the platform information  and create new identification Id, which is unique id for this device (Android, iPhone) or browser (chrome, Firefox) and send all these data to their cloud API.

Additionally, it's recommended to add your custom data after subscription process to have the ability to track subscribers across all platforms, in this situation I prefer to add a user ID.

OneSignal supports tagging users with simple string data, Tags can be used for targeting notifications to specific users or groups, Tags values can also be used as variables in notification content. You can send your custom data like age, gender, user name, etc.

2-Then To Create Notification open your application (as example PHP) and put your dynamic data and click send, which will call the Onesignal restful API to create a notification..

3-Onesignal will take your custom data (as example title, icon, and the targeted users) and create a notification for those users depends on their devices data that has already registered.

Onesignal_flowchart

 

How to integrate onesignal with codeigniter

1- Create new Onesignal account, Create new app , then activate the platforms which you want to apply push notification for it.in our example we would support (chrome, Firefox) only but for sure you can add more. To Show the Full steps Follow this instructions.

2- To activate chrome and Firefox you have two ways to integrate (HTTPS, HTTP) ways, I will follow Web Push SDK Setup (HTTP), because it's the common option for many websites but it's recommended to use HTTPS. , In our example we will use the Onesignal HTTPS subdomain for free, so follow installation steps from here to HTTP websites

3- Choose the way you prefer to Triggering & Customizing Permission Messages from here, in my tutorial I chose the Slidedown way

3- Create Quotes.php controller with two methods, Subscribe()  to handle your website subscriptions and send_message() to handle sending notifications through Onesignal API to the subscribers

 

<?php

class Quotes extends CI_Controller
{

    function __construct()
    {
        parent::__construct();

    }


    // this function will redirect to book service page
    function index()
    {
        $this->subscribe();
    }

    // this function to load service book page
    function subscribe()
    {
        $this->load->view('content/site_subscribe');
    }

    /**
     * Create New Notification
     *
     * Creates adjacency list based on item (id or slug) and shows leafs related only to current item
     *
     * @param int $user_id Current user id
     * @param string $title Current title
     *
     * @return string $response
     */
    function send_message(){
        $message = $this->input->post("message");
        $user_id = $this->input->post("user_id");
        $content = array(
            "en" => "$message"
        );

        $fields = array(
            'app_id' => "ccb2c4c9-8621-4208-b57a-e82dccc316ef",
            'filters' => array(array("field" => "tag", "key" => "user_id", "relation" => "=", "value" => "$user_id")),
            'contents' => $content
        );

        $fields = json_encode($fields);
        print("\nJSON sent:\n");
        print($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 NGM0Mzk5YjMtNTQzMi00OTkwLTkyY2EtMTI1MzNhODBmZjgz'));
        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;
    }

}
/* End of file news.php */
/* Location: ./application/controllers/Services.php */

 

4- Create site_subscribe.php file into views directory, we can handle subscribe and unsubscribe operations with Onesignal JavaScript API, when you click subscribe link your browser data will send to Onesignal API to subscribe the push service with your id , then when press allow it will return back your id with the tag which user id

 
         <div class="starter-template">
                <h1>OneSignal  Subscription</h1>
                <p class="lead">User Subscribe Page</p>
            </div>

            <div class="contact-form">

                <p class="notice error"><?= $this->session->flashdata('error_msg') ?></p><br/>

                <form id="ServiceRequest" action="<?= base_url() ?>quotes/send_message" method='post'>

                    <div class="form-group">
                        <label class="control-label">Message Body:</label>
                        <input type="text" name="message" class="form-control" placeholder="Add Your Message" value="" >
                    </div>
                    <div class="form-group">
                        <label class="control-label">Message Body:</label>
                        <input type="text" name="user_id" class="form-control" readonly value="4444" >
                    </div>
                    <div id='submit_button'>
                        <input class="btn btn-success" type="submit" name="submit" value="Send data"/>
                    </div>
                </form>
            </div>

        <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
        <script>
            var OneSignal = window.OneSignal || [];
            OneSignal.push(["init", {
                appId: "ccb2c4c9-8621-4208-b57a-e82dccc316ef",
                subdomainName: 'ourtutorial',
                autoRegister: true,
                promptOptions: {
                    /* These prompt options values configure both the HTTP prompt and the HTTP popup. */
                    /* actionMessage limited to 90 characters */
                    actionMessage: "We'd like to show you notifications for the latest news.",
                    /* acceptButtonText limited to 15 characters */
                    acceptButtonText: "ALLOW",
                    /* cancelButtonText limited to 15 characters */
                    cancelButtonText: "NO THANKS"
                }
            }]);
        </script>
        <script>
            function subscribe() {
                // OneSignal.push(["registerForPushNotifications"]);
                OneSignal.push(["registerForPushNotifications"]);
                event.preventDefault();
            }
            function unsubscribe(){
                OneSignal.setSubscription(true);
            }

            var OneSignal = OneSignal || [];
            OneSignal.push(function() {
                /* These examples are all valid */
                // Occurs when the user's subscription changes to a new value.
                OneSignal.on('subscriptionChange', function (isSubscribed) {
                    console.log("The user's subscription state is now:", isSubscribed);
                    OneSignal.sendTag("user_id","4444", function(tagsSent)
                    {
                        // Callback called when tags have finished sending
                        console.log("Tags have finished sending!");
                    });
                });

                var isPushSupported = OneSignal.isPushNotificationsSupported();
                if (isPushSupported)
                {
                    // Push notifications are supported
                    OneSignal.isPushNotificationsEnabled().then(function(isEnabled)
                    {
                        if (isEnabled)
                        {
                            console.log("Push notifications are enabled!");

                        } else {
                            OneSignal.showHttpPrompt();
                            console.log("Push notifications are not enabled yet.");
                        }
                    });

                } else {
                    console.log("Push notifications are not supported.");
                }
            });


        </script>

5- Get your app_id and RESTful_id from app settings and replace them into site_subscribe.php file and send_message() function

onesignal_app_id

Also change the subdomainName parameter with what you choose in the configure platform 

onesignal_configure_platform

Important note:
in our example we put a random Id, but in a real product you should replace it with a real user ID in your system

6- Now go to http://localhost/codeigniter_onesignal/quotes# link and you will see the notification like this image

onesignal_php_codeigniter_integration

7- After Click allow to subscribe with the service, you will see welcome message like this

onesignal_welcome_message_example

Important Note:
You can change welcome message as you need to see  details here

8-Finally try to write a message in the input and click send data and you will see messa the  and response like this.

onesignal_notification_example



  • ducbui
    Thank you, good tutorial !
    June 30, 2017
    Reply
  • smac
    sir can you please tell/show how to send it without codeigniter (only with php)
    July 9, 2017
    Reply
  • Saeid
    Thanks a lot for good tutorial. Could you please share your MVC PHP files. I copied your code in my MVC project, but don't find some function.
    September 15, 2017
    Reply
    • admin
      info@webeasystep.com
      you are welcome :) you can follow my video , i do it step by step
      September 16, 2017
      Reply
  • Rizki Darmawan
    Thanks for good tutorial. (Y) What if I want to send notification to user/device that must login first? Like the example on web push notification on facebook. Thanks.. please responses.
    September 20, 2017
    Reply
    • admin
      info@webeasystep.com
      you are welcome Rizki , already my example cover this subject , please see YouTube tutorial and you will find the answer for what you ask for. but for recap , you can do that by adding the user id or whatever any specific identify data in the tag field thanks
      September 20, 2017
      Reply
      • Rizki Darmawan
        rizkidarmawanrpl@gmail.com
        Oh.. sorry i have not watch that. I will then :) so its can (onesignal) do that. i say thank you... i will try.
        September 21, 2017
        Reply

Leave a Reply

Your email address will not be published.


Notify me of followup comments via e-mail.
You can also Subscribe without commenting.