Created
April 20, 2017 11:42
-
-
Save Yogatopia/0225016b485635245e7632ccf7fd0ce9 to your computer and use it in GitHub Desktop.
AppServer code for Push Notification
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var firebase = require('firebase-admin'); | |
var request = require('request'); | |
// Fetch the service account key JSON file contents | |
var serviceAccount = require("path/to/serviceAccountKey.json"); | |
var env = require("path/to/env.json"); | |
// Your Firebase Cloud Messaging Server API key | |
var API_KEY = env.CLOUD_MESSAGE_API_KEY; | |
// Initialize the app with a service account, granting admin privileges | |
firebase.initializeApp({ | |
credential: firebase.credential.cert(serviceAccount), | |
databaseURL: "https://<your database>.firebaseio.com/" | |
}); | |
ref = firebase.database().ref(); | |
function listenForNotificationRequests() { | |
var requests = ref.child('notificationRequests'); | |
requests.on('child_added', function(requestSnapshot) { | |
var request = requestSnapshot.val(); | |
sendNotificationToTopic( | |
request.from_username, | |
request.message, | |
function() { | |
console.log("Successfully sent!"); | |
requestSnapshot.ref.remove(); | |
} | |
); | |
}, function(error) { | |
console.error(error); | |
}); | |
}; | |
function sendNotificationToTopic(from_username, message, onSuccess) { | |
// Send a message to devices subscribed to the provided topic. | |
var topic = `/topics/list`; | |
// https://firebase.google.com/docs/reference/admin/node/admin.messaging.NotificationMessagePayload | |
var payload = { | |
"notification": { | |
title: "hello", | |
body: `${from_username} ${message}`, | |
icon: "new", | |
sound: "default", | |
clickAction: "fcm.ACTION.HELLO", | |
// badge: '1' | |
}, | |
data: { | |
extra: "some_extra_data", | |
} | |
}; | |
var options = { | |
collapseKey: 'demo', | |
contentAvailable: true, | |
priority: "high", | |
timeToLive: 60 * 60 * 24 // Set the message as high priority and have it expire after 24 hours. | |
}; | |
firebase.messaging().sendToTopic(topic, payload, options) | |
.then(function(response) { | |
// See the MessagingTopicResponse reference documentation for the | |
// contents of response. | |
console.log("Successfully sent message:", response); | |
onSuccess(); | |
}) | |
.catch(function(error) { | |
console.log("Error sending message:", error); | |
}); | |
} | |
// start listening | |
listenForNotificationRequests(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment