I'm attempting to send an iOS push notification to a topic in Firebase using node.js. I followed this tutorial but can't figure out why the notification isn't making it to the devices subscribed to the topic. I am able to send topic messages from the console and listenForNotificationRequests() is removing the "notificationRequest" children successfully.
Here is the structure of the notification request in Firebase: example notification request
Here is the node.js code with keys/urls removed:
var firebase = require('firebase-admin');
var request = require('request');
var API_KEY = "APIKEYREMOVED"; // Your Firebase Cloud Messaging Server API key
// Fetch the service account key JSON file contents
var serviceAccount = require("./pathToJSON");
// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "URL_REMOVED"
});
ref = firebase.database().ref();
function listenForNotificationRequests() {
var requests = ref.child("notificationRequests");
requests.on("child_added", function(requestSnapshot) {
var request = requestSnapshot.val();
sendNotificationToUser(
request.username,
request.message,
function() {
requestSnapshot.ref.remove();
}
);
}, function(error) {
console.error(error);
});
};
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({
to : "/topics/user_"+username,
priority : "high",
notification: {
title: message
}
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
// start listening
listenForNotificationRequests();
Any help/advice is greatly appreciated!
via Spencj
No comments:
Post a Comment