Web Solutions Point

This blog is all about sharing solutions

Free Advertisement

Saturday, March 24, 2018

How to send push notification on your Cordova / ionic application (only android)

In this article i will show you how you can send push notification in your Cordova / ionic application on android devices. Here i will use GCM to send push notification. If you are not aware of GCM so, it is a cloud messaging service provided by Google by which you can send push notifications on android devices.

Note : In this article i will cover only android device. I will cover IOS device in later article. So , please don't try this for IOS devices because it will not work. This steps will only applied after you get your GCM registration key.


To send push notification on android device you need 3 things

  • API key 
  • GCM registration id 
  • Data payload

If you have these 3 things you are ready to send push. As per google guidelines you can send push notification to 1000 device in one request. So, let's get started.

Here is the php code to send push notification. I am using php cUrl to send request to GCM server. GCM will process the request & then GCM will send us response with respect to that request. Later we will analyse the response.

1.  gcm.class.php

class GCM
{
    public function send_push_android($registatoin_ids, $message, $dry_run)
    {
        $fields = array(
            'registration_ids' => $registatoin_ids, // accept one $registatoin_id or array of $registatoin_ids
            'data' => $message, // Your date payload comes here
            'dry_run' => $dry_run // This parameter, when set to true, allows developers to test a request without actually sending a message.
        );

        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $response = curl_exec($ch);

        curl_close($ch);
        return $response;
    }
}

2.  send.php

 
error_reporting(E_ALL);

include("gcm.class.php");

// you will get API key from google console or firebase console
define('GOOGLE_API_KEY', '***************************************');

// array containing all registration_ids
// you can fetch all registration ids from database
$androidUsers = array(0 => array('registration_id' => 'e5nwbThMnvs:APA46bGXLTcstgao5Ewxrh7Z92-N6golbwB-e2H5hZpkQH8205XMUtPAIOUt7tZxjIJU2XgA_LSsL09SHNB-dSYzXGmmyX_gyuAxVXlA8Q2xZFiMyRW31fLCgmaEtH7mEjJJIflG3bBq'));

if (count($androidUsers) > 0) { // if registatoin_ids exists
    $registatoin_ids = [];

    // push all registatoin_ids into array
    foreach ($androidUsers as $value) {
        array_push($registatoin_ids, $value['registration_id']);
    }

    // creating object of GCM class
    $gcmObj = new GCM();

    // create message payload for push
    $message = array(
        "subject" => "Web Solutions Point",
        "message" => "You are getting push notification from Web Solutions Point",
        "uniqid" => uniqid(), // generates a uniqid id for all your notification
        "force-start" => 1, // If you add force-start: 1 to the data payload the application will be restarted in background even if it was force closed
        "content-available" => "1", // When a notification or message is sent and this is set to true, an inactive client app is awoken
        "soundname" => "default", // use default sound for notification
        "priority" => "high", // For some users of the plugin they are unable to get messages sent via GCM to show up on their devices. If you are running into this issue try setting the priority of the message to high in the payload
        "time_to_live" => 2419200 // This parameter specifies how long (in seconds) the message should be kept in GCM storage if the device is offline. The maximum time to live supported is 4 weeks, and the default value is 4 weeks.
        "key1" => "value 1", // you can send additional data with GCM using key value pair
        "key2" => "value 2"
    );

    // call send_push_android function & pass all the required parameters
    echo $gcmResponse = $gcmObj->send_push_android($registatoin_ids, $message, false);
    // converting JSON into array
    $gcmResponse = json_decode($gcmResponse, true);

    // FOREACH STARTS HERE
    // Check GCM response for each user
    foreach ($androidUsers as $key => $user) {
        $newRegistration_id = '';
        if (isset($gcmResponse['results'][$key]['registration_id']) && isset($gcmResponse['results'][$key]['message_id'])) {
            // if you get registration_id & message_id in response
            // means success, but the registration token should be updated in the server database
            $newRegistration_id = $gcmResponse['results'][$key]['registration_id'];
            $status = $gcmResponse['results'][$key]['message_id'];

            continue;
        } elseif (isset($gcmResponse['results'][$key]['message_id'])) {
            // if you get only message_id in response
            // success, nothing required
            $status = $gcmResponse['results'][$key]['message_id'];
        } elseif (isset($gcmResponse['results'][$key]['error'])) {
            // if you get error in response
            // error = "Unavailable" ( should be resent )
            // error = "InvalidRegistration" ( maybe the value got corrupted in the database )
            // error = "NotRegistered" ( registration token should be removed from the server database because the application was uninstalled from the device )
            $status = $gcmResponse['results'][$key]['error'];
        }
    }
    // FOREACH ENDS HERE
}

Put these two files in your localhost folder. Replace API key & registration id with your id. Then access push.php from you browser address bar. As soon as you execute this script you will get push notification on your device.

You will get response like this
{
    "multicast_id": 8830936931471935000,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1521876222537348%53c48035f9fd7ecd"
        }
    ]
}

For example

Here are JSON results for 6 registration IDs ( 1, 2, 3, 4, 5, 6 ) with 3 messages successfully processed, 1 canonical registration token returned, and 3 errors:

{ "multicast_id": 216,
  "success": 3,
  "failure": 3,
  "canonical_ids": 1,
  "results": [
    { "message_id": "1:0408" },
    { "error": "Unavailable" },
    { "error": "InvalidRegistration" },
    { "message_id": "1:1516" },
    { "message_id": "1:2342", "registration_id": "32" },
    { "error": "NotRegistered"}
  ]
}



In this example you will get 6 results for 6 registration IDs
  • First message means - successfully delivered
  • Second message means - should be resent because device is not available
  • Third message means - had an unrecoverable error (maybe the registration id got corrupted in the database)
  • Fourth message means - successfully delivered
  • Fifth message means - successfully delivered, but the registration token should be updated in the server database
  • Sixth message means - registration token should be removed from the server database because the application was uninstalled from the device


No comments:

Post a Comment