This guide explains how to handle webhook responses when you receive inbound messages or interactions from your users on your WhatsApp number. The following use cases are covered in the code snippets below:
You need a Plivo account — sign up with your work email address if you don’t have one already. If this is your first time using Plivo’s APIs, follow our instructions to set up a Node.js development environment.
You must have an onboarded WhatsApp account to receive inbound messages. If a number is listed as connected, it can receive inbound messages.
Create a file called receive_whatsapp.js
and paste into it this code.
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.post('/receive_whatsapp/', (req, res) => {
const { From, To, ContentType, Body, Media0, Button, Interactive, Location } = req.body;
switch (ContentType) {
case 'text':
console.log(`Text Message - From: ${From}, To: ${To}, Text: ${Body}`);
break;
case 'media':
console.log(`Media Message - From: ${From}, To: ${To}, URL: ${Media0}, Caption: ${Body}`);
break;
case 'button':
console.log(`Button Message - From: ${From}, To: ${To}, Text: ${Button.Text}, Payload: ${Button.Payload}`);
break;
case 'interactive':
if (Interactive.Type === 'button_reply') {
console.log(`Interactive Button - From: ${From}, To: ${To}, ID: ${Interactive.ButtonReply.Id}, Title: ${Interactive.ButtonReply.Title}`);
} else if (Interactive.Type === 'list_reply') {
console.log(`Interactive List - From: ${From}, To: ${To}, ID: ${Interactive.ListReply.Id}, Title: ${Interactive.ListReply.Title}, Description: ${Interactive.ListReply.Description}`);
}
break;
case 'location':
console.log(`Location - From: ${From}, To: ${To}, Latitude: ${Location.Latitude}, Longitude: ${Location.Longitude}, Name: ${Location.Name}, Address: ${Location.Address}`);
break;
}
res.status(200).send('Message Received');
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Add or update a webhook URL from this link to a WhatsApp Business Account. Once you’ve done this, you should be able to receive inbound messages.
Send a WhatsApp message to the Plivo number you specified using WhatsApp application.