Как отправить Firebase Cloud Messaging с сервера node?

Есть ли способ отправить уведомления из FCM с сервера node.js?

Я ничего не нашел в документации.

Ответы

Ответ 1

Отправка сообщений через Firebase Cloud Messaging требует вызова конечной точки HTTP, как описано в документации при отправке сообщений ниже по течению.

Что-то простое, как это могло бы сделать трюк:

var request = require('request');

function sendMessageToUser(deviceId, message) {
  request({
    url: 'https://fcm.googleapis.com/fcm/send',
    method: 'POST',
    headers: {
      'Content-Type' :' application/json',
      'Authorization': 'key=AI...8o'
    },
    body: JSON.stringify(
      { "data": {
        "message": message
      },
        "to" : deviceId
      }
    )
  }, function(error, response, body) {
    if (error) { 
      console.error(error, response, body); 
    }
    else if (response.statusCode >= 400) { 
      console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage+'\n'+body); 
    }
    else {
      console.log('Done!')
    }
  });

sendMessageToUser(
  "d7x...KJQ",
  { message: 'Hello puf'}
);

Обновление (апрель 2017 г.): теперь вы можете также запустить код, очень похожий на это в Cloud Functions for Firebase. См. https://firebase.google.com/docs/functions/use-cases#notify_users_when_something_interesting_happens

Ответ 2

//I done by this code using node- gcm module.
//We're using the express framework and the node-gcm wrapper

var express = require('express');
var gcm = require('node-gcm');
//init express
var app = express();
app.get('/push', function (req, res) {
    var message = new gcm.Message({
        data: { key1: 'hello' },
        notification: {
            title: 'SPECOZ Offers1',
            body: 'body_data'
        }
    });

    // Set up the sender with you API key, prepare your recipients' registration tokens.
    var sender = new gcm.Sender('Api_Key');
    sender.send(message, 'device_token', function (err, response) {
        if (err) {
            console.error("Error:", err);


        }

        else console.log("Response:", response);
        res.send(response);
    });

});
app.listen("pass the port number");

Ответ 3

const admin = require('firebase-admin');
  const payload = { 
   notification: {
        title: 'this is title', body: 'this is body'
    },
   data: {
           balance: 100,
          priceplanId: 1235 
  }
}  
const deviceToken ='yourtoekn' | ['yourtoekn'];
admin.messaging().sendToDevice(deviceToken, newpayload)
                .then((_response) => console.log(_response))
                .catch(error => console.log(error));

выделенный текст Вы можете отправлять уведомления на устройства ios и Android;