Last active
November 16, 2020 22:16
-
-
Save vladfatu/e377a75dff18117b8592d4b6c9eaeae2 to your computer and use it in GitHub Desktop.
Send transactional push notifications from a Firebase Cloud Function
This file contains 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
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