Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladfatu/e377a75dff18117b8592d4b6c9eaeae2 to your computer and use it in GitHub Desktop.
Save vladfatu/e377a75dff18117b8592d4b6c9eaeae2 to your computer and use it in GitHub Desktop.
Send transactional push notifications from a Firebase Cloud Function
function sendPush(uid) {
// Get the user from Firestore
const getDeviceTokensPromise = admin.firestore()
.collection('users').doc(uid).get();
// Get the User profile from Firebase Auth
const getUserProfilePromise = admin.auth().getUser(uid);
Promise.all([getDeviceTokensPromise, getUserProfilePromise])
.then(function(results) {
// The array containing all the user's tokens.
const tokens = Object.keys(results[0].data().notificationTokens);
// The user profile from Firebase Auth
const user = results[1];
// Check if there are any device tokens.
if (tokens.length === 0) {
return console.log('There are no notification tokens to send to.');
}
// Notification details.
const payload = {
notification: {
title: 'Payment completed!',
body: `Thank you, ${user.displayName}, we received your payment.`
}
};
// Send notifications to all tokens.
admin.messaging().sendToDevice(tokens, payload)
.then(function(response) {
console.log('Successfully sent push: ', response);
return response;
})
.catch(function(error) {
console.log('Error sending push:', error);
});
return results;
})
.catch(function(error) {
console.log('Error retrieving tokens or user details:', error);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment