Get your dream built 10x faster

How to integrate WhatsApp Business with OpenClaw

We build custom applications 5x faster and cheaper 🚀

Book a Free Consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Stuck on an error? Book a 30-minute call with an engineer and get a direct fix + next steps. No pressure, no commitment.

How to integrate WhatsApp Business with OpenClaw

Integrate WhatsApp Business with OpenClaw by treating WhatsApp as an external service: register and configure the WhatsApp Business API (Cloud or on-prem), implement a secure webhook receiver that validates WhatsApp/Meta signatures and forwards normalized events to the OpenClaw skill (installed/configured in ClawHub) via an authenticated HTTP call, and send outbound messages by calling WhatsApp’s API from a trusted external service (not from inside the ephemeral agent runtime). Keep secrets in a secret store, run retries/queues and media storage outside the agent, and debug by inspecting webhook signatures, API responses, token scopes/expiry, and ClawHub/skill invocation logs.

 

Planning and high-level flow

 
  • WhatsApp Business API (Cloud or on-prem) is the source of incoming messages and the destination for outbound sends; it uses webhooks for inbound events and REST endpoints for sending messages.
  • OpenClaw skills are installed and configured explicitly in ClawHub; the agent runtime should receive normalized, authenticated events that map to installed skills (or a small proxy that routes to a skill).
  • Mediator service (recommended): a small external HTTP service that validates WhatsApp webhooks, enriches/normalizes messages, handles retries, stores transient state if needed, and forwards events into OpenClaw (via a secure inbound URL or API). This service also performs outbound calls to WhatsApp.
  • State and persistence (outside agent): conversation history, media blobs, job queues, rate-limiting counters and OAuth refresh tokens should live in an external DB or key vault — not in ephemeral agent memory.

 

Concrete components you must implement

 
  • WhatsApp setup: get a WhatsApp Business account (Cloud API or on-prem), obtain the phone_number_id and an access token (or OAuth client credentials if using a longer flow), and subscribe to webhooks. For Cloud API you use a long-lived token or app-managed tokens; verify the token lifetime and refresh pattern provided by Meta.
  • Secure webhook receiver: an HTTPS endpoint that validates the webhook signature (Meta uses HMAC SHA256 headers), parses events, and converts WhatsApp event shapes into a stable internal payload format that your OpenClaw skill expects.
  • Skill invocation: an authenticated POST from your mediator to the OpenClaw skill endpoint or to whatever mechanism ClawHub documents for delivering external events to a skill. Use a dedicated API key or OAuth credential for that call and keep it in a secret store.
  • Outbound sending: the mediator calls WhatsApp’s HTTP API to send template or session messages. Template (pre-approved) for user-initiated notifications outside a session; session (freeform) for replies within the 24-hour window — follow WhatsApp rules.
  • Error handling & retries: queue failed inbound events and outgoing sends, implement exponential backoff, and persist events to allow reprocessing after restarts.

 

Webhook verification (example)

 
  • This Node.js/Express example shows how to validate the Meta HMAC signature (Cloud API uses x-hub-signature-256), normalize the payload, and forward it to a configured skill endpoint. Replace environment variables for your setup.
const express = require('express')
const crypto = require('crypto')
const fetch = require('node-fetch')

const app = express()

app.use(express.json({
  verify: (req, res, buf) => {
    req.rawBody = buf
  }
}))

