Subscribe My Site

How to Get WhatsApp Business API in 2026: Setup, Cost & AI

1. What Is WhatsApp Business API?

WhatsApp Business API, now commonly presented as the WhatsApp Business Platform, is a business messaging interface that allows your software to communicate with customers through WhatsApp. It is not simply another mobile application. Its purpose is to connect WhatsApp conversations with systems such as customer relationship management (CRM) software, ecommerce platforms, order-management tools, customer-support dashboards, booking systems, and custom applications.

With the regular WhatsApp Business App, a person usually opens a conversation and replies manually from a phone or a supported linked device. With the API, your backend sends requests to Meta's Cloud API endpoint. When a customer messages your business number, Meta can send an event to your server through a configured webhook. Your server can then process the message, save it in a CRM, notify an agent, retrieve an order status, or send an automated response that follows WhatsApp's policies.

Consider an online store. A customer places an order, and the store's order system creates an order number. Your backend can send an approved WhatsApp template confirming the order. If the customer later sends the words “Order status”, the incoming webhook can notify your application. Your application can look up the order in its database and send the latest delivery information back to the customer. The API makes this software-driven workflow possible.

One important benefit of the Cloud API is that Meta hosts the infrastructure. You do not need to deploy and maintain the old On-Premises API containers on your own servers. Meta's documentation identifies the Cloud API as the preferred approach, and the On-Premises API was sunset on 23 October 2025. New integrations should therefore be designed around the Cloud API and the current official documentation.

Key components of the API

  • WhatsApp Business Account (WABA): The WhatsApp business account associated with your business in Meta's ecosystem.
  • Business phone number: The number customers use to contact your business and receive messages from it.
  • Phone Number ID: A Meta identifier used in API requests to identify the registered business number. It is different from the visible phone number.
  • Access token: A credential that authorizes API requests. Treat it like a password and never publish it in browser code or a public repository.
  • Meta app: The developer application in which you add and configure the WhatsApp product.
  • Webhook: A public HTTPS endpoint on your server that receives incoming-message notifications and message-status events.
  • Message templates: Pre-approved message formats used for eligible business-initiated communication, including messages sent outside the customer-service window.

The API does not automatically provide a complete customer-support application. You must either build the interface and workflows yourself or use a provider that offers an inbox and related tools. The API is the connection layer; your application determines how conversations are stored, assigned, searched, and handled by your team.

2. WhatsApp Business App vs WhatsApp Business API

The WhatsApp Business App is convenient for small businesses that handle a manageable number of conversations manually. It offers a business profile, catalogue, greeting messages, away messages, quick replies, and labels. If one person manages a local shop or service and does not need complex automation, the app may be enough.

The Business Platform API is designed for businesses that need to connect messaging with software, manage conversations across a team, automate repetitive workflows, or synchronize customer information with a CRM. The API is not automatically better for every business. It adds technical and operational responsibilities, and message charges may apply.

A common misunderstanding is that API access means unlimited or free bulk messaging. It does not. The API is a technical access layer. You must still follow opt-in requirements, approved-template rules, quality standards, messaging limits, and applicable charges. Sending unsolicited messages can damage your quality rating and may lead to restrictions.

Which option should you choose?

  • Choose the Business App if you mainly reply manually, have a small number of daily conversations, and do not need a CRM or custom automation.
  • Consider the API if several agents need to handle the same business number, conversations must be logged in a CRM, or messages need to be triggered by orders, appointments, or support events.
  • Consider a Business Solution Provider if you want an inbox and automation without building your own backend. Compare its subscription, message markup, onboarding charges, and contract terms before signing up.

3. Who Needs WhatsApp Business API?

The API is most useful when WhatsApp is part of a repeatable business process rather than just a personal communication channel. It can help ecommerce stores send order updates, service companies manage appointment reminders, education providers share course notifications, and support teams route questions to the right department.

For example, an ecommerce business may connect the API to its order database. When an order is confirmed, the system sends a notification. When the parcel is dispatched, it sends a shipping update. If the customer replies with a question, the CRM can create a support ticket and assign it to an agent. This reduces manual work and keeps conversation history connected to the customer record.

A clinic or appointment-based service may use approved templates for appointment confirmations and reminders, subject to applicable rules and customer consent. A coaching business may use WhatsApp to answer course-access questions and route payment issues to a human team member. A local retailer may connect a catalogue or inventory system so that staff can respond with current product information.

When the API may be unnecessary

If you receive only a few messages each day and can comfortably answer them from one phone, the regular Business App may be simpler and less expensive. Do not adopt an API merely because it sounds advanced. First identify the specific process you want to improve, estimate the expected conversation volume, and calculate both software and messaging costs.

4. Requirements and Documents

Before starting, prepare access to the Meta account that controls your business assets. The exact verification requirements can vary according to your account, country, business type, and the features you want to use. You can generally begin exploring the Cloud API with Meta's test environment, but production use and higher limits may require additional business information or verification.

Basic preparation checklist

  • A Facebook or Meta account with access to the business assets.
  • A Meta Business Portfolio, previously known in many interfaces as a Business Manager.
  • Access to Meta for Developers and permission to create or manage an app.
  • A business phone number that can receive the verification code by SMS or voice call.
  • A business name and supporting information that accurately represent the organization.
  • A public HTTPS endpoint if you are building your own webhook integration.
  • A secure server or hosting environment for access tokens and API credentials.
  • A clear customer opt-in process and a plan for handling opt-outs.
  • A privacy notice explaining how customer information and conversations are handled.

Depending on the review, Meta may request business documents or evidence that connects the business name to the organization. Keep your legal business details consistent across your portfolio, website, documents, and public business information. Do not submit false documents or use a business name that you are not authorized to represent.

5. How to Get WhatsApp Business API: Step-by-Step Setup

The following process describes the direct Cloud API route. Meta may change the layout and wording of its dashboard, so treat the steps as a practical guide rather than a promise that every button will have the same name. Use the official Meta documentation linked at the end of this article whenever a screen differs from the instructions here.

Step 1: Open your Meta Business Portfolio

Sign in to the Meta account that should own or manage the business assets. Open Meta Business Suite or the Business Portfolio settings area. If you already have a portfolio, confirm that you have administrator access or the specific permissions needed to add a WhatsApp account and manage apps. If you are creating a new portfolio, enter accurate business details and save them carefully.

Use a business-controlled email address where possible, enable two-factor authentication, and avoid sharing your personal login with staff or developers. Give each team member an individual role that matches their responsibilities. This makes it easier to remove access when someone leaves the organization.

Step 2: Register on Meta for Developers

Open Meta for Developers and complete the developer registration flow if your account has not already been registered. Review the platform terms and any identity or security checks presented during signup. Once registration is complete, open the developer dashboard and choose the option to create an app.

Select the app type and business association that match the current options in the dashboard. The labels may change over time. If the dashboard asks you to connect the app to a Business Portfolio, choose the correct portfolio rather than a personal or unrelated business asset.

Step 3: Create an app and add the WhatsApp product

Enter an app name and a contact email address. Select the business portfolio when prompted, then create the app. From the app dashboard, locate the product catalogue and add WhatsApp. The WhatsApp Getting Started area should display the development setup, including a temporary access token, a test business phone number, a Phone Number ID, and a WhatsApp Business Account ID.

Keep a record of the identifiers, but do not publish tokens or secrets. A Phone Number ID and WABA ID are identifiers; an access token is a credential. They should not be treated as interchangeable values.

Step 4: Add a test recipient

Meta's development environment typically allows you to send test messages to a limited set of recipient numbers that you add and verify. Add a phone number that you control, select the correct country code, and complete the verification step. Use the test environment to understand the request format before connecting your production number.

Step 5: Send the sample message

Use the sample request shown in your dashboard. You can send it from the dashboard or from a terminal using the Graph API. Replace the version, Phone Number ID, token, and recipient with the values displayed in your account. The sample below uses placeholders deliberately.

curl -X POST "https://graph.facebook.com/vXX.X/PHONE_NUMBER_ID/messages" \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "messaging_product": "whatsapp",
    "to": "91XXXXXXXXXX",
    "type": "template",
    "template": {
      "name": "hello_world",
      "language": { "code": "en_US" }
    }
  }'

If the request succeeds, the API normally returns a response containing a message identifier. A successful API response confirms that Meta accepted the request; it does not guarantee that the recipient read the message. Delivery and read receipts are separate status events that you can receive through a webhook.

Step 6: Connect your business account and phone number

When you are ready to move beyond the test number, follow the production onboarding flow. Select the correct Business Portfolio and WABA, then add the phone number you intend to use. Meta may ask you to verify the number through an SMS or voice call. Enter the verification code in the dashboard and complete any display-name review or registration step shown.

Before connecting an existing number, check whether it is currently active in the regular WhatsApp or WhatsApp Business App. A number already in use may need to be migrated or may qualify for a coexistence flow. Read the number section below before proceeding, because removing a number from an app can affect its existing app experience and chat history.

Step 7: Complete business verification and display-name review

Business verification and display-name review are separate concepts. Verification checks information about the organization. Display-name review checks whether the name shown to WhatsApp users complies with the naming rules. You may be able to test before completing all verification steps, but production limits and feature access can depend on account status, quality, and current Meta requirements.

Use a display name that customers can reasonably associate with your business. Avoid misleading names, promotional phrases, unsupported claims, or names that imply an affiliation you do not have. If Meta rejects a name, read the reason and correct the underlying issue instead of repeatedly submitting variations that do not meet the policy.

Step 8: Plan for a durable access token

The temporary token in the Getting Started panel is useful for initial testing, but it is not a production credential strategy. For a production application, configure the appropriate system user and permissions in your Business Portfolio, assign the necessary assets, and generate a token according to Meta's current guidance. The required permissions commonly include the WhatsApp messaging and business-management permissions relevant to your integration.

Store the token in a server-side environment variable or a secrets manager. Never place it in frontend JavaScript, a public GitHub repository, a Blogger post, a screenshot, or a mobile app package where it can be extracted. Set a process for rotation and revocation, and make sure only authorized administrators can access it.

