如何从节点服务器发送Firebase云消息传递?
有什么办法从一个node.js
服务器发送FCM
通知?
我没有发现任何关于它在文档内。
通过Firebase云消息传递发送消息需要按照发送下游消息的文档中所述调用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年4月):现在,您还可以在Cloud Functions for Firebase中运行与此类似的代码。 请参阅https://firebase.google.com/docs/functions/use-cases#notify_users_when_something_interesting_happens
//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");