AI/ML
Top 7 Real-world Use Cases: Enhancing Customer Service with ChatGPT
18th April 2023
7 minsLearn how to build an AI-powered WhatsApp chatbot step-by-step, leveraging Node.js and OpenAI’s capabilities. From setting up a Meta business account to integrating WhatsApp API and OpenAI, this guide empowers businesses to streamline customer interactions and unlock new possibilities in automated communication.
In today’s digital age, harnessing the power of artificial intelligence (AI) to enhance customer interactions is paramount for businesses striving to stay ahead in the market. WhatsApp, being one of the most widely used messaging platforms globally, presents a prime opportunity for businesses to engage with their audience effectively. Enter the realm of AI-powered WhatsApp chatbots. These virtual assistants are revolutionizing customer service, providing round-the-clock support, and streamlining communication processes.
Whether you’re a burgeoning startup or an established enterprise, navigating through the steps of development can be made simpler with the right approach. In this comprehensive guide, we’ll explore the fundamental principles, step-by-step procedures, and crucial considerations necessary for integrating the WhatsApp Business API with your Node.js application. Harnessing the power of OpenAI’s natural language processing capabilities, we’ll craft a seamless user experience that resonates with your audience.
From setting up your WhatsApp Business account to integrating OpenAI’s API with your Node.js code, follow along as we demystify the process and empower you to build your own AI-driven solution. This transformative journey into the realm of AI-driven conversational agents is not one you have to undertake alone. An AI Chatbot Development Company can serve as your trusted partner, providing invaluable insights and expertise along the way. Let’s embark on this exciting expedition together.
Fill the details and click on Submit.
2. Create a new Meta (Facebook) App (click here).
After login, click on “My Apps”
3. Now click on “create app”
4. Select “Other” and click “next”.
5. Choose App Type: “Business” and click “Next”.
6. Provide app details and click on “Create App”
1. Add WhatsApp to your Meta (Facebook) App.
To obtain a permanent WhatsApp Access Token, follow 1 to 3 steps:
1. Create a “System User”:
2. Add Assets.
3. Generate System User Access Tokens.
Choose the app that will use the token and set the token expiration to never.
4. Add a new Business Number for WhatsApp
5. Add a Payment Method
6. Test your new Business Number for WhatsApp
1. Verify WhatsApp Webhook Callback.
export async function GET(req: NextRequest) {
let hubMode = req.nextUrl.searchParams.get("hub.mode");
let hubChallenge = req.nextUrl.searchParams.get("hub.challenge");
let hubToken = req.nextUrl.searchParams.get("hub.verify_token");
//find the token in database
if (
hubMode === "subscribe" &&
hubToken === "<value from .env OR from database>"
) {
console.log("verified successfully");
return new Response(hubChallenge);
}
return new Response("Invalid Credentials", { status: 400 });
}
also we need to keep the following highlighted data
In our code, we need various identifiers such as the access token, app secret, test number, phone number ID, and business account ID. These identifiers help us determine from whom we are receiving messages and to whom we need to send messages.
// WhatsApp will triger this post request once user asked question to bot and also response to the user
export async function POST(req: NextRequest) {
let res: any = await req.json();
let questionFromWhatsapp =
res?.entry?.[0]?.changes?.[0]?.value?.messages?.[0]?.text?.body; // question received from whatsapp
if (
questionFromWhatsapp == undefined ||
questionFromWhatsapp.trim().length <= 0
) {
//if the request is only about status don't move further
// return NextResponse.json({ message: "received" });
return new Response("received", { status: 200 });
}
//get the phone number id from the response. this phone number is business number
const phoneNumberId =
res?.entry?.[0]?.changes?.[0]?.value?.metadata["phone_number_id"];
//this method will return the phone number from whom the message has been received
const responseNumber = getResponseNumber(res);
// retriving userId from database
try {
const version = "v18.0";
//check whether limit is reached or not
const phoneNumberId = "your phone number id";
const recipientPhoneNumber = "+" + responseNumber;
// const accessToken = process.env.WHATSAPPTOKEN
const accessToken = "token which you get from facebook";
try {
//--------------- This code is for sending message to telegram
const url = `https://graph.facebook.com/${version}/${phoneNumberId}/messages`;
// Define the data to be sent in the request body
const data = {
messaging_product: "whatsapp",
recipient_type: "individual",
to: `${recipientPhoneNumber}`,
type: "text",
text: {
preview_url: false,
body: "Hii, I am a chatbot, I am currently busy, I will get back to you soon.",
},
};
// Define the options for the fetch request
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(data),
};
// Make the POST request using fetch
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// Handle the data as needed
} catch (error) {
// Handle the error as needed
console.log(error);
}
return new Response("received", { status: 200 });
} catch (error) {
console.log("error", error);
}
} catch (error: any) {
console.log(error);
//mantain the error log in database, in case of unhandle error
}
}
const getResponseNumber = (res: any) => {
return res?.entry?.[0]?.changes?.[0]?.value?.contacts[0]?.wa_id;
};
In this comprehensive guide, we’ve navigated the intricacies of integrating the WhatsApp Business API with a Node.js application. From setting up webhooks to processing incoming messages and sending tailored responses, we’ve covered essential steps like handling access tokens, app secrets, test numbers, phone number IDs, and business account IDs.
This seamless integration not only empowers businesses to automate communication on WhatsApp but also unlocks a myriad of possibilities, whether it’s crafting customer support bots, automating marketing endeavors, or pursuing personal projects. As you embark on this journey, remember that this is merely a foundation. The WhatsApp Business API offers a plethora of additional features waiting to be explored and integrated into your application.
As you continue to refine your AI chatbot development endeavors, consider leveraging the expertise of an AI Chatbot Development Company. Their insights and support can catalyze your progress, ensuring your chatbot endeavors reach their full potential. Always refer to the official WhatsApp Business API documentation for comprehensive and accurate information as you advance in your development journey.