Hello folks, today in this article, we will be going through how you can create a chatbot and integrate it with WhatsApp Cloud API. We will be also giving this chatbot a brain using an OpenAI model.
Prerequisites
To create a WhatsApp chatbot you will need a few Prerequisites:
- A Meta Business Account
- A Meta Developer Account
- An OpenAI Account
You can create these easily using your existing Facebook account or create a new one.
Once you have all of these ready, we can get started by configuring in Meta Developer account to enable WhatsApp integration.
Configuration
Create Meta App
Logon to https://developers.facebook.com/apps/.
Create a New App.
Choose Business
Choose your Business Manager Account and enter other details
Click on Create App and your app will be created.
Add WhatsApp Integration
Open your app page and you will land on this screen.
Scroll down and find WhatsApp. Click on Set up
WhatsApp Configuration
You will see this screen. Here you have been assigned a Temporary Token and a Test WhatsApp Number. We will use these to send and receive messages on that Test WhatsApp Number. In future, if you want, you can connect real numbers as well which will be a proper WhatsApp Business account.
You have to configure a few recipient WhatsApp numbers for testing, up to 5 numbers can be added.
The Phone Number ID shown will be used later to use WhatsApp Cloud API, so keep it handy.
Authentication Token
The final piece of configuration is generation of an authentication token which will be used while communicating with Meta APIs.
Log on to https://business.facebook.com/ and open your Business Settings.
Navigate to the System Users section from left-hand menu
You can add a user or if it already exists, click on Generate New Token
Select the app you created earlier and check whatsapp_business_management and whatsapp_business_messaging permissions and then copy this token.
Application
So we will develop our application using NodeJS and Express
We will install basic dependencies like express
morgan
helmet
cors
axios
dotenv
We will create two API routes one for verification of the webhook (this will be only used once) and one to receive messages/updates from WhatsApp
- GET
/api/webhook
- To verify this webhook - POST
/api/webhook
- To receive messages from WhatsApp
So, we can configure a webhook in WhatsApp so that every time a message or update comes we will get notified of that and we can respond accordingly.
This GET API of /api/webhook
will be used for verification of this webhook where WhatsApp will send a token and a couple of parameters and we will verify if all those matches whatever is configured on our server. It is called a Verification Token. We create a random long verification token and store it in the environment variables of our server.
This will be our API route for GET /api/webhook
app.get("/api/webhook", (req, res) => {
const VERIFY_TOKEN = process.env.VERIFY_TOKEN;
// Parse params from the webhook verification request
let mode = req.query["hub.mode"];
let token = req.query["hub.verify_token"];
let challenge = req.query["hub.challenge"];
// Check if a token and mode were sent
if (!mode || !token) {
return res.status(403).send({ error: "Missing mode or token" });
}
// Check the mode and token sent are correct
if (mode === "subscribe" && token === VERIFY_TOKEN) {
// Respond with 200 OK and challenge token from the request
console.log("WEBHOOK_VERIFIED");
return res.status(200).send(challenge);
} else {
// Responds with '403 Forbidden' if verify tokens do not match
return res.sendStatus(403);
}
});
To verify our webhook we go to WhatsApp Configuration from the Meta App page
Add the Webhook API URL and the Verification token and click on Verify and Save. You can use a proxy like ngrok if you are still in development. Webhook URL must be an HTTPS one with no Self-signed certificate in the chain.
In Webhook fields, Subscribe to messages
Now for the receiving messages webhook, POST /api/webhook
app.post("/api/webhook", async (req, res) => {
try {
// Parse the request body from the POST
const body = req.body;
// Check the Incoming webhook message
console.log("Incoming webhook: " + JSON.stringify(body));
// Validate the webhook
if (req.body.object) {
// Handle the event
if (req.body.object === "whatsapp_business_account") {
const entry = req.body.entry[0];
// Handle the message
if (entry.changes) {
for (const change of entry.changes) {
if (
change.value &&
change.field === "messages" &&
change.value.contacts &&
change.value.messages
) {
// Handle the value
const value = change.value;
const userName = value.contacts[0].profile.name;
const messages = value.messages;
// Handle messages
for (const message of messages) {
if (
message.type === "text" &&
message.text &&
message.text.body
) {
const waid = message.from;
const text = message.text.body;
const msgId = message.id;
console.log(
"Message from " + waid + " - " + userName + ": " + text
);
}
}
}
}
}
}
}
} catch (err) {
console.error("Error occured " + err);
}
});
This is how we will extract messages from the incoming webhook when the user sends a Text message on the configured number. We can use this text message and then reply accordingly.
For our application, we pass this as a prompt to an OpenAPI model and then get a response from the AI and respond to the user. We are using openai
package for this.
For responding to the user, we will use the https://graph.facebook.com/v13.0/<phonenumberid>/messages
API endpoint with the authentication token we collected earlier in Headers like below:
await axios.post(
process.env.WHATSAPP_SEND_MESSAGE_API,
{
messaging_product: "whatsapp",
recipient_type: "individual",
to: waid,
type: "text",
text: {
preview_url: false,
body: reply,
},
},
{
headers: {
Authorization: "Bearer " + process.env.WHATSAPP_TOKEN,
},
}
);
By this response will be send to the user.
Conclusion
This is how we will use WhatsApp Cloud API and integrate WhatsApp with your application. There are endless possibilities since Meta recently made this API available to all, which was earlier only available to business owners or BSP (Business Service Partners).
Documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/reference
Top comments (2)
Too cool!!! Thank you for sharing ❤️
Glad you liked it Renan