Building an AI-Powered WhatsApp Chatbot: A Step-by-Step Guide

Table of contents

Summary:

Learn 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.

Step 1: Setting Up Meta (Facebook) Business Account and App

  1. First create a Meta business account, (click here).

Fill the details and click on Submit.

2. Create a new Meta (Facebook) App (click here).

  • (Log in) to your Meta (Facebook) Developer Account.

After login, click on “My Apps”

click on my app

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”

Step 2: Setting Up Meta (Facebook) App for WhatsApp Integration

1. Add WhatsApp to your Meta (Facebook) App.

  • In the “Developers Dashboard”, choose your app. 
  • Locate “Add products to your app” in your app’s dashboard tab.
  • Choose “WhatsApp” for setup.
  • Select your Meta (Facebook) Business Account
  • Navigate to App settings > Basic from the sidebar
  • Save changes.
  • Set App Mode to Live

Step 3: Generate WhatsApp Token

To obtain a permanent WhatsApp Access Token, follow 1 to 3 steps:

1. Create a “System User”:

  • Visit the Meta Business Suite.
  • Find your business account in the top-left dropdown menu and click its Settings (gear) icon.
  • Click Business Settings.
  • Add an Admin system user.

2. Add Assets.

  • After creating the system user, click on Add Assets.
  • Navigate to Apps > “Your app name”.
  • Select your app and grant full control to manage the app.

3. Generate System User Access Tokens.

  • Click the Generate New Token button on the system user.

Choose the app that will use the token and set the token expiration to never.

  • Select “whatsapp_business_messaging” and “whatsapp_business_management” permissions.
  • Generate the token.
  • Copy the access token and store it securely.

4. Add a new Business Number for WhatsApp

  • You can use your own business number or utilize the provided test number for your WhatsApp chatbot.
  • In the WhatsApp Developer Dashboard, navigate to WhatsApp > API Setup from the sidebar.
  • Proceed to “Step 5: Add a Phone Number,” click Add phone number.
  • Provide details required in the following form.
  • Verify your number using the received code.
  • Once successfully added, select your phone number in Step 1 of API Setup.

5. Add a Payment Method

  • To send messages via WhatsApp, you need a valid payment method. Visit here for details.
  • After adding your business phone number, click “Add payment method” to address the “Missing valid payment method” alert.
  • You’ll be directed to your WhatsApp account settings. Click “Payment Methods” > “Add business payment method” and follow the prompts to add your card info.

6. Test your new Business Number for WhatsApp

  • Return to WhatsApp Developer Dashboard, navigate to API Setup 
  • Enter a testing “To” number.
  • Click “Send message” to verify successful message delivery.

Step 4: Configure WhatsApp API Webhook settings

1. Verify WhatsApp Webhook Callback.

  • In WhatsApp Developer Dashboard, navigate to Configuration.
  • Under Webhook, click edit
  • Now, we need to provide a live webhook URL and token to WhatsApp. The live URL is your application’s URL, and the token is also generated from your end. In the image below, I’ve added my Ngrok URL because my Node.js application is running on Ngrok, and I’ve used a UUID as a token.
  • In the verification process, WhatsApp sends a GET request to the callback URL to validate the hub token. The following code, written in Next.js (a Node.js framework), handles this verification process. The verification will only be successful if your code sends a 200 status code in response, as shown below.

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 });

 }

  • Find the “messages” field and subscribe to it by checking the box.
  • Now we need WhatsApp Access token and Facebook app secrete which we get from the same WhatsApp business account
  • In the below image you see Facebook app secrete

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.

Step 5: Sending and Receiving message through API

  • In the provided TypeScript code, we have successfully integrated the WhatsApp API to send and receive messages. Additionally, I have incorporated OpenAI and a custom-trained AI model to respond to incoming messages, for my goal.
  • The callback URL provided to WhatsApp is used for both GET and POST requests. When a message is sent to the business number, WhatsApp triggers this callback URL and sends the message along with user details. The following code reads that message and responds based on the implemented logic.
  • The POST function is an asynchronous function that handles incoming POST requests. It first parses the incoming request to JSON and extracts the message sent by the user from WhatsApp. If the message is undefined or empty, it returns a response with a status of 200 and does not proceed further.
  • The function then retrieves the business phone number and the sender’s phone number from the request. 
  • The function then prepares a POST request to send a message back to the user via WhatsApp. It constructs the URL for the request, defines the message to be sent, and sets the request options, including the method, headers, and body.
  • The function then sends the request using the fetch function. If the request is successful, it returns a response with a status of 200. If an error occurs at any point, it is logged to the console.
  • The getResponseNumber function is a helper function that extracts the sender’s phone number from the incoming request.
  • This code provides a basic example of how to integrate a Node.js application with the WhatsApp Business API, allowing for automated sending and receiving of 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;

};

Conclusion

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.

Bhargav Bhanderi
Bhargav Bhanderi
Director - Web & Cloud Technologies

    Have a Project in Mind, Let's Discuss

    India
    A-404, Ratnaakar Nine Square,
    Opp Keshavbaug party plot,
    Vastrapur, Ahmedabad (380015), Gujarat.
    +91 79 40086120
    United States
    4059 Ida Ln,
    Vestavia Hills,
    Birmingham AL 35243,
    United States.
    +1(205) 417-7500
    Hong Kong
    Unit 06, 25/F,
    Metroplaza Tower II,
    223 Hing Fong Road,
    Kwai Chung, Hong Kong.
    +852 92014949