Wednesday, 3 May 2017

FCM Node.js server issue android

For sending FCM upstream messages through my app I followed this tutorial Sending Notifications with Firebase

My working code is below:

var firebase = require('firebase-admin');
var request = require('request');
const functions = require('firebase-functions');
firebase.initializeApp(functions.config().firebase);

var API_KEY = "my api key"; // Your Firebase Cloud Messaging Server API key

// Fetch the service account key JSON file contents
//var serviceAccount = require("serviceAccountKey.json");

// Initialize the app with a service account, granting admin privileges
//firebase.initializeApp({
//  credential: firebase.credential.cert(serviceAccount),
//  databaseURL: "https://-----.firebaseio.com"
//});

exports.listenForNotificationRequests = functions.database.ref('/notificationRequests')
    .onWrite(event => {
       const request = event.data.val();
              sendNotificationToUser(
                    request.username,
                    request.message,
                    function() {
                      console.error("success");
                    }
                  );
    });

function sendNotificationToUser(username, message, onSuccess) {
  request({
    url: 'https://fcm.googleapis.com/fcm/send',
    method: 'POST',
    headers: {
      'Content-Type' :' application/json',
      'Authorization': 'key='+API_KEY
    },
    body: JSON.stringify({
       notification: {
       title: message, //title of notification
       body: message
        },
      to : usertoken //a static registered user token
    })
  }, function(error, response, body) {
    if (error) { console.error(error); }
    else if (response.statusCode >= 400) {
      console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
    }
    else {
      onSuccess();
    }
  });
}

On running this code I am receiving RemoteMessage in my MyFirebaseMessagingService 's onMessageReceived , but this message return null notification or data. So notification does not appear in app. Can any body here help me what I am doing wrong?



via Saira Nawaz

No comments:

Post a Comment