Step 9: Configure a webhook

A webhook is how your server receives incoming message notifications and status updates. Create a public HTTPS endpoint on your backend, configure a verification token that you generate, and enter the callback URL and token in the WhatsApp configuration area of your Meta app. Subscribe the app to the relevant WhatsApp Business Account webhook fields, including the message events your application needs.

Your endpoint must respond correctly to Meta's verification challenge. For real events, acknowledge the request quickly and process it safely. In production, use a queue so a temporary AI or CRM outage does not cause the webhook request to remain open for too long. Validate webhook authenticity using Meta's documented signature mechanism before trusting the payload.

Step 10: Create and submit message templates

Templates are required for many business-initiated messages outside the customer-service window. Create templates with a clear purpose, accurate wording, and appropriate category. Use variables only where they are needed, and make sure the final message remains understandable when the variable is inserted. Submit the template for review and wait for its status to become approved before relying on it in production.

Step 11: Test, monitor, and launch gradually

Test inbound messages, outbound messages, status updates, invalid numbers, duplicate webhook deliveries, and failure scenarios. Confirm that your system does not send the same reply multiple times when Meta retries an event. Check that opt-outs are respected and that human agents can take over a conversation. Start with a small, consented audience and monitor delivery, quality, complaints, and costs before increasing volume.

6. Can You Use an Existing WhatsApp Number?

In many cases, you can use a phone number that your business already controls, but the onboarding route matters. A number actively registered in the regular WhatsApp or WhatsApp Business App may need to be removed from the app before it can be registered directly for the API. This can affect the existing app account and its chat experience. Do not delete or migrate a number until you understand the consequences and have backed up any information you need.

Meta also offers a coexistence experience for eligible businesses, allowing certain WhatsApp Business App numbers to connect to the Business Platform while continuing to use the app. Availability, eligibility, onboarding method, feature support, and limitations can vary. Follow the current Embedded Signup flow and official instructions for app users instead of assuming that every number can use coexistence.

What is WhatsApp Business App coexistence?

Coexistence is designed to let an eligible business keep using the WhatsApp Business App while also connecting the number to the platform. It can be useful when a business wants API automation but still wants staff to use the familiar mobile app. However, not every app feature or integration behaves identically after onboarding. Providers report limitations such as throughput caps and some app features being unavailable, so verify the exact current limitations before choosing this route.

Choose the number carefully

  • Use a number that your business controls and can continue to access.
  • Confirm that you can receive the required verification code.
  • Review migration and coexistence requirements before making changes.
  • Back up important business records and customer information using appropriate, lawful methods.
  • Tell customers if your contact number or support process is changing.

7. How to Send Your First Message with WhatsApp Cloud API

Once your test number, recipient, token, and Phone Number ID are available, you can send a sample template message. The request is an HTTP POST to the messages endpoint for your phone number. It includes the messaging product, recipient, message type, and template information. Use the API version currently shown in your Meta app or official documentation; do not copy an old version number from an outdated tutorial.

The cURL example in Step 5 illustrates the structure. In a real request, replace every placeholder with the correct value. Keep the Authorization header on the server side. If you are testing from a local terminal, avoid saving tokens in shell history or sharing terminal screenshots that reveal them.

Understanding the response

A successful response generally includes a WhatsApp message ID. Save that ID with your internal customer or order record so you can correlate later delivery-status events. The initial response does not prove that the message reached the customer's device. Your webhook can receive statuses such as sent, delivered, read, or failed, depending on the event and the platform's current reporting behavior.

If the request returns an error, inspect the HTTP status and the structured error object. Common causes include an expired token, incorrect Phone Number ID, missing permission, unverified recipient in the test environment, invalid template name, unsupported API version, or a recipient number in the wrong format. Avoid repeatedly retrying a request that is guaranteed to fail until the underlying problem is corrected.

8. What Is a WhatsApp Webhook and How Do You Set It Up?

A webhook is an HTTPS endpoint that receives event notifications from another service. In a WhatsApp integration, Meta can send webhook events when a customer sends a message or when the status of an outgoing message changes. Your server uses those events to update a CRM, trigger an automation, or notify a support agent.

Without a webhook, your application may be able to send messages but will not have a reliable event-driven way to receive customer messages and delivery updates. A webhook is therefore a central part of most two-way WhatsApp integrations.

Webhook verification in simple terms

During setup, Meta sends a verification request containing a mode, a verification token, and a challenge value. Your endpoint checks that the mode is the expected subscription mode and that the supplied token matches the secret you configured. If the values match, the endpoint returns the challenge exactly as required. If they do not match, it should reject the request.

The verification token is a secret that you choose for this handshake. It is not the same as the Meta access token. Use a long, unpredictable value and store it securely. Do not reuse a password or publish the token in your article, repository, or frontend application.

