0

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?

admin.messaging() worked!!

AL.
  • 36,815
  • 10
  • 142
  • 281
Saira Nawaz
  • 710
  • 2
  • 10
  • 24
  • 1
    You're already using the firebase-admin sdk so why are you going through the trouble of building the request from scratch when you can call admin.messaging().sendToDevice() ? https://firebase.google.com/docs/cloud-messaging/admin/send-messages – Cisco May 03 '17 at 14:10
  • @FranciscoMateo thanks for your response. I did a lot search for sending device to device messaging in firbase but was never returned with your suggesstion. I will definitely go for it and will update my question. – Saira Nawaz May 03 '17 at 14:16

1 Answers1

0

This is running code in my module

var request = require('request');
var sendMsgToGroup = function(deviceId, message) {
    request({
        url: 'https://fcm.googleapis.com/fcm/send',
        method: 'POST',
        headers: {
            'Content-Type': ' application/json',
            'Authorization': 'key=<YOUR API KEY>'
        },
        body: JSON.stringify({
            notification: {
                title: message,
                body: 'Testing Notificaiton'
            },
            "to": deviceId
        })
    }, function(error, response, body) {
        if (error)
            console.log(error);
        else if (response.statusCode >= 400)
            console.log("HTTP Error" + response.statusCode + "-" + 
                        response.statusCode + "\n" + body);
        else
            console.log(body);
        });
    };

module.exports.sendMessageToGroup = sendMsgToGroup;

You can call this function like

 var FCM = require('./FCM/fcm_config.js');
 FCM.sendMessageToGroup("<Device Token Number>", 'testing');

Reference Link

Dhiral Kaniya
  • 1,941
  • 1
  • 19
  • 32