SuperAPI AI Directory

whatsapp-cloud-api

Coding & development

View repository

Updated 10-16 01:13

About this skill

WhatsApp Cloud API - Professional Integration

Overview

Integration with WhatsApp Business Cloud API (Meta). Messages, templates, HMAC-SHA256 webhooks, customer service automation. Node.js and Python boilerplates.

When to Use This Skill

  • When the user mentions "whatsapp" or related topics
  • When the user mentions "whatsapp business" or related topics
  • When the user mentions "api whatsapp" or related topics
  • When the user mentions "chatbot whatsapp" or related topics
  • When the user mentions "mensagem whatsapp" or related topics
  • When the user mentions "template whatsapp" or related topics

Do Not Use This Skill When

  • The task is unrelated to whatsapp cloud api
  • A simpler, more specific tool can handle the request
  • The user needs general-purpose assistance without domain expertise

How It Works

Skill for implementing professional integrations with WhatsApp Business using Meta's official Cloud API. Supports Node.js/TypeScript and Python.

Overview

The WhatsApp Cloud API is Meta's official API for sending and receiving messages via WhatsApp Business. Since October 2025, it is the only supported option (the On-Premises API has been discontinued).

API version: Graph API v21.0 (2026) Base URL: https://graph.facebook.com/v21.0/{phone-number-id}/messages Authentication: Bearer Token (System User Token for production)

Pricing 2026 (per message):

Category Cost When charged
Marketing $0.025-$0.1365 Campaigns, promotions
Utility $0.004-$0.0456 Order confirmations, updates
Authentication $0.004-$0.0456 OTP, password reset
Service FREE Reply within the 24h window

Prerequisites:

  • Meta Business Suite account (free)
  • App on Meta for Developers with the WhatsApp product
  • Verified phone number
  • System User Token (permanent)

If the user does not have a Meta Business account, read references/setup-guide.md for the complete setup guide from scratch.


Decision Tree

Use this tree to determine the next step:

O usuario precisa de setup inicial?
├── SIM → Leia references/setup-guide.md
└── NAO → Qual linguagem?
    ├── Node.js/TypeScript
    └── Python
    → O que quer fazer?
       ├── Enviar mensagens → Secao "Tipos de Mensagem" abaixo
       ├── Receber mensagens → Secao "Webhooks" abaixo
       ├── Automatizar atendimento → Secao "Automacao" abaixo
       ├── WhatsApp Flows / Commerce → Secao "Features Avancados" abaixo
       ├── Gerenciar templates → references/template-management.md
       └── Compliance / limites → Secao "Compliance & Quality" abaixo

To start a project from scratch with a ready-made boilerplate, use the script:

python scripts/setup_project.py --language nodejs --path ./meu-projeto

## Ou

python scripts/setup_project.py --language python --path ./meu-projeto

1. Configure Environment Variables

WHATSAPP_TOKEN=seu_access_token_aqui
PHONE_NUMBER_ID=seu_phone_number_id
WABA_ID=seu_whatsapp_business_account_id
APP_SECRET=seu_app_secret
VERIFY_TOKEN=token_customizado_para_webhook

2. Send a Simple Text Message

Node.js/TypeScript:

import axios from 'axios';

const GRAPH_API = 'https://graph.facebook.com/v21.0';

async function sendText(to: string, message: string) {
  const response = await axios.post(
    `${GRAPH_API}/${process.env.PHONE_NUMBER_ID}/messages`,
    {
      messaging_product: 'whatsapp',
      to,
      type: 'text',
      text: { body: message }
    },
    { headers: { Authorization: `Bearer ${process.env.WHATSAPP_TOKEN}` } }
  );
  return response.data; // { messaging_product, contacts, messages: [{ id }] }
}

Python:

import httpx
import os

GRAPH_API = "https://graph.facebook.com/v21.0"

async def send_text(to: str, message: str) -> dict:
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"{GRAPH_API}/{os.environ['PHONE_NUMBER_ID']}/messages",
            json={
                "messaging_product": "whatsapp",
                "to": to,
                "type": "text",
                "text": {"body": message}
            },
            headers={"Authorization": f"Bearer {os.environ['WHATSAPP_TOKEN']}"}
        )
        return response.json()  # {"messaging_product", "contacts", "messages": [{"id"}]}

3. Send a Template Message (Outside the 24H Window)

Templates are the only way to start a conversation with a customer. They must be approved by WhatsApp before use.

