Create one working vertical slice: a customer sends a WhatsApp message, your service verifies and processes the webhook, an interchangeable model drafts a grounded answer, and the reply returns through Meta. Then add memory, one safe business tool, and explicit production gates.
This guide does not promise a production system from one prompt. Production readiness requires business verification, policy compliance, security review, failure handling, monitoring, load testing, and an accountable human escalation path.
1. Define the narrow job
Choose one outcome, such as answering approved product questions and checking an order status. Write:
| Decision | Your rule |
|---|---|
| Users | Who may message the number |
| Allowed answers | Which approved knowledge sources may be used |
| Tool action | One read-only action for the first release |
| Escalation | When and how a human takes over |
| Retention | What is stored, why, and for how long |
| Refusal | Requests the agent must decline or hand off |
Do not begin with purchases, refunds, account changes, or other irreversible actions. The first success criterion is a reliable, auditable conversation, not maximum automation.
2. Map the system before code
Customer → WhatsApp → Meta Cloud API → HTTPS webhook
↓
validation → queue → worker
↓
policy + knowledge + memory → model adapter
↓
approved tools → response policy
↓
Meta messages endpoint → CustomerSeparate transport, orchestration, model access, memory, knowledge, tools, and observability. This lets you swap a model provider without rewriting WhatsApp handling.
Use a database for durable conversation state and a queue for background processing. In-memory history disappears on restart and breaks across multiple instances.
3. Set up Meta safely
Create a Meta app with WhatsApp, connect the correct business portfolio and WhatsApp Business Account, and start with Meta's test number. Cloud API commonly uses whatsapp_business_messaging; management workflows may also require whatsapp_business_management. Confirm the exact permissions for your ownership and onboarding model in current Meta documentation.
Keep placeholders only:
META_GRAPH_VERSION=vXX.X
WHATSAPP_PHONE_NUMBER_ID=<phone-number-id>
WHATSAPP_ACCESS_TOKEN=<secret-reference>
WHATSAPP_APP_SECRET=<secret-reference>
WHATSAPP_VERIFY_TOKEN=<random-verification-value>Never commit tokens. Development dashboard tokens can expire. For production, use an appropriate system-user or supported business integration flow, least privilege, rotation, revocation, and a secret manager. Pin a reviewed Graph API version and track its retirement date instead of silently using a moving default.
4. Build the webhook boundary
Meta verifies your callback with a GET challenge. Your endpoint should compare the supplied verify token and return hub.challenge only on a match.
For POST events, preserve the raw request body and verify X-Hub-Signature-256 with the app secret using constant-time comparison. Reject invalid signatures. Parse defensively because one payload can contain status events, messages, or unsupported message types.
Acknowledge valid events quickly, then process them asynchronously. Meta can redeliver webhooks. Store the Meta message ID as an idempotency key and ignore duplicates. A deduplication record needs an expiry policy, not permanent storage.
5. Respect messaging rules
Inside the 24-hour customer service window after a user's message, a business may send free-form replies under WhatsApp policy. Outside that window, business-initiated messages require an approved template and appropriate user opt-in. Automation must provide a clear, prompt human escalation path.
Store the last inbound-user timestamp and classify every outbound message before sending. Do not let the model choose whether a template is required. Treat template name, language, variables, consent basis, and purpose as validated application data.
6. Add a provider-neutral model adapter
Define one internal interface such as generate(messages, tools, policy). Put provider URL, model ID, timeouts, and limits in configuration. OpenRouter offers an OpenAI-compatible endpoint and model routing, but it is one option, not an architectural dependency.
Review provider retention and routing before sending customer content. OpenRouter exposes provider controls including data-collection restrictions and Zero Data Retention routing where supported. Verify the chosen model and endpoint meet your requirements. Minimize payloads, redact unnecessary identifiers, cap context, and log model IDs and usage without logging message bodies by default.
Retry only transient failures with capped exponential backoff and jitter. Do not retry validation, authentication, or policy errors blindly. A fallback model may differ in cost, behavior, privacy, or tool support, so approve fallbacks explicitly.
7. Design memory and tools
Key memory by a pseudonymous conversation identifier rather than using a phone number throughout the system. Store only the recent messages or structured facts needed for the task. Add expiry, deletion, access controls, encryption appropriate to your environment, and a documented data map.
Treat model tool calls as untrusted proposals. Validate tool name, schema, authorization, tenant, and business rules in code. For write actions, require confirmation and an idempotency key. Never claim an order, booking, refund, or availability result without a successful tool response.
8. Use the NEXAIUM master prompt
Paste this into Claude Code from an empty project. Keep it in plan mode until you approve the architecture.
You are helping me build a secure, production-aware WhatsApp AI agent. Work in two gates: PLAN, then IMPLEMENT only after I approve the plan.
BUSINESS CONTRACT
Business: [BUSINESS]
Agent job: [ONE NARROW OUTCOME]
Approved knowledge: [SOURCES]
First tool: [READ-ONLY TOOL OR NONE]
Human escalation: [PATH]
Supported message types: [TEXT ONLY FOR FIRST SLICE]
Retention rule: [DURATION AND DELETION]
Hosting constraints: [RUNTIME, DATABASE, QUEUE, REGION]
REQUIRED ARCHITECTURE
Use Meta WhatsApp Cloud API directly through a version-pinned Graph API. Separate modules for webhook transport, orchestration, policy, knowledge, model adapter, memory, tools, outbound messaging, and observability. Make the model provider configurable. OpenRouter may be the first adapter, but business logic must not depend on it. Use durable storage and asynchronous processing. Never hardcode secrets or real identifiers.
SECURITY AND POLICY
Implement GET webhook verification. For POST requests, verify X-Hub-Signature-256 against the raw body with constant-time comparison. Validate payloads and reject oversized or malformed input. Deduplicate by Meta message ID. Enforce rate limits and tenant boundaries. Minimize personal data, define retention and deletion, redact logs, and provide a human escalation path. Application code, not the model, must enforce the 24-hour customer service window and approved-template requirement.
MEMORY AND TOOLS
Use a pseudonymous conversation key. Store bounded recent context plus only necessary structured facts, with expiry. Treat model output and tool calls as untrusted. Allowlist tools and validate every argument. The first release must use no irreversible tool action. Never invent business facts or claim tool success without a successful response.
RELIABILITY
Acknowledge valid webhooks quickly and process jobs asynchronously. Add capped retries with exponential backoff and jitter for transient failures only. Use idempotency for inbound events, outbound sends, and tool calls. Add timeouts, circuit-breaking or failure isolation, dead-letter handling, graceful degradation, health and readiness endpoints, and structured redacted logs. Preserve correlation IDs across webhook, model, tool, and outbound calls.
PLAN GATE
Before coding, return: assumptions and open questions; component and data-flow diagram; threat model; data map; message-window state machine; failure and retry table; database schema; API contracts; deployment plan; test plan; monitoring and rollback plan; and exact credentials or Meta configuration I must supply. Flag every claim that needs current official documentation. Do not request or display real secrets.
IMPLEMENTATION GATE
After approval, create complete code, migrations, tests, .env.example with placeholders, README, SECURITY.md, DATA-MAP.md, RUNBOOK.md, and deployment configuration. Keep business knowledge and prompts editable outside application logic. Add unit, integration, contract, replay, and end-to-end tests using fixtures with fictional data.
ACCEPTANCE TESTS
Prove: valid verification succeeds; invalid signatures fail; duplicate message IDs cause one effect; webhook acknowledgement does not wait for the model; unsupported messages get a safe response; model timeout degrades calmly; tool errors never become invented success; messages outside the 24-hour window use only an approved template path; logs contain no secrets or message bodies; deletion and retention jobs work; worker restart does not lose accepted jobs; and a human can take over.
Do not describe the build as production-ready. At the end, report test evidence, remaining risks, manual Meta steps, and the exact production gates still open.9. Test in layers
| Layer | Minimum proof |
|---|---|
| Unit | Signature, payload, window, redaction, and tool validators |
| Integration | Database, queue, model adapter, and Meta client with stubs |
| Replay | Duplicate and out-of-order webhook fixtures |
| End to end | Test number sends and receives a real message |
| Failure | Timeouts, 429s, 5xx, expired token, queue and database outage |
| Security | Invalid signature, injection, oversized input, unauthorized tool call |
Use fictional fixtures. Keep a human-review transcript set covering greetings, ambiguous requests, prompt injection, unsafe requests, escalation, and restart or deletion. Evaluate groundedness, tool correctness, policy compliance, latency, and handoff quality, not whether responses merely sound fluent.
10. Pass the production gate
- [ ] Business and app verification requirements are complete.
- [ ] Production token lifecycle and least privilege are documented.
- [ ] HTTPS, signature verification, queueing, deduplication, and backups work.
- [ ] The 24-hour window and templates are enforced outside the model.
- [ ] Retention, deletion, privacy notice, consent, and human escalation are reviewed.
- [ ] Alerts cover webhook errors, queue age, delivery failures, latency, token expiry, tool errors, and spend.
- [ ] Load, restore, rollback, key rotation, and incident runbooks were exercised.
- [ ] A named owner can disable the agent and resume human service.
Deploy first to a staging number and environment. Promote the same reviewed artifact, change configuration through secret references, then run one inbound reply, one duplicate delivery, one escalation, and one permitted template test. A healthy endpoint alone is not evidence that the agent is safe or useful.
11. Continue improving
Review failed conversations, policy blocks, human handoffs, latency, cost, and tool errors with redacted data. Change one behavior at a time, rerun the transcript suite, and keep a rollback point.
For a broader build discipline, continue with the Three-Step AI Workflow or explore more NEXAIUM Free Guides.
Official sources
- Meta WhatsApp Cloud API collection for tokens, identifiers, permissions, messages, and webhooks.
- WhatsApp Business Messaging Policy for automation, escalation, templates, and the 24-hour window.
- Anthropic Claude Code CLI reference for plan mode and command behavior.
- OpenRouter quickstart, provider routing, fallbacks, and Zero Data Retention.
- OWASP LLM Top 10 and OWASP Logging Cheat Sheet for threat modeling and safe logs.
Reviewed September 4, 2026. Meta versions, permissions, policies, and provider behavior change. Recheck official documentation before implementation.