Minimum webhook checklist

  • Use a public HTTPS URL with a valid certificate.
  • Implement the GET verification challenge exactly as Meta documents.
  • Accept POST requests and parse the expected JSON payload.
  • Validate webhook signatures before processing production events.
  • Respond quickly, then process events asynchronously through a queue.
  • Store event IDs or message IDs to prevent duplicate processing.
  • Log failures without writing access tokens or unnecessary personal data to logs.
  • Subscribe only to the webhook fields your application actually needs.

Webhook payloads can contain more than one entry or change, so do not assume that every request contains exactly one message. Your code should safely iterate through the payload structure, handle missing fields, ignore unsupported message types, and cope with status notifications that do not contain a customer text message.

9. Message Templates, Categories, and the 24-Hour Customer Service Window

WhatsApp uses a customer-service window to distinguish customer-initiated conversations from business-initiated communication. When a customer sends your business a message, a service window opens or refreshes. During the applicable 24-hour window, your business can generally send free-form replies that are relevant to the conversation. Outside the window, business-initiated messages generally require an approved template.

This rule is important for reminders, promotions, order updates, and follow-ups. A business should not assume it can send any arbitrary message at any time simply because it has API access. Check the current Meta documentation for the exact rules, exceptions, and billing treatment that apply to your message type and market.

Common template categories

  • Marketing: Messages intended to promote products, services, offers, or engagement campaigns.
  • Utility: Transactional or account-related updates, such as an order confirmation or a service notification, when they meet the category rules.
  • Authentication: Eligible one-time passcodes and verification messages.
  • Service conversations: Customer-initiated support messages within the customer-service window are treated under the relevant service rules.

Template classification is determined by Meta's current rules and review process, not merely by the label selected by the sender. A promotional message should not be disguised as a utility notification to obtain a different rate or treatment.

Example of a clear utility template

Use variables for information that changes, such as the customer's name or order number. Avoid inserting unrelated promotional content into a utility template. Keep the message clear, useful, and consistent with the reason the customer agreed to receive updates.

Opt-in and opt-out

Collect customer permission before sending messages, and explain what kind of communication the customer is agreeing to receive. Keep a record of the consent source and timestamp where appropriate. Provide a simple way to stop messages, such as replying STOP where your workflow supports it, and make sure the opt-out is applied across the systems that send messages. Do not purchase lists or message people simply because their phone numbers are publicly visible.

10. WhatsApp Business API Pricing in India 2026: How Much Does It Cost?

There is no single flat monthly price for every WhatsApp API account. Your total cost can include Meta's message charges, a provider's platform or subscription fee, integration development, hosting, CRM software, AI usage, and taxes. The amount depends on the destination country, message category, delivery volume, and the specific commercial arrangement you choose.

Meta's pricing model has changed over time. The 2026 rate-card transition referenced in the supporting research is dated 1 October 2026. Treat the figures below as a dated India reference that must be checked against the current Meta rate card before publishing or preparing a business budget. The rate card shown in your account and Meta's current official pricing documentation take priority over third-party summaries.

India rate-card reference — 1 October 2026

Simple cost examples for 1,000 delivered messages

To understand the arithmetic, multiply the applicable per-message rate by the number of billable delivered messages. If 1,000 marketing messages were billed at the indicative ₹0.8631 rate, the base amount would be ₹863.10 before applicable taxes and provider fees. If 1,000 utility messages were billed at ₹0.1150, the base amount would be ₹115.00. These are examples using the reported rates above, not a quotation or guarantee of the amount Meta will charge.

Actual billing can differ because not every message is necessarily billable in the same way. Category, destination market, delivery status, customer-service window, free entry-point periods, monthly service allowances, and rate-card changes can all affect the invoice. Always calculate using the exact rules that apply to your account.

How to understand the 1 October 2026 changes

When Meta changes a rate card or billing model, older blog posts and provider pages can remain online with outdated figures. Check the effective date of the rate card and compare the message category definitions as well as the prices. A price copied from a previous year may no longer apply, even if the article still appears in search results.

Additional provider charges

A Business Solution Provider may charge a monthly subscription, per-agent fee, onboarding fee, automation fee, or markup on messaging. Some providers bundle a shared inbox, chatbot builder, broadcast interface, campaign reports, integrations, and support. Others charge separately for each feature. Ask for a written quotation that separates Meta's pass-through charges from the provider's own fees.

A practical budget formula

Estimate your monthly total using the following components:

  • Expected number of delivered messages by category and destination market.
  • Meta's current applicable rate for each category.
  • Provider subscription, per-agent, setup, and markup fees, if any.
  • CRM subscription or integration costs.
  • Backend hosting, database, monitoring, and backup costs.
  • AI model usage if you run a ChatGPT or Gemini-based support assistant.
  • Applicable taxes and a contingency for volume changes.

Start with a conservative estimate and compare it with actual usage after the first month. If your business sends promotional campaigns, calculate those separately from order updates and support conversations. This helps you identify which workflows are creating the largest costs.

11. How to Integrate WhatsApp API with a CRM System

CRM integration connects WhatsApp conversations with customer records, leads, sales opportunities, support tickets, and follow-up tasks. Instead of keeping customer details in separate spreadsheets or individual phones, your team can see the conversation in the context of the customer relationship.

