Ask Your Question
1

How can I utilize the WhatsApp cloud API with Node.js and Express to send messages?

asked 2022-03-04 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-03-08 05:00:00 +0000

woof gravatar image

To utilize the WhatsApp cloud API with Node.js and Express to send messages, you will need to follow these steps:

  1. Register for a WhatsApp Business account and create a verified business profile.
  2. Create a project on the Facebook Developer Console and enable the WhatsApp Business API.
  3. Install the Twilio WhatsApp API library for Node.js by running it on the command prompt using the following command: npm install twilio.
  4. Obtain the credentials (Account SID and Authentication Token) and the WhatsApp sender phone number from the Twilio console Dashboard.
  5. Import the twilio library and configure the client by adding your Twilio credentials and the WhatsApp sender phone number in your Node.js file using the following code:
const accountSid = 'YOUR_ACCOUNT_SID';
const authToken = 'YOUR_AUTH_TOKEN';
const client = require('twilio')(accountSid, authToken);
const fromNumber = 'whatsapp:' + YOUR_WHATSAPP_SENDER_NUMBER;
  1. Create an Express route to handle the incoming message requests, and define a function for sending WhatsApp messages using the Twilio API:
app.post('/whatsapp', (req, res) => {
  const { body, from } = req.body;
  const message = {
    body: 'Hello! This is a WhatsApp message sent using Node.js and the Twilio API.',
    from: fromNumber,
    to: from,
  };
  client.messages.create(message)
    .then(() => {
      console.log('Message sent successfully!');
      res.status(200).send('Message sent successfully!');
    })
    .catch((err) => {
      console.error(err);
      res.status(500).send('Error sending message: ' + err);
    });
});
  1. Start your Express server using the listen method and specify the port for the server to listen on.

  2. To send a WhatsApp message, make a HTTP POST request to the Express route you created in step 6, passing the recipient phone number and message in the request body.

That's it! You should now be able to send WhatsApp messages using the WhatsApp cloud API and Node.js with Twilio.

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-03-04 11:00:00 +0000

Seen: 8 times

Last updated: Mar 08 '23