My working file so far. Note: It takes a few minutes for the notification to be sent.
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send('Hello from Rebeloper!');
});
exports.sendPushNotifications = functions.https.onRequest((request, response) => {
response.send('Attempting to send push notification...');
console.log('LOGGER --- Trying to send message...');
var uid = 'UXp0GIZlsndwXMsPm2zVD0p45zl2';
return admin.database().ref('/users/' + uid).once('value', snapshot => {
var user = snapshot.val();
console.log('Username: ' + user.username + ' ; fcmToken: ' + user.fcmToken);
//See documentation on defining a message payload.
var message = {
notification: {
title: 'TITLE',
body: 'BODY'
},
data: {
score: '850',
time: '2:45'
},
token: user.fcmToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
return response;
})
.catch((error) => {
console.log('Error sending message:', error);
throw new Error('Error sending message:', error);
});
});
// This registration token comes from the client FCM SDKs.
// var registrationToken = 'fTCyM8WkS4g:APA91bHRuILsb13NZj-kmDZ8JW4dnsAeNTf0nUvPlZwB733rC6EldSd3_zcFZgL9G8c84ZZeaMyhQCq23uVH3HooXgJyu26hxv45Lx65S2ia6ApS1MDeyQTAnBk0OrVb0f1qpYhB5D7X';
// //See documentation on defining a message payload.
// var message = {
// notification: {
// title: 'TITLE',
// body: 'BODY'
// },
// data: {
// score: '850',
// time: '2:45'
// },
// token: registrationToken
// };
//
// // Send a message to the device corresponding to the provided
// // registration token.
// admin.messaging().send(message)
// .then((response) => {
// // Response is a message ID string.
// console.log('Successfully sent message:', response);
// return response;
// })
// .catch((error) => {
// console.log('Error sending message:', error);
// throw new Error('Error sending message:', error);
// });
});