Developer Guides

How to Use Webhooks with WhatsApp

Exposing a public HTTPS endpoint and handling payload responses requires systematic implementation. Connecting system callbacks allows your app to capture customer events instantly. Follow this step-by-step developer setup guide.

Nov 15, 2025 11 min read By Waplix Team
Share:
How to Use Webhooks with WhatsApp

Deploy production-ready WhatsApp webhooks with Waplix

Connecting your app to WhatsApp goes beyond sending message payloads. A reliable integration must respond to incoming customer messages, process interactive quick-replies, and log delivery statuses in real-time. Webhooks make this event-driven flow possible by pushing updates directly to your servers.

Setting up your webhook endpoint requires configuring a public HTTPS listener, implementing a GET verification handshake, parsing POST payloads, and validating message authenticity. Without these elements, your system may experience timeouts, duplicate message calls, or security vulnerabilities.

This step-by-step guide explains how to build a webhook listener, test it locally, deploy it to production, and secure it against unauthorized requests.

Overview: Webhooks let your server process events like incoming messages and status logs instantly, removing the latency of polling models.

Receive pre-parsed JSON payloads, configure retry logic, and inspect webhook logs from our developer dashboard.

Create your free developer account See Waplix features

What is a WhatsApp webhook callback?

A webhook is a user-defined HTTP callback. When an event occurs—such as a user sending an image, a message status changing to "read", or a delivery failing—the API provider sends an HTTP POST request containing a JSON payload to your registered listener URL.

