1 | initial version |
To utilize the WhatsApp cloud API with Node.js and Express to send messages, you will need to follow these steps:
npm install twilio
.const accountSid = 'YOUR_ACCOUNT_SID';
const authToken = 'YOUR_AUTH_TOKEN';
const client = require('twilio')(accountSid, authToken);
const fromNumber = 'whatsapp:' + YOUR_WHATSAPP_SENDER_NUMBER;
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);
});
});
Start your Express server using the listen
method and specify the port for the server to listen on.
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.