There are four common approaches. The right one depends on your budget, technical skills, CRM, and the amount of customization you need.

Four common CRM integration methods

  1. Native CRM integration: Some CRM products offer a built-in WhatsApp integration or an approved partner connection. This is often the quickest route, but check whether the integration supports inbound messages, templates, assignment, reporting, and your required workflows.
  2. Business Solution Provider: A provider may offer a shared inbox and a connector for popular CRMs. This can reduce development work, but you should compare recurring charges and data-export options.
  3. No-code automation platform: Workflow tools can connect a webhook trigger to a CRM action. This is useful for simple lead creation or notifications. Complex conversation handling, retries, security, and high-volume processing may require custom development.
  4. Custom API integration: A developer builds the webhook, database mapping, CRM API calls, message sending, and agent interface. This provides flexibility but requires ongoing maintenance and monitoring.

Example CRM workflow

Imagine a customer clicks a WhatsApp link on your website and asks about a product. Meta sends the incoming message event to your webhook. Your backend identifies the sender's phone number, checks whether a CRM contact already exists, and creates or updates the record. The CRM can assign the conversation to a sales agent based on product category or region. The agent replies through the team inbox, which sends the message through the Cloud API.

When the customer makes a purchase, the ecommerce platform updates the same contact record with the order ID and purchase status. A later support message can then be associated with the existing customer rather than creating a duplicate lead. This gives the team a more complete view of the customer journey.

Useful CRM data fields

How to choose a CRM

Do not choose a CRM based only on a WhatsApp logo on its integrations page. Ask whether it supports your exact use case: two-way messaging, approved templates, media, message status, multiple agents, role-based permissions, conversation history, opt-out synchronization, and data export. Confirm whether the provider uses the official WhatsApp Business Platform and whether your business retains control of its WABA and phone number.

Before committing, test the integration with a small group of users. Check what happens when an agent leaves, when a customer opts out, when the CRM is unavailable, and when a webhook event is delivered more than once. These operational details are just as important as the initial connection.

12. How to Connect a WhatsApp Autoresponder with the ChatGPT API

One of the most useful advanced applications is a customer-support assistant that can answer routine questions on WhatsApp. You can connect incoming WhatsApp messages to an AI model through your own backend. The backend receives a webhook, extracts the customer's message, sends it to the OpenAI API, receives a generated response, and sends that response back through the WhatsApp Cloud API.

This is not a setting that you simply switch on inside WhatsApp. You need a Meta app, a registered business number, a webhook, a server, an OpenAI API key, and code that safely connects the services. You should also add business-specific information, a human handover path, opt-out handling, and checks that prevent the AI from inventing prices or policies.

Architecture: how the integration works

  1. A customer sends a message to your WhatsApp business number.
  2. Meta sends a webhook event to your public HTTPS backend.
  3. Your backend validates the event and identifies the sender and message.
  4. Your application checks consent, duplicate events, service-window rules, and whether a human agent is handling the conversation.
  5. The backend sends the relevant customer text and approved business context to the OpenAI API.
  6. The AI generates a customer-support response.
  7. Your backend checks the response and sends it through the WhatsApp Cloud API.
  8. The system stores the message IDs and delivery events so agents can review the conversation.

Step 1: Create an OpenAI API key

Use the OpenAI developer platform to create an API key for your application. API usage and ChatGPT subscription access are separate products; a ChatGPT plan does not automatically include unlimited API usage. Review the current API billing and model documentation before choosing a model.

Create a dedicated key for the application, restrict access where supported, and store it in a server-side secret or environment variable. Do not paste the key into Blogger, frontend JavaScript, a public GitHub repository, or a message to a developer who does not need it. If a key is exposed, revoke it and create a replacement.

Step 2: Create a Node.js backend project

Install a supported Node.js version on your server or development machine. Create a project folder and install Express, the OpenAI SDK, and dotenv. The following commands are a simple starting point; production deployments should use a lockfile, pinned dependency versions, and a controlled deployment process.

mkdir whatsapp-ai-bot
cd whatsapp-ai-bot
npm init -y
npm install express openai dotenv

Depending on your Node.js configuration, you may need to enable ES modules in your package configuration or use the import syntax supported by your project. Use a current, supported runtime and review the official SDK documentation for the latest initialization pattern.

Step 3: Configure environment variables

Create a local environment file for development and add the required values. Do not commit this file to Git. In production, configure secrets through your hosting provider's environment-variable or secrets-management interface.

PORT=3000
VERIFY_TOKEN=choose_a_long_random_webhook_secret
WHATSAPP_TOKEN=YOUR_META_ACCESS_TOKEN
PHONE_NUMBER_ID=YOUR_PHONE_NUMBER_ID
GRAPH_API_VERSION=vXX.X
OPENAI_API_KEY=YOUR_OPENAI_API_KEY
OPENAI_MODEL=YOUR_CURRENT_SUPPORTED_MODEL

Use the Graph API version currently supported by your Meta app. The model name must be a model currently available to your OpenAI API account. Avoid copying an old model identifier from an outdated tutorial. Keeping the model in an environment variable lets you change it without editing the application source code.