{
  "messaging_product": "whatsapp",
  "to": "5511999999999",
  "type": "template",
  "template": {
    "name": "hello_world",
    "language": { "code": "pt_BR" },
    "components": [
      {
        "type": "body",
        "parameters": [
          { "type": "text", "text": "João" }
        ]
      }
    ]
  }
}

4. Check Delivery

Use the test script to validate:

python scripts/send_test_message.py --to 5511999999999 --message "Teste de integracao"

Message Types

Type Use Limit
Text Simple text messages 4096 chars
Template Start conversation / outside the 24h window 1600 chars body
Image Photos and images 5MB
Document PDFs, spreadsheets, docs 100MB
Video Videos 16MB
Audio Voice messages 16MB
Interactive Button Quick reply buttons Max 3 buttons
Interactive List Menu with options in sections Max 10 options
Location Share location lat/long
Contact Share contact vCard format
Reaction React with emoji to message 1 emoji

Example - Interactive buttons (Node.js):

async function sendButtons(to: string, body: string, buttons: Array<{id: string, title: string}>) {
  return axios.post(`${GRAPH_API}/${process.env.PHONE_NUMBER_ID}/messages`, {
    messaging_product: 'whatsapp',
    to,
    type: 'interactive',
    interactive: {
      type: 'button',
      body: { text: body },
      action: {
        buttons: buttons.map(b => ({
          type: 'reply',
          reply: { id: b.id, title: b.title }
        }))
      }
    }
  }, { headers: { Authorization: `Bearer ${process.env.WHATSAPP_TOKEN}` } });
}

// Uso:
await sendButtons('5511999999999', 'Como posso ajudar?', [
  { id: 'suporte', title: 'Suporte' },
  { id: 'vendas', title: 'Vendas' },
  { id: 'info', title: 'Informacoes' }
]);

For complete examples of all types in Node.js and Python, read references/message-types.md.


Webhooks

Webhooks allow you to receive messages and status updates in real time.

Verification (Get) - Required

When you configure the webhook in Meta Developers, Meta sends a GET to verify:

// Node.js (Express)
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) {
    res.status(200).send(challenge);
  } else {
    res.sendStatus(403);
  }
});

Receiving (Post) - With Hmac-Sha256 Security

Every webhook notification comes signed in the header X-Hub-Signature-256. ALWAYS validate before processing:

import crypto from 'crypto';

function validateSignature(rawBody: Buffer, signature: string): boolean {
  const expectedSig = crypto
    .createHmac('sha256', process.env.APP_SECRET!)
    .update(rawBody)
    .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(`sha256=${expectedSig}`),
    Buffer.from(signature)
  );
}

Important: Use crypto.timingSafeEqual (Node.js) or hmac.compare_digest (Python) to prevent timing attacks. Never use simple string comparison.

Events Received

  • messages - Customer message (text, media, button, location)
  • statuses - Status update (sent → delivered → read)
  • errors - Delivery errors

Requirements:

  • HTTPS endpoint with valid SSL certificate
  • Respond with HTTP 200 within 5 seconds
  • Dev: use ngrok for local testing

For complete setup with Node.js and Python examples, read references/webhook-setup.md.


Interactive Main Menu

Use buttons or lists to create an options menu on the first interaction:


## Python - Menu Com Lista Interativa

async def send_main_menu(to: str):
    await send_interactive_list(
        to=to,
        header="Bem-vindo!",
        body="Selecione o que precisa:",
        button_text="Ver opcoes",
        sections=[{
            "title": "Atendimento",
            "rows": [
                {"id": "suporte", "title": "Suporte Tecnico", "description": "Ajuda com problemas"},
                {"id": "vendas", "title": "Vendas", "description": "Conhecer nossos produtos"},
                {"id": "financeiro", "title": "Financeiro", "description": "Boletos e pagamentos"},
            ]
        }]
    )

State Machine For Flows

Manage conversations with a state machine. Each customer has a current state that determines how the next message will be processed:

INICIO → MENU_PRINCIPAL → SUPORTE → AGUARDANDO_DETALHES → ESCALACAO_HUMANO
                        → VENDAS → CATALOGO → CHECKOUT
                        → FINANCEIRO → SEGUNDA_VIA_BOLETO

