Push Notification Cordova, FCM And PHP

This post is about how to create a push notification in mobile app, using Cordova, firebase cloud messaging (FCM) and PHP as a server-side programming language. And we are gonna use cordova-plugin-fcm-with-dependecy-updated as a cordova plugin. An here's the step.

Example Cordova Push Notification

- Register a FCM project, and set your app id as, com.exampleyourprojectid.lokal or you can create you can create real app id for your own app, go to https://console.firebase.google.com/ to do that
- Create cordova project, using this command:
cordova create project_folder com.exampleyourprojectid.lokal
- Move terminal directory to your project using command:
cd project_folder
- Download the google-services.json on FCM dashboard, put it on your project_folder
- Add the plugin:
cordova plugin add cordova-plugin-fcm-with-dependecy-updated
- Add Android platform to your cordova project:
cordova platform add android
- Now build your app:
cordova build android
- Open android studio, open project locate to the path project_folder/platform/android, then after android finish synchronizing your project,  add rules to your root-level build.gradle file, to include the google-services plugin and the Google's Maven repository:

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.2.0' // google-services plugin
    }
}
allprojects {
    // ...
    repositories {
        // ...
        google() // Google's Maven repository
    }
}

Based on this tutorial: https://firebase.google.com/docs/cloud-messaging/android/first-message

- Now open other text editor, add attribute on body: <body onload="onLoad()"> and some JavaScript code line at www/index.html

<script type="text/javascript" src="cordova.js"></script>
<script>
function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}
// device APIs are available
//
function onDeviceReady() {
    document.addEventListener("pause", onPause, false);
    document.addEventListener("resume", onResume, false);
    document.addEventListener("menubutton", onMenuKeyDown, false);
    // Add similar listeners for other events

    FCMPlugin.onTokenRefresh(function(token){
        // alert("TOKEN: "+ token );
    });
    FCMPlugin.getToken(function(token){
        var t = null==token ? "NULL": token;
        // alert("TOKEN IS : " +t);
    });
    FCMPlugin.onNotification(function(data){
     
        if (null==data){
            alert("data is null");
        }else{
            if(data.wasTapped){
                //Notification was received on device tray and tapped by the user.
                alert( JSON.stringify(data) );
            }else{
                //Notification was received in foreground. Maybe the user needs to be notified.
                alert( JSON.stringify(data) );
            }         
        }
    });
    //Subscribe to topic must be last or other callback will not work
    FCMPlugin.subscribeToTopic('generalTopic');
}
function onPause() {
    // Handle the pause event
}
function onResume() {
    // Handle the resume event
}
function onMenuKeyDown() {
    // Handle the menubutton event
}
</script>

- Now test the app using emulator:
cordova emulate android to emulate in AVD
- To test push notification using postman, download postman, then import fire_base.json to postman, you can download here : fire_base.json
- Still in Postman, change the header authorization key using key you get from google Firebase dashboard
- Choose fcm_send_test then click the button "Send"

Postman Push Notification

- To create a PHP as a server side to send notification, create the following function:

<?php
function send_push_notification(){
$url = 'https://fcm.googleapis.com/fcm/send';
$fcm_api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$title = "test";
$body = "test";
$topic = "generalTopic";
$data_string = '{
    "notification": {
        "title": "'.$title.'",
        "body": "'.$body.'",
        "sound": "default",
        "click_action": "FCM_PLUGIN_ACTIVITY",
        "icon": "fcm_push_icon"
    },
    "data": {
        "param1": "value1",
        "param2": "value2"
    },
 
    "to": "/topics/'.$topic.'",
    "priority": "high",
    "restricted_package_name": ""
}';
$ch = curl_init(  );
curl_setopt( $ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_POST, true);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Authorization: key='.$fcm_api_key
));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
echo json_encode($response);
}
?>

Every time you want to  send push notification to mobile device, call the send_push_notification() function above.

Comments

Popular posts from this blog

ERROR 1348 Column Password Is Not Updatable When Updating MySQL Root Password

How To Create Spring Boot Project Using Netbeans

How To Connect SSH Using PEM Certificate On Windows

How To Use React Ckeditor Upload File Image With Demo and Example Codes

Spring Kafka - how to use ReplyingKafkaTemplate send and reply synchronously