Step 4: Create a basic Express webhook and AI reply handler

The following example demonstrates the main connection points: webhook verification, receiving text messages, generating a business-support response, and sending a reply. It is a learning example, not a complete production-ready bot. It intentionally omits several controls discussed after the code, including signature verification, queue processing, persistent deduplication, rate limiting, consent checks, and a full human-agent state system.

import express from "express";
import OpenAI from "openai";
import "dotenv/config";

const app = express();
app.use(express.json());

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY
});

const GRAPH_VERSION = process.env.GRAPH_API_VERSION;
const PHONE_NUMBER_ID = process.env.PHONE_NUMBER_ID;
const WHATSAPP_TOKEN = process.env.WHATSAPP_TOKEN;

app.get("/webhook", (req, res) => {
  const mode = req.query["hub.mode"];
  const token = req.query["hub.verify_token"];
  const challenge = req.query["hub.challenge"];

  if (mode === "subscribe" &&
      token === process.env.VERIFY_TOKEN) {
    return res.status(200).send(challenge);
  }
  return res.sendStatus(403);
});

async function sendWhatsAppText(to, body) {
  const url =
    `https://graph.facebook.com/${GRAPH_VERSION}/` +
    `${PHONE_NUMBER_ID}/messages`;

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${WHATSAPP_TOKEN}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      messaging_product: "whatsapp",
      recipient_type: "individual",
      to,
      type: "text",
      text: { body }
    })
  });

  const data = await response.json();
  if (!response.ok) {
    throw new Error(`WhatsApp API error: ${JSON.stringify(data)}`);
  }
  return data;
}

async function createBusinessReply(customerText) {
  const response = await openai.responses.create({
    model: process.env.OPENAI_MODEL,
    instructions:
      "You are a concise customer-support assistant for a business. " +
      "Answer only using the business information supplied in the prompt. " +
      "If information is missing, say a human team member will help. " +
      "Do not invent prices, stock, delivery dates, refunds or policies. " +
      "Do not request passwords, OTPs or full payment-card details.",
    input: customerText
  });

  return response.output_text?.trim() ||
    "Thanks for your message. Our support team will help you shortly.";
}

app.post("/webhook", async (req, res) => {
  // Acknowledge quickly; production systems should queue the event.
  res.sendStatus(200);

  try {
    const entries = req.body.entry || [];

    for (const entry of entries) {
      for (const change of (entry.changes || [])) {
        const value = change.value || {};
        const messages = value.messages || [];

        for (const message of messages) {
          if (message.type !== "text" || !message.text?.body) {
            continue;
          }

          const sender = message.from;
          const customerText = message.text.body;
          const aiReply = await createBusinessReply(customerText);
          await sendWhatsAppText(sender, aiReply);
        }
      }
    }
  } catch (error) {
    // Send details to a protected server log/monitoring service.
    console.error("Webhook processing failed:", error.message);
  }
});

app.listen(process.env.PORT || 3000, () => {
  console.log("WhatsApp AI webhook server started");
});

Step 5: Understand what the code does

The GET route handles Meta's webhook verification challenge. The POST route receives webhook events. The helper function sends a text message through the Graph API, while the AI helper calls the OpenAI Responses API and returns the generated text. The example loops through entries and changes because webhook payloads can contain multiple items.

The example acknowledges the webhook before completing AI processing so that the request does not remain open while the model is generating a response. However, acknowledging early means a production application must persist or queue the event before returning success. Otherwise, a server crash after acknowledgement could cause the message to be lost. Use a durable queue or database-backed job system for reliable processing.

Step 6: Give the AI accurate business information

A general model does not automatically know your current stock, store timings, shipping rules, return policy, service area, or prices. Supply approved business information through a controlled prompt, retrieval system, or database lookup. For information that changes frequently, retrieve the current value from your own system instead of relying on text written months ago.

For example, a store assistant should know the store's official opening hours, supported delivery areas, and the process for checking an order. If it cannot verify stock or a delivery date, it should say that a team member will confirm it. It should never invent a discount, promise a refund, or claim that an order has shipped without checking the relevant system.

Step 7: Add human handover

Customers should be able to reach a person. Create a clear handover trigger for messages such as “talk to an agent”, complaints, refund disputes, payment problems, medical or legal questions, and any request the AI cannot answer confidently. When handover is active, pause automated replies until the agent closes or returns the conversation to the bot.

Give agents enough context to understand the conversation, but do not expose customer information to people who do not need it. Record who took over and when. If your business operates outside normal hours, explain when a human response can be expected rather than pretending an agent is available.

Step 8: Enforce the 24-hour window and template rules

The sample code sends a free-form text reply and does not check the customer-service window. Do not deploy it as-is. Before sending a free-form reply, your production application must determine whether the customer-service window is open under the current rules. If it is closed, use an approved template where permitted, or wait until the customer messages again. The exact logic should be based on reliable timestamps and current Meta documentation.

