Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.