Firebase Cloud Messaging in ionic apps

People who are used to integarte GCM in ionic apps, its time to migrate to FCM( Firebase Cloud Messaging )

App/Device/Client side steps :

Use plugin https://github.com/fechanique/cordova-plugin-fcm

STEP 1
cordova plugin add cordova-plugin-fcm

STEP 2

if(window.cordova) {

FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
// $state.go(‘message’, {id:data.pageId});
// $location.path(‘app/userList’);
alert(‘onNotification tapped true’);
} else {
alert(“xxxxxxxxxxxx”+data);
}
},
function(msg){
// alert(“asdf”+msg)
alert(‘onNotification callback successfully registered: ‘ + msg);
FCMPlugin.onTokenRefresh(function(token){
console.log( token );
window.localStorage.setItem(“deviceId”,token);
});
},
function(err){
// alert(“fjkjg”+err)
alert(‘Error registering onNotification callback: ‘ + err);
}
);
}

 

Update version 1.0.0 to 1.2.3
dependencies {
classpath ‘com.android.tools.build:gradle:1.0.0+’
}

STEP 3

to fix crash, add app id to  existing defaultConfig like below,
defaultConfig {
applicationId “com.init.solutions”
// remaining code
}

Server Side:

var request = require(‘request’);

var options = {
url: ‘https://fcm.googleapis.com/fcm/send’,
headers: {
// ‘User-Agent’: ‘request’,
‘Content-Type’: ‘application/json’,
‘Authorization’ : ‘KEY=XXXXde90z3A:APadasdasdasdasddsA’
},
body : JSON.stringify({
“notification”:{
“title”:”Notification title”,
“body”:”Notification body”,
“sound”:”default”,
“click_action”:”FCM_PLUGIN_ACTIVITY”,
“icon”:”fcm_push_icon”
},
“data”:{
“param1″:”value1”,
“param2″:”value2”
},
“to”:”c7fgnn9QJ50:APA91bGaLIdYmhpy0O0T…..”,
//”priority”:”high”,
//”restricted_package_name”:””
})

};

request.post( options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
} else {
console.log(body) // Show the HTML for the Google homepage.
}
})

Leave a Reply

Your email address will not be published. Required fields are marked *