Step 9: Production controls you should add

  • Webhook signature verification and strict request validation.
  • Persistent event storage and duplicate-message prevention.
  • A durable queue with retries and dead-letter handling.
  • Rate limits and protection against repeated or abusive requests.
  • Customer consent and opt-out checks before sending messages.
  • Service-window and approved-template enforcement.
  • Human handover, agent assignment, and conversation status.
  • AI output limits, business-grounded answers, and sensitive-topic escalation.
  • Monitoring for API failures, latency, delivery status, and usage cost.
  • Retention rules and access controls for customer conversation data.

Also check the WhatsApp Business Platform policies that apply to AI services. The platform is intended for business messaging and support use cases; it should not be used to distribute a general-purpose AI assistant in a way prohibited by the current policy. Design the bot as a business-specific assistant and review the latest policy before launch.

Step 10: Test before connecting real customers

Test with your own numbers and sample data. Try common questions, misspellings, unsupported requests, a request for a human, an opt-out, duplicate webhook events, and a failed OpenAI request. Confirm that the bot does not send a second reply when Meta retries an event. Test what happens when the Meta API is unavailable or when the AI provider returns an error. A safe fallback message should direct the customer to a human or explain when the team will respond.

13. Can Google AI Studio Provide WhatsApp API?

No. Google AI Studio does not issue WhatsApp Business API access. It is a development environment for experimenting with Google's AI models and generating or testing application code. It can help you write a webhook, create a backend, or prototype a Gemini-powered support assistant, but it cannot replace Meta's business onboarding, WABA, phone-number registration, access token, or webhook configuration.

To connect Gemini to WhatsApp, you still need the WhatsApp Business Platform setup described earlier. Your backend receives the WhatsApp webhook, sends the relevant message to the Gemini API, receives the model response, and sends the reply through the Cloud API. Keep the Gemini API key on the server and apply the same consent, privacy, human handover, and WhatsApp policy controls.

ChatGPT vs Gemini: which should you choose?

Choose based on the model quality for your language and business tasks, API pricing, response speed, tool support, safety controls, data-handling terms, and the reliability of your implementation. Run a small evaluation using real examples with personal information removed. Compare accuracy, refusal behavior, hallucinations, latency, and total cost rather than choosing only by brand name.

Whichever provider you use, the WhatsApp connection remains separate from the AI provider. Meta handles WhatsApp messaging; your backend coordinates the conversation; the AI service generates a response. This separation makes it easier to change AI providers later without rebuilding your WhatsApp onboarding.

14. How to Create a WhatsApp Click-to-Chat Link

A click-to-chat link lets a visitor open a WhatsApp conversation with your business without manually saving the phone number first. It is useful on websites, landing pages, social media profiles, product pages, and email signatures. A standard link uses the international phone number format without spaces, brackets, or the plus sign.

https://wa.me/COUNTRYCODEPHONENUMBER

For an Indian number, use the country code 91 followed by the mobile number. Do not include spaces, hyphens, or a leading plus sign in the number path. Replace the example below with your own business number.

https://wa.me/91XXXXXXXXXX?text=Hello%20I%20need%20more%20details

Adding a pre-filled message

You can add a text query parameter to pre-fill a message. Spaces and special characters should be URL-encoded. The customer still chooses whether to send the message; opening the link does not automatically send it. This is useful because the visitor can review or edit the text before starting the conversation.

Use a clear call to action such as “Chat with our support team” or “Ask about this product”. If the link is for a specific product, you can pre-fill the product name or reference number, but avoid placing confidential information in the URL.

Remember that a click-to-chat link is not the same as WhatsApp Business API. It opens a conversation in WhatsApp. API automation, CRM synchronization, templates, and webhooks require the separate platform integration.

15. Can You Automate Outbound Voice Calls with WhatsApp API?

WhatsApp messaging endpoints do not automatically place voice calls. Meta has a separate Business Calling API for eligible business use cases. Access, supported markets, account eligibility, customer permission, and calling rules are different from ordinary messaging rules. Do not assume that an account with messaging access can immediately make automated calls.

Customer permission is an important part of the calling experience. Review the current Business Calling documentation for the required opt-in flow, supported countries, account thresholds, and restrictions. The supporting research noted country limitations and a messaging-limit threshold reproduced by providers, but those details should be rechecked against Meta's live documentation before you rely on them.

If your goal is to send an appointment reminder or order update, a compliant message template may be more appropriate than a voice call. If calling is genuinely necessary, design the experience around clear consent, reasonable frequency, identification of the business, and a simple way for the customer to decline further calls.

16. Security, Privacy, and Compliance: How to Keep the API Safe

A WhatsApp integration handles customer contact details and conversation content. It should be treated as a business system that needs access control, secure storage, monitoring, and a documented data-handling process. A working API connection is not enough if credentials are exposed or customer information is accessible to everyone in the organization.

Protect access tokens and API keys

  • Store Meta tokens and AI-provider keys on the server, never in browser code.
  • Use environment variables or a secrets manager with restricted access.
  • Do not commit environment files or credentials to public repositories.
  • Rotate credentials according to your security process and revoke exposed keys immediately.
  • Use separate credentials for development, staging, and production.
  • Give developers and staff only the permissions they need.

Protect customer data