app.post('/whatsapp-webhook', async (req, res) => {
  const signatureHeader = req.get('x-hub-signature-256') || ''
  const appSecret = process.env.META_APP_SECRET // <b>//</b> set in your secrets manager
  const expected = 'sha256=' + crypto.createHmac('sha256', appSecret).update(req.rawBody).digest('hex')

  try {
    // timingSafeEqual requires Buffers of same length
    const sigBuf = Buffer.from(signatureHeader)
    const expBuf = Buffer.from(expected)
    if (sigBuf.length !== expBuf.length || !crypto.timingSafeEqual(sigBuf, expBuf)) {
      return res.status(401).send('invalid signature')
    }
  } catch (err) {
    return res.status(401).send('invalid signature')
  }

  const body = req.body

  // Normalize incoming message to a stable shape your OpenClaw skill expects
  const normalizedEvents = []
  if (Array.isArray(body.entry)) {
    for (const entry of body.entry) {
      if (!entry.changes) continue
      for (const change of entry.changes) {
        const value = change.value
        // value.messages is common for incoming messages
        if (value.messages) {
          for (const msg of value.messages) {
            normalizedEvents.push({
              source: 'whatsapp',
              phone_number_id: value.metadata?.phone_number_id,
              from: msg.from,
              id: msg.id,
              timestamp: msg.timestamp,
              type: msg.type,
              message: msg
            })
          }
        }
        // handle statuses, message_deliveries, etc., as needed
      }
    }
  }

  // Forward to OpenClaw skill endpoint (configure SKILL_ENDPOINT and SKILL_TOKEN)
  if (normalizedEvents.length > 0) {
    try {
      await fetch(process.env.SKILL_ENDPOINT, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.SKILL_TOKEN}`
        },
        body: JSON.stringify({ events: normalizedEvents })
      })
    } catch (err) {
      // <b>//</b> store the event and error to retry later
      console.error('forward to skill failed', err)
      return res.status(202).send('accepted') // accept but ensure retry in your queue
    }
  }

  res.status(200).send('ok')
})

app.listen(3000)

 

Sending messages to WhatsApp (example)

 
  • Use the Graph API endpoint (Cloud) of the form https://graph.facebook.com/v{version}/{PHONE_NUMBER_ID}/messages with Authorization: Bearer <ACCESS\_TOKEN>.
const sendWhatsAppText = async ({ phoneNumberId, to, text, accessToken }) => {
  const url = `https://graph.facebook.com/v17.0/${phoneNumberId}/messages`
  const payload = {
    messaging_product: 'whatsapp',
    to: to,
    type: 'text',
    text: { body: text }
  }
  const res = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify(payload)
  })
  const data = await res.json()
  if (!res.ok) {
    // <b>//</b> handle error codes and rate limiting (inspect data.error)
    throw new Error(`WhatsApp send failed: ${JSON.stringify(data)}`)
  }
  return data
}

 

How OpenClaw fits in (vendor-neutral, correct boundaries)

 
  • Install skills explicitly via ClawHub: add or enable the skill that will handle WhatsApp events. Provide the skill with the required configuration values (e.g., a route or credential) using ClawHub’s configuration UI or secret mechanisms.
  • Event delivery: deliver inbound WhatsApp events to the skill by making an authenticated HTTP request to the skill's inbound endpoint. The agent runtime runs the skill logic; do not assume the agent persists long-term state.
  • External responsibilities: run web servers, scheduled jobs, queues and any durable storage outside the agent. Use the mediator service to bridge WhatsApp and OpenClaw.
  • Authentication and scopes: use appropriate tokens (WhatsApp access token, skill API key/OAuth token). Ensure tokens are stored in a secrets manager and that scopes/permissions are minimal.

 

Operational concerns and best practices

 
  • Secrets and credentials: store Meta/WhatsApp access tokens, App secret, and skill tokens in a secrets manager or environment variables injected by your deployment system; rotate tokens per vendor guidance.
  • Webhook verification: always validate signatures; reject webhooks that don’t verify.
  • Idempotency: deduplicate messages by message ID from WhatsApp before invoking the skill (WhatsApp may retry delivery).
  • Rate limits: implement rate limiting and backoff for outbound sends; handle 4xx/5xx responses and specific errors like template not approved, phone number blocked, etc.
  • Media handling: download media from WhatsApp’s media URL (requires Authorization header) and store it in your durable storage; don’t embed large blobs inside skill calls unless small.
  • Templates and 24-hour window: implement flow control that uses approved message templates for notifications outside the user session window, and freeform messages for replies within the messaging window.
  • Monitoring: log raw webhook payloads (redact secrets), track failed forwards to skills, instrument message queues, and surface metrics for throughput and errors.

 

Debugging checklist

 
  • Confirm webhook calls from WhatsApp reach your mediator (check web server access logs and response codes).
  • Verify webhook signature and app secret correct; if signature mismatch, the webhook should be rejected (401).
  • Inspect incoming webhook JSON for expected fields (message ids, from, timestamp).
  • Check that normalized events are sent to the correct OpenClaw skill endpoint, using the right Authorization header and token; record request/response bodies and HTTP status codes.
  • If outbound sends fail, inspect WhatsApp error structure (data.error) for details: authentication, template approval, rate limits, or blocked numbers.
  • Confirm tokens are not expired and that scopes are sufficient for sending messages and reading media; refresh or reissue tokens as required.
  • Use retries and a durable queue when transient failures occur; reprocess failed messages after fixing issues.

 

Security checklist

 
  • Terminate TLS on webhook/mediator endpoints.
  • Validate webhook signatures.
  • Use least-privilege credentials and rotate them regularly.
  • Store tokens in a vault; don’t commit them to repo or logs.
  • Rate-limit inbound requests and enforce payload size limits.

Book Your Free 30‑Minute Migration Call

Speak one‑on‑one with a senior engineer about your no‑code app, migration goals, and budget. In just half an hour you’ll leave with clear, actionable next steps—no strings attached.

Book a Free Consultation

Troubleshooting WhatsApp Business and OpenClaw Integration

1

WhatsApp Connector auth errors

 

Quick answer

 

Most WhatsApp Connector auth errors come from bad tokens, expired/rotated credentials, missing environment variables in the OpenClaw agent runtime, or failing webhook signature validation. Fix by confirming the access token, app secret, phone_number_id, and that the skill in ClawHub uses the correct env vars and permissions.

 

Debug checklist

 
  • Verify token: call WhatsApp API with the token from your runtime; watch HTTP 401 vs 403 responses.
  • Check expiry/rotation: refresh long‑lived tokens or reissue if revoked.
  • Env vars: ensure ClawHub/agent runtime loads keys (no local-only files).
  • Webhook sig: validate X-Hub-Signature-256 using app secret (HMAC SHA256).
  • Permissions: confirm WhatsApp business app scopes and phone_number_id match requests.
  • Logs: inspect skill logs and API responses for exact error fields and HTTP codes.

2

Ingestor webhook config

Direct answer: Configure the Ingestor webhook as an HTTPS endpoint that authenticates and validates incoming payloads (HMAC/shared secret), stores credentials in environment variables, responds quickly with a 2xx status to acknowledge receipt, offloads processing to a background worker for OpenClaw skill invocation, and exposes logs/metrics and retry/idempotency controls.

 

Webhook config checklist

 

Essentials:

  • HTTPS endpoint and secret in env var.
  • Signature verification (HMAC) and JSON schema validation.
  • Fast ack (202/200) and enqueue work for agents/skills.
  • Idempotency, retries, logs, and metrics.
  • Map payload to skill inputs and ensure permissions in ClawHub.
const crypto=require('crypto'),express=require('express');
const app=express();app.use(express.json());
app.post('/webhook',(req,res)=>{
  //<b>// validate HMAC</b>
  const sig=req.headers['x-signature']||'';
  const exp='sha256='+crypto.createHmac('sha256',process.env.INGESTOR_SECRET).update(JSON.stringify(req.body)).digest('hex');
  if(!crypto.timingSafeEqual(Buffer.from(sig),Buffer.from(exp)))return res.sendStatus(401);
  //<b>// enqueue and ack</b>
  enqueueJob(req.body);
  res.sendStatus(202);
});

3

Template sync failure

Direct answer: A sync failure typically indicates auth, webhook, or network/API errors between your OpenClaw agent/skill and the external service. Triage by checking agent runtime logs, validating env vars/OAuth tokens, replaying the failing HTTP request, and moving retry/stateful logic outside the agent if needed.

 

Debug checklist

 
  • Inspect logs and skill traces for HTTP status and error bodies.
  • Verify credentials (env vars, API keys, OAuth refresh flow).
  • Validate webhooks (signatures, timestamps).
  • Replay requests with curl or a test worker; add idempotency and retries.
  • Offload stateful retries to an external service or queue for reliability.
// validate env
if (!process.env.API_KEY) throw new Error('Missing API_KEY');
console.log('env OK');

4

Channel rules routing

Short answer: verify the skill's environment variables and credentials, confirm the ClawHub skill configuration and permission scopes, reproduce failing API calls from logs, and move stateful or scale-sensitive pieces outside the agent runtime if needed.

 

Practical checklist

 
  • Env & creds: check API keys, OAuth tokens, and secret env vars before skill execution.
  • Logs & API: inspect runtime logs, HTTP responses, and error bodies to pinpoint auth or schema mismatches.
  • Permissions: validate token scopes and skill permissions in ClawHub.
  • Webhooks: verify signatures and replay events.
  • Scale/state: host DBs/queues outside agents for reliability.
Book a Free Consultation

Still stuck?
Copy this prompt into ChatGPT and get a clear, personalized explanation.

This prompt helps an AI assistant understand your setup and guide you through the fix step by step, without assuming technical knowledge.

AI AI Prompt


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â