2016-06-24 35 views

Trả lời

22

Gửi tin nhắn qua Firebase Cloud Messaging sẽ gọi đến điểm kết thúc HTTP như được mô tả trong documentation on sending downstream messages.

Something đơn giản như điều này có thể làm các trick:

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'} 
); 

Cập nhật (April 2017): bây giờ bạn cũng có thể chạy mã rất giống với này trong Cloud Chức năng cho căn cứ hỏa lực. Xem https://firebase.google.com/docs/functions/use-cases#notify_users_when_something_interesting_happens

+0

Cảm ơn! nhưng đó là biến YOUR_API_KEY_HERE ?? Tôi không biết cách lấy chìa khóa đó từ bảng điều khiển FCM ... –

+2

Trong bảng điều khiển, biểu tượng Bánh răng> Cài đặt dự án> Nhắn tin qua đám mây ở đó bạn sẽ thấy khóa API của mình (khóa máy chủ). –

+1

Tôi đang cố gắng này ra và tôi không nhận được một lỗi, nhưng tôi không nhìn thấy các thông báo hoặc. Có lý do nào cho việc này không? Tôi đã thử một deviceId cụ thể cũng như một chủ đề ... ví dụ nhanh chóng sử dụng "/ topic/news" vì vậy tôi đã làm điều đó. *** cho ios btw, nhưng các thông số là giống nhau tôi nghĩ rằng ... – ingrid

8
//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"); 
Các vấn đề liên quan