Ask Your Question
4

What is the method for sending a WhatsApp message via MessageBird using a Firebase cloud function?

asked 2022-08-18 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-10-27 00:00:00 +0000

devzero gravatar image

Here is an example of how to send a WhatsApp message via MessageBird using a Firebase cloud function:

  1. Install the MessageBird SDK and Firebase Admin SDK in your project:
npm install messagebird firebase-admin --save
  1. Create a new cloud function in your Firebase project:
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.');
  }
});
  1. Add your MessageBird API key and WhatsApp number to your Firebase project:
firebase functions:config:set messagebird.key="YOUR_API_KEY" messagebird.whatsapp_number="+1234567890"
  1. Call the cloud function from your client-side code:
const sendWhatsAppMessage = firebase.functions().httpsCallable('sendWhatsAppMessage');

sendWhatsAppMessage({ to: '+1234567890', message: 'Hello, world!' })
  .then((result) => {
    console.log(result.data);
  })
  .catch((error) => {
    console.error(error);
  });
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-08-18 11:00:00 +0000

Seen: 11 times

Last updated: Oct 27 '21