1 | initial version |
Here is an example of how to send a WhatsApp message via MessageBird using a Firebase cloud function:
npm install messagebird firebase-admin --save
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const messagebird = require('messagebird')(functions.config().messagebird.key);
exports.sendWhatsAppMessage = functions.https.onCall(async (data, context) => {
// Check that the user is authenticated
if (!context.auth) {
throw new functions.https.HttpsError('unauthenticated', 'The function must be called while authenticated.');
}
// Extract the message data from the request
const { to, message } = data;
// Send the message via MessageBird
try {
await messagebird.messages.create({
to: `whatsapp:${to}`,
from: 'whatsapp:+1234567890',
type: 'text',
content: {
text: message,
},
});
return { success: true };
} catch (error) {
console.error(error);
throw new functions.https.HttpsError('unknown', 'An unknown error occurred while sending the WhatsApp message.');
}
});
firebase functions:config:set messagebird.key="YOUR_API_KEY" messagebird.whatsapp_number="+1234567890"
const sendWhatsAppMessage = firebase.functions().httpsCallable('sendWhatsAppMessage');
sendWhatsAppMessage({ to: '+1234567890', message: 'Hello, world!' })
.then((result) => {
console.log(result.data);
})
.catch((error) => {
console.error(error);
});