This pattern shifts your app architecture from a polling model to a push model, conserving resources and ensuring near-zero latency for incoming responses.

  • Server Load
  • Integration StepManual Polling RouteWebhooks Ingress RouteDeveloper Advantage
    Endpoint RequirementsNone. Runs outbound client tasks only.Requires public HTTPS endpoint listener.Enables inbound interactivity
    Validation ProtocolSimple authentication token in header.GET handshake verification query parse.Secures connection endpoints
    Payload FormatsFlat GET response schemas.Nested JSON event objects.Provides detailed event context
    Continuous connection overhead.Event-driven, temporary connections.Optimizes infrastructure usage

    By connecting systems, you can trigger specific messages based on customer behavior—such as confirming a booking, following up on a delivery, or recovering an abandoned shopping cart.

    Core event types tracked via webhooks

    Your webhook listener must inspect the event header to parse and route payloads to the correct handlers.

    1. Inbound messages (`messages.receive`)

    Fires when a customer sends a text, image, document, location, or contact card. Your application uses this event to capture input, trigger AI responses, or route chats to agent queues.

    2. Message status updates (`messages.status`)

    Tracks the lifecycle of outbound messages. Events update status values from `sent` to `delivered`, `read`, or `failed` in real-time, providing visibility into customer engagement.

    3. Template quality changes

    Meta monitors template rejection and block rates. Webhook alerts notify your team if a template's quality rating drops, helping you adjust content before blocks occur.

    4. Account billing events

    Alerts notify you when your conversation quota limits are reached or card transactions fail, helping you maintain service continuity.

    Key Takeaway

    Process status updates (sent/delivered/read) asynchronously in a queue. High-volume delivery reports can bottleneck your main request loop if processed synchronously.

    Step-by-step webhook implementation

    Configuring a webhook listener requires setting up validation, parsing payloads, and handling retries. Follow this implementation guide.

    01

    Expose a public HTTPS URL

    Set up an endpoint on your server. Use tools like local tunnels during development to expose your local port via HTTPS.

    02

    Implement the validation GET handshake

    Write a GET endpoint to verify Meta's token verification challenge, returning the challenge string in plain text.

    03

    Handle inbound HTTP POST events

    Configure a POST route to accept JSON payloads, return an immediate 200 OK, and hand off processing to a background worker.

    04

    Parse payload data

    Extract fields like sender ID, message text, media file IDs, and delivery timestamps from incoming payloads.

    05

    Verify signature headers

    Validate the SHA256 signature in the request headers against your webhook secret to confirm the payload's authenticity.

    06

    Manage retry logic

    Ensure your listener returns a 200 OK within 3 seconds. Unresolved alerts will trigger automated retry loops from the gateway.

    Developer Tip: Queue incoming webhooks instantly to a message broker (e.g. Redis, RabbitMQ) and acknowledge receipt with a 200 OK immediately. Do not perform long-running processes inside the webhook thread.

    Webhook event ingestion pipeline

    A robust listener separates webhook ingestion from payload processing. This diagram outlines the workflow from event trigger to application database updates.

    Events trigger callbacks from Meta. The listener validates the header signatures, queues the payload in Redis, and returns an immediate response. Background workers then process the data, handle database updates, and update CRM records.

    Technical data flow and architecture

    Real-time updates require clean sync between Meta servers, the Waplix gateway, and your backend databases.

    When an event occurs, Meta triggers the Waplix backend. Waplix processes the payload, maps fields to standard structures, signs the headers, and sends the payload to your registered listener URL.

    Developer Integration: Node.js and Python webhook examples

    These examples show how to configure webhook validation and parse incoming JSON payloads using common backend frameworks.

    1. Node.js Express setup

    Write an Express route that validates the handshake GET request and processes POST payloads.

    const express = require('express');
    const crypto = require('crypto');
    const app = express();
    
    app.use(express.json());
    
    const WEBHOOK_SECRET = process.env.WAPLIX_WEBHOOK_SECRET;
    
    // 1. GET Handshake Verification (Runs once during setup)
    app.get('/webhooks/whatsapp', (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 === 'my_verify_token_123') {
        return res.status(200).send(challenge);
      }
      return res.sendStatus(403);
    });
    
    // 2. POST Event Handler (Fires for incoming messages/updates)
    app.post('/webhooks/whatsapp', (req, res) => {
      // Validate signature header
      const signature = req.headers['x-waplix-signature'];
      const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
      const digest = hmac.update(JSON.stringify(req.body)).digest('hex');
    
      if (signature !== digest) {
        return res.sendStatus(401); // Unauthorized payload
      }
    
      // Acknowledge receipt immediately to avoid timeouts
      res.sendStatus(200);
    
      // Hand off payload to background queue
      processPayloadAsync(req.body);
    });

    2. Python Flask setup

    A similar setup using Python Flask to process incoming message payloads.

    import hmac
    import hashlib
    import os
    from flask import Flask, request, jsonify
    
    app = Flask(__name__)
    
    WEBHOOK_SECRET = os.environ.get("WAPLIX_WEBHOOK_SECRET")
    
    @app.route("/webhooks/whatsapp", methods=["GET"])
    def verify_webhook():
        mode = request.args.get("hub.mode")
        token = request.args.get("hub.verify_token")
        challenge = request.args.get("hub.challenge")
    
        if mode == "subscribe" and token == "my_verify_token_123":
            return challenge, 200
        return "Forbidden", 403
    
    @app.route("/webhooks/whatsapp", methods=["POST"])
    def handle_webhook():
        signature = request.headers.get("X-Waplix-Signature")
        payload = request.data
        
        # Verify signature signature
        expected_sig = hmac.new(WEBHOOK_SECRET.encode(), payload, hashlib.sha256).hexdigest()
        if signature != expected_sig:
            return "Unauthorized", 401
            
        # Return 200 OK immediately
        return "OK", 200
    Developer Security Note: Always store your API keys securely in your environment variables. Validate incoming webhook signatures server-side to ensure payloads originate from Waplix.

    For more detailed code samples, visit the API documentation and review our webhook documentation.

    Compliance, policies, and opt-out workflows

    Operating a customer support desk on WhatsApp requires strict adherence to Meta's messaging policies and local data privacy laws.

    • Opt-in verification. Businesses must secure explicit consent before sending outbound transactional alerts or ticket updates to customers.
    • The 24-hour service window. Free-form messages can be sent within a 24-hour service window opened by a user's message. Messages sent outside this window must use pre-approved templates.
    • Opt-out controls. Include clear opt-out options (such as quick-reply buttons like "STOP") in your templates to make unsubscribing easy and protect your quality rating.
    • Follow local privacy laws. Ensure compliance with GDPR, TCPA, and other relevant regional regulations.
    Compliance Note: This guide provides operational advice, not legal counsel. Regulations vary by country and region. Always consult qualified legal advisors to ensure your messaging strategies comply with local laws.

    How Waplix simplifies webhook management

    Meta's raw webhook architecture requires managing complex JSON arrays, parsing nested user profile objects, and handling signature verifications. Waplix parses Meta's payload structures and sends clear, simplified JSON events directly to your server.

    Waplix Webhook Settings Screen Screenshot Placeholder

    Replace this with a real Waplix screenshot showing webhook endpoint URLs, verify tokens, and event subscriptions.

    Suggested screenshot: Configuring webhook URLs and subscribing to specific messaging events in Waplix.
    Webhook Real-Time Logs Console Screenshot Placeholder

    Replace this with a real Waplix screenshot showing API logs, webhook payloads, HTTP status responses, and request headers.

    Suggested screenshot: The Waplix webhook debugger console, showing real-time dispatch payloads and statuses.

    Common integration mistakes

    • Synchronous processing. Running heavy backend tasks (e.g. database updates) inside the webhook thread leads to timeout failures.
    • Skipping signature checks. Neglecting validation allows unauthorized parties to send fake payloads to your endpoint.
    • Incorrect HTTP status codes. Returning 500 errors or non-200 responses for successfully parsed payloads triggers retry loops.
    • Neglecting idempotency. Not tracking message IDs can lead to duplicate entries if Meta retries delivery.
    • Ignoring failure webhooks. Not logging message delivery failures (like invalid numbers) makes tracking logs inaccurate.

    Best practices for webhook listeners

    Queue all payloads

    Acknowledge receipt with an immediate 200 OK response and process payload contents asynchronously using a queue.

    Verify headers

    Validate the request signature against your endpoint's secret token to ensure the payload originates from a trusted provider.

    Implement idempotency

    Store incoming message IDs in a temporary cache (e.g. Redis) to filter duplicate event triggers.

    Monitor delivery stats

    Analyze callback durations, verify HTTP codes, and track timeout alerts to optimize server resources.

    Conclusion and next steps

    Webhooks are essential for building responsive, real-time messaging applications on WhatsApp. Designing secure, asynchronous listeners ensures your system handles traffic spikes reliably while keeping databases synchronized.

    Expose a public HTTPS URL, implement signature checks, queue incoming payloads, and test your setup using local tunnels to build a secure integration foundation.

    Build secure WhatsApp integrations with Waplix

    Create a developer account, connect your business number, and automate customer support at scale.

    Create your free account Contact our sales team

    Related Guides & Insights

    AI Appointment Booking on WhatsApp
    AI Agents

    AI Appointment Booking on WhatsApp

    Learn how to build AI-driven booking systems on WhatsApp, connecting calendar databases to conversational agents, automating updates, and reducing client no-shows.

    Read Article
    AI Automation for Small Businesses
    AI Agents

    AI Automation for Small Businesses

    Discover practical ways small businesses can leverage no-code AI automation on WhatsApp to manage customer conversations, qualify prospects, and coordinate bookings 24/7.

    Read Article
    AI Memory in Customer Support
    AI Agents

    AI Memory in Customer Support

    Explore the technology behind AI memory and context retention, learning how session databases personalization results in better, trust-filled client interactions.

    Read Article