24-Hour Window

  • Inside the window (24h after the customer's last message): You can send any type of message for free
  • Outside the window: Only template messages (charged by category)

AI Integration (Claude Api)

Combine WhatsApp with Claude for intelligent responses:

  1. Receive message via webhook
  2. Send to Claude API with conversation context
  3. Return response via WhatsApp
  4. Keep escalation to human available

For complete automation patterns, read references/automation-patterns.md.


Whatsapp Flows

Multi-screen interactive forms within WhatsApp. The customer fills in fields without leaving the app. Defined in JSON with screens, components and actions.

Use cases: registrations, appointments, NPS surveys, product selection.

Commerce & Catalog

Up to 500 products in the WhatsApp catalog. Send single-product or multi-product messages with in-app checkout.

Template Management Api

Create, list and delete templates programmatically. Up to 6000 translations per account. Approval in minutes.

Whatsapp Channels

One-way broadcasting to unlimited subscribers. Located in the "Updates" tab of WhatsApp.

Click-To-Whatsapp Ads

Ads on Facebook/Instagram with a button that opens a conversation on WhatsApp. 99% open rate.

Status Tracking

Track delivery: pending → server → device → read. Receive via status updates webhook.

For complete details of advanced features, read references/advanced-features.md. For template management via API, read references/template-management.md.


Essential Checklist

  • Explicit opt-in obtained before sending messages
  • Opt-out mechanism implemented (keyword "SAIR" or "STOP")
  • Consent record with timestamp, method and purpose
  • Content within WhatsApp policies (no spam, no prohibited content)
  • LGPD/GDPR compliance (legal basis defined, data subject rights)
  • Appropriate message frequency (not excessive)
  • Templates approved before use
  • Complete business verification (for higher limits)

Quality Rating

WhatsApp monitors the quality of your messages and assigns a rating:

Rating Meaning Action
Green Good quality, few blocks Maintain — eligible for upgrade
Yellow Medium quality, attention needed Review content and frequency
Red Low quality, risk of suspension Immediate action: reduce volume

Positive signals: High response rate, engagement, few blocks Negative signals: Blocks, spam reports, low engagement

Tier System (Message Limits)

Since October 2025, limits are per Business Portfolio (not per number):

Tier Conversations/24h How to reach
Initial 250 New / unverified account
Tier 1 1,000 Auto-upgrade: 50%+ of the limit for 7 days
Tier 2 10,000 Auto-upgrade: 50%+ of the limit for 7 days
Tier 3 100,000 Auto-upgrade: 50%+ of the limit for 7 days
Unlimited Unlimited Auto-upgrade: 50%+ of the limit for 7 days

2026 Changes: Tiers 2K and 10K will be removed. After business verification, immediate limit of 100K.

For complete compliance guide, read references/compliance.md.


Troubleshooting

Problem Probable Cause Solution
401 Unauthorized Expired or invalid token Generate new System User Token
400 Bad Request Malformed payload Check JSON against examples
Template rejected Content violates policies Review and resubmit with changes
Webhook not receiving Invalid URL or no HTTPS Use ngrok (dev) or SSL certificate (prod)
Rate limit exceeded Exceeded 80 msg/s Implement queue with retry
Low quality rating Many blocks/reports Reduce volume, improve content
Message not delivered Invalid number or not on WhatsApp Validate number before sending
Number not verified OTP not completed Repeat verification via SMS or call

To validate your configuration:

python scripts/validate_config.py

References (Read as Needed)

File When to read
references/setup-guide.md Initial setup — create Meta account, configure API
references/message-types.md Complete examples of all message types
references/webhook-setup.md Configure webhooks with HMAC security
references/automation-patterns.md Chatbot, queues, state machine, AI integration
references/compliance.md LGPD/GDPR, opt-in, quality rating, tier system
references/api-reference.md Endpoints, errors, rate limits, 2026 pricing
references/advanced-features.md Flows, Commerce, Channels, Ads, Status Tracking
references/template-management.md Template CRUD via API

Scripts

Script What it does
scripts/setup_project.py Creates project with boilerplate (Node.js or Python)
scripts/validate_config.py Validates credentials and connection to the API
scripts/send_test_message.py Sends test message to validate setup

Boilerplate

Directory Content
assets/boilerplate/nodejs/ Complete TypeScript/Express project
assets/boilerplate/python/ Complete Python/Flask project
assets/examples/ Examples of JSON payloads (templates, webhooks, flows)

Best Practices

  • Provide clear, specific context about your project and requirements
  • Review all suggestions before applying them to production code
  • Combine with other complementary skills for comprehensive analysis

Common Pitfalls

  • Using this skill for tasks outside its domain expertise
  • Applying recommendations without understanding your specific context
  • Not providing enough project context for accurate analysis

Related Skills

  • instagram - Complementary skill for enhanced analysis
  • social-orchestrator - Complementary skill for enhanced analysis
  • telegram - Complementary skill for enhanced analysis

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.