Collect only the information required for the service. Explain how customers can contact your business and how their information will be used. Limit access to conversation history, use secure transport, protect database backups, and define a retention period. Avoid storing sensitive information in logs when it is not necessary for troubleshooting.

Do not ask customers to send passwords, one-time passcodes, full payment-card details, or other secrets through a chat assistant. If a transaction requires sensitive verification, direct the customer to a secure, approved flow. Make sure your privacy notice and business practices comply with the laws that apply to your organization and customers.

AI safety rules

Constrain the assistant to the business information it is authorized to use. Do not allow it to invent product availability, prices, medical advice, refunds, delivery dates, or legal commitments. Escalate uncertain or high-impact questions to a trained person. Make it clear when a customer is interacting with an automated assistant if that is appropriate for your service and legal obligations.

17. Common WhatsApp API Errors and Their Solutions

Most setup problems come from credentials, permissions, identifiers, webhook configuration, templates, or number registration. Read the complete error response and check the relevant dashboard rather than changing several settings at once. Keep a record of the exact request time, endpoint, API version, and error code, but remove tokens and personal customer information from any support logs you share.

Webhook returns HTTP 200, but the bot does not reply

An HTTP 200 response only confirms that your endpoint acknowledged the webhook request. It does not prove that your application extracted the message, called the AI provider, or sent a WhatsApp reply. Check the server logs at each stage: event received, message extracted, AI request completed, outgoing message request sent, and API response received. Use a correlation ID or message ID to connect the stages.

The token appears correct, but permission is denied

A token can be valid but still lack access to the required asset or action. Confirm that the app is associated with the correct Business Portfolio, that the system user has access to the WABA and phone number, and that the token includes the permissions required by the current API flow. Recheck the app mode and any access-review requirements that apply to the account.

A message template is rejected

Read the rejection reason and compare the template with the current category and content rules. Check whether the template contains promotional content that does not match its category, unclear variable placeholders, misleading wording, or prohibited content. Edit the actual issue and resubmit. Do not repeatedly submit the same rejected template without changes.

18. WhatsApp Business API Best Practices

  • Start with one clear use case. Begin with order updates, appointment reminders, or customer support rather than trying to automate every process at once.
  • Use a consent-based contact strategy. Keep records of how customers agreed to receive messages and honor opt-outs promptly.
  • Keep templates useful and accurate. Match the category to the message purpose and avoid misleading wording.
  • Build a human support route. Customers need a way to reach a person when automation is not enough.
  • Protect your credentials. Keep tokens and AI keys on the backend and restrict access.
  • Make webhook processing reliable. Use a queue, retries, idempotency, and monitoring.
  • Track message quality and cost. Monitor delivery, failed messages, complaints, category mix, and monthly spend.
  • Keep customer data organized. Connect conversations to CRM records without collecting unnecessary information.
  • Review policy changes. Revisit Meta's documentation and rate card periodically.
  • Test before scaling. Use a small controlled rollout and fix issues before increasing volume.

Good automation should make customer service faster and clearer, not make it harder for customers to get help. Keep messages relevant, avoid excessive follow-ups, and make sure every automated workflow has an owner who can investigate problems.

19. Final Launch Checklist

Use this checklist before connecting the integration to real customers:

  • Meta Business Portfolio is correctly configured and controlled by the business.
  • Meta developer app has the WhatsApp product configured.
  • Production WABA and phone number are correctly connected.
  • Phone Number ID and WABA ID have been checked.
  • Production token is configured securely and has the required permissions.
  • Webhook uses HTTPS and passes verification.
  • Webhook signature validation is implemented.
  • Incoming events are stored or queued before acknowledgement.
  • Duplicate events cannot trigger duplicate replies.
  • Templates are approved and correctly categorized.
  • Customer opt-in and opt-out processes are working.
  • Service-window rules are enforced.
  • CRM contact matching and agent assignment have been tested.
  • Human handover works and pauses bot replies when needed.
  • AI answers are grounded in approved business information.
  • Monitoring, backups, error alerts, and cost tracking are enabled.
  • Privacy notice and internal access policies have been reviewed.
  • Current Meta pricing and applicable taxes have been verified.

20. Frequently Asked Questions (FAQs)

Conclusion: Is WhatsApp Business API Right for Your Business?

WhatsApp Business API can turn a business phone number into part of a connected customer-service and sales system. It can help you connect conversations with a CRM, automate order updates, manage multiple agents, and build a business-specific AI support assistant. The biggest benefits appear when messaging is connected to a real process and the business has enough conversation volume to justify the setup and ongoing costs.

If you are just starting and receive a small number of messages, begin with the regular WhatsApp Business App. If you need automation or software integration, test the Cloud API with Meta's development number first. Then connect your production number, configure a secure webhook, create approved templates, and launch gradually. Verify the current pricing and policies before you budget or send messages at scale.

The most important principle is to build a reliable and customer-friendly system. Protect credentials, collect appropriate consent, keep AI answers grounded in verified business information, and make human support available whenever automation reaches its limits.

Official Resources and Further Reading

Post a Comment

0 Comments