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);
});
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-08-18 11:00:00 +0000
Seen: 11 times
Last updated: Oct 27 '21
What does the error message "TypeError: e.endsWith is not a function" mean in Redoc?
What is the method of focusing on a specific ESLint error message in the scripts of my package.json?
What does the error message "1 timer(s) still in the queue" indicate in an Angular/Karma unit test?
In NextAuth.js, why is the HTTP GET action not supported and resulting in an error?
When trying to access the newly added S3 asset, why does it keep returning a 502 error?