# Luna: full documentation Luna is a messaging API for WhatsApp, built on Meta’s official WhatsApp Cloud API. This file gathers the integration guides and the API reference, generated from the same content as the site (https://lunahia.com.br/en/docs). --- # Luna documentation Fonte: https://lunahia.com.br/en/docs Luna is a messaging API for WhatsApp, built on Meta’s official WhatsApp Cloud API. Helsen operates as an approved Tech Provider, and no unofficial library takes part in the path. Luna delivers the messaging infrastructure, and what happens inside the conversation belongs to your product. ## The path, from zero to a first message 1. **Create the account** in the [console](https://app.lunahia.com.br/cadastro). You confirm the e-mail and sign in. The account starts on the free trial: 14 days, with capacity for 1 number. To connect more numbers (one per customer, on the SaaS path), sign up for a plan by writing to contato@lunahia.com.br. The plans are on [Pricing](https://lunahia.com.br/en/pricing). 2. **Connect a number.** The number’s owner authorizes in Meta’s window. [Connect a number](https://lunahia.com.br/en/docs/connect-a-number) 3. **Create an API key** in the console, with only the scopes you need. [Quickstart](https://lunahia.com.br/en/docs/quickstart#chave) 4. **Register a webhook** and verify the signature. [Receive events](https://lunahia.com.br/en/docs/receive-events) 5. **Send a message.** [Send messages](https://lunahia.com.br/en/docs/send-messages) If you would rather follow it in one go, the [Quickstart](https://lunahia.com.br/en/docs/quickstart) walks through the five steps with examples that run. ## The guides - [Quickstart](https://lunahia.com.br/en/docs/quickstart): from a new account to a sent message and a received event. - [Account and keys](https://lunahia.com.br/en/docs/account-and-keys): sign up, log in, create and revoke API keys, the scopes, and read the account, the plan and the state of the platform, all with curl. - [Connect a number](https://lunahia.com.br/en/docs/connect-a-number): a new number, a number that stays on the WhatsApp Business app on the phone (coexistence), and a number coming from another provider. - [SaaS with N customers](https://lunahia.com.br/en/docs/saas-with-n-customers): the complete path of a product that subscribes to a plan of numbers and gives its customers WhatsApp, with one externalId per customer, everyone’s events on one endpoint, and a key and webhook per customer. Start here if you sell to many businesses. - [Plan and numbers](https://lunahia.com.br/en/docs/plan-and-numbers): the free trial, the number capacity, the 409 capacity error, how to disconnect and reconnect a number, and what happens when the trial ends. - [Receive events](https://lunahia.com.br/en/docs/receive-events): the endpoint, every event type, the delivery guarantees, retries, replay and signature verification. - [Send messages](https://lunahia.com.br/en/docs/send-messages): every message type, the 24-hour window, idempotency and following delivery. - [AI agent](https://lunahia.com.br/en/docs/ai-agent): the complete loop of an agent that answers on WhatsApp, in code that runs when pasted (Python and Node): verify, deduplicate, mark as read, show typing, reply with idempotency and fall back to a template. - [Users without a phone number (BSUID)](https://lunahia.com.br/en/docs/users-without-phone): what changes when the user writes without the phone number showing, the wa_id that can be null, how to answer with recipient, and a change of phone number or BSUID. - [What the number does at Meta](https://lunahia.com.br/en/docs/number-on-meta): the business profile, blocked users, the QR code with a short link and the notice that a contact asked to stop receiving marketing. - [Test mode](https://lunahia.com.br/en/docs/test-mode): a test key that sends without going to Meta and delivers simulated states to your webhook, signed and with test true. - [SDK and n8n](https://lunahia.com.br/en/docs/sdk-and-n8n): the n8n workflow that works today with the standard nodes (Webhook, Code and HTTP Request), with a workflow to import, and what exists of the SDK and the dedicated node. - [Templates](https://lunahia.com.br/en/docs/templates): create, follow the status, media header, and the difference between approved and cleared. - [Errors](https://lunahia.com.br/en/docs/errors): the error shape, the main codes, what to do about each, and the rate limit headers. - [Limits and pacing](https://lunahia.com.br/en/docs/limits-and-pacing): the request limit, the burst of each conversation, the per-number pace, the send queue and the daily conversation limit, with the numbers and what happens when you go past them. - [Account health](https://lunahia.com.br/en/docs/account-health): Meta’s notices about restriction, violation, deactivation, disconnection, limit and quality, what each event means and what to do in each case. - [Meta costs](https://lunahia.com.br/en/docs/meta-costs): who charges for what, the Meta charging rules in force since October 1, 2026, and where to check what was charged. - [Glossary](https://lunahia.com.br/en/docs/glossary): 24-hour window, template, idempotency, BSUID, webhook, signature, wamid, externalId, event_id and raw body, in plain language. ## Coming from another platform - [Coming from Z-API or the Evolution API](https://lunahia.com.br/en/docs/migrate-from-unofficial-api): the mapping of authentication, sending, events and states, and what does not exist on the official API. The model difference is in [Z-API and Evolution: the model](https://lunahia.com.br/en/migrate-from-evolution-api). - [Coming from Twilio](https://lunahia.com.br/en/docs/migrate-from-twilio): sending, templates, states, webhook signature and error codes. - [Coming from another official partner](https://lunahia.com.br/en/docs/migrate-from-another-partner): for those running customers through 360dialog or Gupshup, including how to move a number with the PIN. ## The API reference The guides explain the path. Each route’s contract, field by field, is in the [API reference](https://lunahia.com.br/en/docs/reference), generated from the same definition that validates requests. The OpenAPI 3.1 specification is at [openapi.json](https://api.lunahia.com.br/openapi.json). If a guide disagrees with the reference, the reference wins. Every call carries an API key in the `Authorization` header, in the form `Bearer hlsn_...`. The base is `https://api.lunahia.com.br`, and every route lives under `/v1`. ## What Luna charges for, and what Meta charges for Luna charges for the active-number capacity of the plan, and for nothing beyond that. WhatsApp platform usage is charged by Meta, directly to the end business, on the payment method it registers in its own account. Helsen does not intermediate that payment. The plans are on [Pricing](https://lunahia.com.br/en/pricing). Meta’s rules are in [Meta costs](https://lunahia.com.br/en/docs/meta-costs). --- # Quickstart Fonte: https://lunahia.com.br/en/docs/quickstart This guide takes you from a new account to a sent message and a received event. The console steps are described in words, and the API steps come with examples in curl, Node and Python. ## Before you start - An e-mail and a password of at least 12 characters for the account. - A WhatsApp number with the Brazil country code (+55). Luna serves only those numbers. - A WhatsApp Business account owned by the number’s owner, and a payment method of theirs at Meta. The number and the account belong to the end business, and Meta charges them for WhatsApp platform usage. - A public HTTPS address to receive [webhooks](https://lunahia.com.br/en/docs/glossary#webhook). In development, an HTTPS tunnel to your machine works. - Node 20 or newer, or Python 3 with `requests`, to run the examples. curl works too, and it is all you need for steps 1 to 3 and 5. (The [AI agent](https://lunahia.com.br/en/docs/ai-agent) guide uses only Python’s standard library, without `requests`.) ## The examples’ variables The examples do not carry made-up values for you to replace: they read environment variables. Set each one when the step that produces it ends (the terminal you run the examples in must have them): | Variable | Where it comes from | | --- | --- | | `LUNA_API_KEY` | The key you create in step 3. It starts with `hlsn_` and appears once. | | `LUNA_NUMBER_ID` | The origin number: the `metaPhoneNumberId` (or the `id`) that `GET /v1/numbers` returns, at the end of step 3. | | `LUNA_TO` | Your mobile phone, digits only, with 55 and the area code, without the `+` (for example `5511999990000`). It is who you will reply to in step 5. | | `LUNA_WEBHOOK_SECRET` | The `secret` that the endpoint registration returns in step 4. It starts with `whsec_`. | | `LUNA_MESSAGE_ID` | The `id` that the `202` of step 5 returns, to look the message up. | ```bash export LUNA_API_KEY="hlsn_..." export LUNA_NUMBER_ID="123456789012345" export LUNA_TO="5511999990000" ``` ## 1. Create the account 1. Open the [sign-up page in the console](https://app.lunahia.com.br/cadastro). 2. Fill in the company name, the e-mail and the password (twice), and click **Criar conta** (Create account). 3. Open the e-mail you receive and click the confirmation link. It is valid for seven days and works only once. 4. [Sign in to the console](https://app.lunahia.com.br/login) with the same e-mail and password. The session lasts eight hours. > Confirming the e-mail is what unlocks connecting a number. Before that, the account can already create keys and integrate against the API, but it cannot open the connection. ## 2. Connect a number 1. In the **Números** (Numbers) menu, open **Conectar número** (Connect number) and click **Conectar WhatsApp** (Connect WhatsApp). 2. Meta’s window opens. The number’s owner chooses the WhatsApp account and the number, and authorizes access. Do not close the tab until the window finishes. 3. When Luna finishes registering, the number shows up in **Números**. Through the API, its `state` is `REGISTERED`. Is the number already on the WhatsApp Business app on the phone, or does it come from another provider? Both cases have their own steps in [Connect a number](https://lunahia.com.br/en/docs/connect-a-number). ## 3. Create an API key 1. In the **Integração** (Integration) menu, open **Chaves de API** (API keys) and click **Criar chave** (Create key). 2. Confirm your password. The console asks again even with the session open, and does not ask again for the next two hours. 3. Give it a label and tick only this guide’s scopes: `numbers:read`, `webhooks:write`, `messages:write` and `messages:read`. If you sell to many businesses and will go on to [SaaS with N customers](https://lunahia.com.br/en/docs/saas-with-n-customers), also tick `onboarding:write` (the per-customer connection link) and `webhooks:read`; to create templates, `templates:write`. A missing scope answers `403` on the first call. 4. Copy the secret, which starts with `hlsn_`. **It appears exactly once.** No route returns it afterwards: if you lose it, revoke the key and create another. Keep the key in an environment variable, never in code: ```bash export LUNA_API_KEY="hlsn_YOUR_KEY_HERE" ``` Now read your numbers. The response carries the `metaPhoneNumberId`, which is the value the send asks for in `from`: ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/numbers", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` Response (trimmed) ```json { "data": [ { "id": "ed404df1-b420-4ed6-8743-ba1609892e0a", "metaPhoneNumberId": "123456789012345", "displayNumber": "+55 11 99999-0000", "state": "REGISTERED", "orientacao": "Número conectado e operando. Mensagens já entram e saem por ele." } ] } ``` The `id` field is the number’s identifier at Luna. The `metaPhoneNumberId` is Meta’s. Every route that takes a number accepts both, so use whichever your system already stores. ```bash export LUNA_NUMBER_ID="123456789012345" ``` ## 4. Register the webhook First bring up a server that receives the event. The two files below verify the signature of every delivery and print what arrives. Save the first as `verify.mjs` (or `verify.py`) and the second as `server.mjs` (or `server.py`), and run it with `LUNA_WEBHOOK_SECRET` set after registering. **In plain words.** You and Luna share a secret: the `secret` that the registration response returns, which starts with `whsec_`. Before sending each event, Luna mixes the secret with the event’s content and writes the result in the `X-Luna-Signature` header, like a stamp. Whoever does not know the secret cannot make an identical stamp. On receiving, you redo the same mix and see whether the stamp matches: if it does, the event came from Luna and nobody changed it on the way. **Why it matters.** Your webhook’s address is public. Without checking the stamp, anyone can send a fake event (a “paid order”, for example) and your system would act as if it were real. 1. From the header, take the number after `t=` (the instant Luna signed) and the values after `v1=` (the stamps). 2. Join the `t`, a dot and the **body exactly as it arrived** (the same bytes, without opening the JSON and building it again), and do the mix with your secret: that is HMAC-SHA256, which every language has ready-made. 3. Compare the result with each `v1`. Equal to any: you can trust it. Different from all: answer `401` and ignore the event. ```js import crypto from 'node:crypto'; const TOLERANCE_SECONDS = 300; // rawBody: the exact bytes received (a Buffer), never re-serialized JSON. export function verifyLunaSignature(rawBody, header, secret, nowMs = Date.now()) { if (typeof header !== 'string' || !secret) return false; // 1. The header carries the instant t and the signature v1. const m = /^t=(\d{1,15}),/.exec(header); if (!m) return false; const t = Number(m[1]); // 2. Refuse what is too old (a recorded delivery replayed later). if (Math.abs(Math.floor(nowMs / 1000) - t) > TOLERANCE_SECONDS) return false; // 3. Redo the calculation with your secret and compare it with v1. const expected = crypto .createHmac('sha256', secret) .update(`${t}.`) .update(rawBody) .digest(); // During a secret rotation the header carries two v1 values: check them all. let ok = false; for (const [, hex] of header.matchAll(/v1=([0-9a-fA-F]{64})/g)) { if (crypto.timingSafeEqual(Buffer.from(hex, 'hex'), expected)) ok = true; } return ok; } ``` ```python import hashlib import hmac import re import time TOLERANCE_SECONDS = 300 def verify_luna_signature(raw_body, header, secret, now=None): # raw_body: the exact bytes received, never re-serialized JSON. if not header or not secret: return False # 1. The header carries the instant t and the signature v1. m = re.match(r"^t=(\d{1,15}),", header) if not m: return False t = int(m.group(1)) # 2. Refuse what is too old (a recorded delivery replayed later). now = time.time() if now is None else now if abs(int(now) - t) > TOLERANCE_SECONDS: return False # 3. Redo the calculation with your secret and compare it with v1. expected = hmac.new( secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256 ).hexdigest() # During a secret rotation the header carries two v1 values: check them all. ok = False for sig in re.findall(r"v1=([0-9a-fA-F]{64})", header): if hmac.compare_digest(sig.lower(), expected): ok = True return ok ``` ```js import http from 'node:http'; import { verifyLunaSignature } from './verify.mjs'; const SECRET = process.env.LUNA_WEBHOOK_SECRET; // whsec_... const seen = new Set(); // in production: a database or Redis, with an expiry async function handle(event) { switch (event.event_type) { case 'message.received': // wa_id can be null (user without a phone number): user_id is then the key console.log('received', event.message.wa_id ?? event.message.user_id, event.message.text); break; case 'message.status': console.log('status', event.message.wamid, event.message.status); break; default: console.log('ignored', event.event_type); // new types can appear } } http .createServer((req, res) => { const chunks = []; req.on('data', (chunk) => chunks.push(chunk)); req.on('end', () => { const raw = Buffer.concat(chunks); if (!verifyLunaSignature(raw, req.headers['x-luna-signature'], SECRET)) { res.writeHead(401).end(); return; } res.writeHead(200).end(); // answer first, work after const event = JSON.parse(raw.toString('utf8')); if (seen.has(event.event_id)) return; // at-least-once: drop repeats seen.add(event.event_id); handle(event).catch((err) => console.error('handler failed', err)); // the handler never runs on the request thread: the work goes to a queue }); }) .listen(Number(process.env.PORT ?? 3000)); ``` ```python import json import os import queue import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from verify import verify_luna_signature SECRET = os.environ["LUNA_WEBHOOK_SECRET"] # whsec_... seen = set() # in production: a database or Redis, with an expiry seen_lock = threading.Lock() events = queue.Queue() # the handler never runs on the request thread: the work goes to a queue def handle(event): kind = event["event_type"] if kind == "message.received": # wa_id can be null (user without a phone number): user_id is then the key print("received", event["message"]["wa_id"] or event["message"]["user_id"], event["message"]["text"]) elif kind == "message.status": print("status", event["message"]["wamid"], event["message"]["status"]) else: print("ignored", kind) # new types can appear def worker(): # one worker takes the events one at a time (call the LLM here, not in the request) while True: event = events.get() try: handle(event) except Exception as err: # a failure in one event must not stop the worker print("handler failed", repr(err)) class Handler(BaseHTTPRequestHandler): def do_POST(self): raw = self.rfile.read(int(self.headers.get("Content-Length", 0))) header = self.headers.get("X-Luna-Signature") if not verify_luna_signature(raw, header, SECRET): self.send_response(401) self.send_header("Content-Length", "0") self.end_headers() return self.send_response(200) # answer first, work after self.send_header("Content-Length", "0") self.end_headers() event = json.loads(raw) with seen_lock: repeated = event["event_id"] in seen # at-least-once: drop repeats seen.add(event["event_id"]) if not repeated: events.put(event) threading.Thread(target=worker, daemon=True).start() ThreadingHTTPServer(("", int(os.environ.get("PORT", "3000"))), Handler).serve_forever() ``` The server answers `200` at once and hands the event to a queue (the Python worker thread, the Node floating promise): if it did the work before answering, a slow call to another system would pass the 10 seconds Luna waits for and the delivery would count as a failure. Checking the signature with `openssl`, step by step, is in [Receive events](https://lunahia.com.br/en/docs/receive-events#assinatura). Now register the server’s public URL. In the console, use **Integração**, **Webhooks**, **Cadastrar endpoint** (Register endpoint). Through the API: ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/webhooks/luna" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "url": "https://example.com/webhooks/luna" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/webhooks/endpoints", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "url": "https://example.com/webhooks/luna", }, timeout=10, ) print(res.status_code, res.json()) ``` `201` response ```json { "id": "5c0e9a52-3a0e-4c3f-9f3e-0b3f6f1a2c77", "url": "https://example.com/webhooks/luna", "createdAt": "2026-10-06T14:00:00.000Z", "updatedAt": "2026-10-06T14:00:00.000Z", "previousSecretExpiresAt": null, "secret": "whsec_EXAMPLE_NOT_A_REAL_SECRET" } ``` > The `secret` field appears in this response and in no other. Store it now, in `LUNA_WEBHOOK_SECRET`. The URL must be `https` and point to a public address, and Luna does not follow redirects. ## 5. Send the first message Free-form text only goes out to someone who messaged your number in the last 24 hours (the [24-hour window](https://lunahia.com.br/en/docs/glossary#janela)). So before sending, **write from your phone to the connected number**. That opens the window, and it is also your first received event (see step 6). Then reply with `POST /v1/messages`. The `from` is the origin number, the `metaPhoneNumberId` from step 3 (`LUNA_NUMBER_ID`). The `to` is the recipient’s phone, digits only, with the country code and without the plus sign (`LUNA_TO`, your mobile phone): ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d @- < `Idempotency-Key` is an **optional** header and is left out of the example above. It does one thing: if you repeat the call (after a timeout, say), Luna returns the same message instead of sending a second one. Send one unique value for each message, such as a UUID. For an AI agent it is close to mandatory: see [AI agent](https://lunahia.com.br/en/docs/ai-agent#idempotencia). ```bash curl -X GET "https://api.lunahia.com.br/v1/messages/$LUNA_MESSAGE_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch(`https://api.lunahia.com.br/v1/messages/${process.env.LUNA_MESSAGE_ID}`, { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( f"https://api.lunahia.com.br/v1/messages/{os.environ['LUNA_MESSAGE_ID']}", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ## 6. See the first event The server from step 4 should have printed the `message.received` for the message you wrote from your phone, and then a `message.status` for each state change of the reply you sent. These are the bodies: `message.received` ```json { "version": "2026-11-10", "event_id": "a2f4909b0fd2db8ab8b1bfe4e16487f49b86113e27bf8c3c9d10a2d0fefebc72", "event_type": "message.received", "occurred_at": "2026-10-06T14:02:11.482Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "b6d84033-a8e8-4db9-aab6-565ce203cc51", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "text", "text": "Oi! Queria saber o status do meu pedido.", "profile_name": "Maria Souza", "media": null, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` `message.status` ```json { "version": "2026-11-10", "event_id": "464e089a80690f1792db6249678ddeced5ad5be0d46d95e2daa263779f7d92e5", "event_type": "message.status", "occurred_at": "2026-10-06T14:02:14.090Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "status": "sent", "error_code": null, "error": null, "pricing": { "billable": false, "pricing_model": "PMP", "type": "free_customer_service", "category": "service" }, "callback_data": "atendimento-8841" } } ``` ### Read the received message without a webhook You do not need a server to see what your phone sent: Luna stores the messages, and `GET /v1/messages` lists them, newest first. With `direction=inbound` only the received ones come. The scope is `messages:read`: ```bash curl -X GET "https://api.lunahia.com.br/v1/messages?direction=inbound&limit=5" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages?direction=inbound&limit=5', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/messages?direction=inbound&limit=5", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` `200` response (trimmed) ```json { "data": [ { "id": "b6d84033-a8e8-4db9-aab6-565ce203cc51", "direction": "inbound", "type": "text", "bodyText": "oi", "waId": "5511999990000", "createdAt": "2026-10-06T14:00:00.000Z" } ], "nextCursor": null } ``` The `waId` is the phone of whoever wrote: it is the `to` value for replying. To see just one conversation, add `&waId=5511999990000`. ### If nothing arrived - Read the number with `GET /v1/numbers/{id}` and look at `subscriptionConfirmedAt`. If it is null, the app’s subscription to the account has not been confirmed yet, and no event arrives. - Check that your server answers `2xx` within 10 seconds. Any other answer counts as a failure and the delivery is retried. - Ask for a message’s event again with `POST /v1/messages/{id}/replay`. Details in [Receive events](https://lunahia.com.br/en/docs/receive-events#retentativas). - The send state and the reason for a failure are in `GET /v1/messages/{id}`, in the `erros` field. See [Errors](https://lunahia.com.br/en/docs/errors). ## Next steps - Connect a number that stays on the phone app, or that comes from another provider: [Connect a number](https://lunahia.com.br/en/docs/connect-a-number). - Wiring up an AI agent? The complete loop, with code that runs: [AI agent](https://lunahia.com.br/en/docs/ai-agent). - Learn the events and the delivery guarantees: [Receive events](https://lunahia.com.br/en/docs/receive-events). - Send images, documents, buttons and more: [Send messages](https://lunahia.com.br/en/docs/send-messages). - Start a conversation outside the 24-hour window: [Templates](https://lunahia.com.br/en/docs/templates). - Each route’s contract is in the [API reference](https://lunahia.com.br/en/docs/reference). --- # Account and keys Fonte: https://lunahia.com.br/en/docs/account-and-keys Everything the console does with your account can also be done through the API, because the console is a client of it. This guide shows the whole path: sign up, log in, create a key, use the scopes, revoke, and read the account, the plan and the state of the platform. ## How the API authenticates Every integration route asks for a key in the `Authorization` header, in the form `Bearer hlsn_...`. The key carries scopes: each route demands its own, and a key without the scope gets `403`. With no key, or with an invalid or revoked one, the answer is `401`. There are two kinds of credential. The **integration key** is your server’s: it is valid until revoked. The **session** is the console’s: it lasts eight hours, comes from the login, and cannot create or revoke keys on its own. To create a key, the session confirms the password first (step 3 below). ## 1. Sign up `POST /v1/operators/signup` creates the account and its first operator in a single call, with no credential. The password is at least 12 characters, and whoever builds the screen reads that minimum at `GET /v1/public/password-policy` (`{ "minLength": 12 }`, no credential) instead of copying the number. The answer is `201` and carries no session: the next step is to log in. ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/signup" \ -H "Content-Type: application/json" \ -d '{ "email": "ana@suaempresa.com.br", "password": "uma frase longa que so voce sabe", "tenantName": "Sua Empresa" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/operators/signup', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ "email": "ana@suaempresa.com.br", "password": "uma frase longa que so voce sabe", "tenantName": "Sua Empresa" }), }); console.log(res.status, await res.json()); ``` ```python import requests res = requests.post( "https://api.lunahia.com.br/v1/operators/signup", json={ "email": "ana@suaempresa.com.br", "password": "uma frase longa que so voce sabe", "tenantName": "Sua Empresa", }, timeout=10, ) print(res.status_code, res.json()) ``` ```json { "nextStep": "login" } ``` Luna sends an email with a confirmation link. It is valid for seven days and accepted once. The account already reads the documentation and creates keys before confirming, but only a confirmed account opens a number connection session. If the email did not arrive, `POST /v1/operators/confirmation/resend` sends it again (only with the console session, and there is a ceiling of a few resends per hour). ## 2. Log in `POST /v1/operators/login` exchanges email and password for an eight-hour session credential. The `token` field is the `Bearer` of the next calls in this guide that use the session. The refusal is always the same, wrong password or no such account. ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/login" \ -H "Content-Type: application/json" \ -d '{ "email": "ana@suaempresa.com.br", "password": "uma frase longa que so voce sabe" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/operators/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ "email": "ana@suaempresa.com.br", "password": "uma frase longa que so voce sabe" }), }); console.log(res.status, await res.json()); ``` ```python import requests res = requests.post( "https://api.lunahia.com.br/v1/operators/login", json={ "email": "ana@suaempresa.com.br", "password": "uma frase longa que so voce sabe", }, timeout=10, ) print(res.status_code, res.json()) ``` ```json { "tenantId": "0b5e3c1a-7d42-4f6a-9c18-2e7a1d5b8f90", "operatorId": "6a2d9f40-1b73-4e85-a0c6-3d8e5f7b9a12", "token": "hlsn_...", "expiresAt": "2026-10-28T20:00:00.000Z", "scopes": [ "onboarding:write", "numbers:read", "numbers:write", "messages:read", "messages:write", "templates:read", "templates:write", "webhooks:read", "webhooks:write", "keys:read", "session:end", "session:elevate" ] } ``` Keep the session token ```bash export LUNA_SESSION="hlsn_..." ``` To change the password knowing the current one, without going through "Forgot my password", use `POST /v1/operators/password/change` with the session and the body `{ "currentPassword": "...", "newPassword": "..." }`. The answer is `204`. The new password follows the same rule as signup, the operator's other sessions are ended and the one that asked for the change stays valid. A wrong current password answers `401`, and there is a ceiling on attempts per session. ## 3. Confirm the password Creating and revoking a key is a sensitive action. `POST /v1/operators/step-up` confirms the password of the session’s operator and opens a two-hour window in which that same session can create and revoke keys. The answer carries `elevatedUntil`, the end of the window, and in `scopes` what the window lends the session (`keys:write`). After the two hours, the password is asked again. With the session from step 2 ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/step-up" \ -H "Authorization: Bearer $LUNA_SESSION" \ -H "Content-Type: application/json" \ -d '{ "password": "uma frase longa que so voce sabe" }' ``` ```json { "elevatedUntil": "2026-10-28T14:00:00.000Z", "scopes": ["keys:write"] } ``` To know whether the window is still open without asking for the password needlessly, read `GET /v1/operators/session` with the session: `expiresAt` is the end of the session, `elevatedUntil` is the end of the window (null with no window or with it closed) and `scopes` are the scopes the session has now. It asks for the `session:end` scope, which the console session already has. ## 4. Create a key `POST /v1/api-keys` creates the key. Ask only for the scopes it needs: a key that only sends messages should not be able to connect a number or create other keys. With `externalId`, the key belongs to ONE of your customers and sees only what is theirs. With `mode: "test"`, the key is a test key: it sends without going to Meta, and only uses two routes (see [Test mode](https://lunahia.com.br/en/docs/test-mode)). The answer carries the `secret` field **exactly once**: no route returns it afterwards, and whoever loses it revokes the key and creates another. With the session, inside the window from step 3 ```bash curl -X POST "https://api.lunahia.com.br/v1/api-keys" \ -H "Authorization: Bearer $LUNA_SESSION" \ -H "Content-Type: application/json" \ -d '{ "label": "Integração de produção", "scopes": [ "messages:write", "messages:read", "numbers:read" ] }' ``` ```json { "id": "7d1f4c02-9a3b-4e51-8c7d-2f0b6a91e334", "label": "Integração de produção", "kind": "integration", "scopes": ["messages:write", "messages:read", "numbers:read"], "mode": "live", "externalId": null, "createdAt": "2026-10-28T12:10:44.201Z", "expiresAt": null, "revokedAt": null, "lastUsedAt": null, "secret": "hlsn_..." } ``` Keep the secret, which is your server’s key ```bash export LUNA_API_KEY="hlsn_..." ``` ## The scopes The list is closed and the same for every account. These are the scopes an integration key can have. The `session:end` and `session:elevate` scopes exist only on console sessions. | Scope | What it allows | | --- | --- | | `keys:read` | List and read the account’s keys. | | `keys:write` | Create and revoke keys. | | `numbers:read` | Read numbers, their health, the business accounts, the connection links, the account and the plan. | | `numbers:write` | Edit a number’s label, reconnect and disconnect. | | `messages:read` | Read messages and conversations, and download the media that arrived. | | `messages:write` | Send messages, upload media files, mark as read and show “typing”. | | `templates:read` | List and read templates. | | `templates:write` | Create, edit and delete templates, and upload the sample files. | | `onboarding:write` | Connect numbers: open and complete sessions, reconnect, give the PIN, and create and delete connection links. | | `webhooks:read` | Read the webhook endpoints, the event types and the events Luna gave up delivering. | | `webhooks:write` | Register, edit, test and delete endpoints, rotate the secret, requeue events and ask for a message’s event to be delivered again. | `GET /v1/api-keys/scopes` returns this same list through the API: each scope with its name in Portuguese (`label`), what it allows (`summary`) and `sensitive`, which is `true` for the permissions that give a power that calls for care (creating keys and redirecting the webhook). `GET /v1/api-keys/profiles` returns the ready-made profiles, `agent` (support agent), `full` (full integration) and `read_only`, each with the scopes it grants. When creating the key, send `profile` in place of `scopes`, one of the two and never both: the key is born with the scopes the profile grants at that moment, and stores the scopes, while the profile stays only as a label, in `profile` (null when you picked the scopes one by one). Each key in the list also carries `status` (`active`, `revoked` or `expired`, decided by the API) and `allowedActions` (`revoke` while the integration key is valid), so you can show the button without comparing dates. Both routes ask for `keys:read`. > Each route’s scope is in the [API reference](https://lunahia.com.br/en/docs/reference), at the top of each operation. A missing scope is `403`, and the answer does not say which one is missing beyond what the route asks. ## List and revoke keys `GET /v1/api-keys` lists the keys, with scopes, creation, last use and revocation. The secret never shows. Use `kind=integration` to see only integration keys and hide console sessions. The scope is `keys:read`. ```bash curl -X GET "https://api.lunahia.com.br/v1/api-keys?kind=integration" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/api-keys?kind=integration', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/api-keys?kind=integration", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` `POST /v1/api-keys/{id}/revoke` invalidates the key at once. Repeating the call returns the same result, without error, and the revocation date stays on record. It needs `keys:write` and, for the console session, the window from step 3. ```bash curl -X POST "https://api.lunahia.com.br/v1/api-keys/YOUR_KEY_ID/revoke" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/api-keys/YOUR_KEY_ID/revoke', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/api-keys/YOUR_KEY_ID/revoke", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ## Read the account and the plan `GET /v1/account` returns the credential’s account: identifier, name, whether the email is already confirmed and when the account was created. It has no scope of its own: it asks for `numbers:read`, the lightest of the read scopes. The `operatorEmail` field is filled only when the credential is a console session. ```bash curl -X GET "https://api.lunahia.com.br/v1/account" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/account', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/account", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ```json { "id": "0b5e3c1a-7d42-4f6a-9c18-2e7a1d5b8f90", "name": "Sua Empresa", "emailConfirmed": true, "createdAt": "2026-10-28T11:58:02.114Z", "operatorEmail": null } ``` `PATCH /v1/account` changes the account name. The body is `{ "name": "..." }`, 1 to 120 characters, and the answer is the account with the new name, in the same shape as the `GET`. Only the console session does this (scope `session:end`), and plan suspension does not block it. `GET /v1/subscription` returns the plan, the number capacity and how many are in use. It has a guide of its own: [Plan and numbers](https://lunahia.com.br/en/docs/plan-and-numbers). ```bash curl -X GET "https://api.lunahia.com.br/v1/subscription" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/subscription', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/subscription", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` `GET /v1/account/overview` returns the summary a home screen needs, already decided by the API: `attention`, the list of what the account needs to look at (each item with `code`, `severity`, `title`, `message`, `solution`, the `resource` it refers to, the `action` that fixes it and `since`), in the order it should appear, with what is stopped first; `checklist`, the four first steps (`connect_number`, `create_key`, `add_webhook_endpoint` and `send_message`), each with `done` and `doneAt`; and `numbers`, the numbers by connection state. It asks for `numbers:read`, and a key restricted to one of your customers is refused, because the summary belongs to the whole account. ## See whether the platform is up `GET /status` needs no key and reveals no account data. It answers the state of the platform, measured every few minutes by a synthetic message that enters through the same door Meta uses and has to reach a destination over HTTPS. The `status` is `ok`, `degraded`, `down` or `unknown`; with no recent check, it is `unknown`, and never `ok`. `components` separates intake (`ingestion`), delivery (`delivery`) and the database partition horizon (`partitions`). ```bash curl -X GET "https://api.lunahia.com.br/status" ``` ```js const res = await fetch('https://api.lunahia.com.br/status', { method: 'GET', }); console.log(res.status, await res.json()); ``` ```python import requests res = requests.get( "https://api.lunahia.com.br/status", timeout=10, ) print(res.status_code, res.json()) ``` ```json { "status": "ok", "checkedAt": "2026-10-28T12:05:00.000Z", "components": { "ingestion": "ok", "delivery": "ok", "partitions": "ok" }, "since": "2026-10-27T09:30:00.000Z" } ``` `GET /healthz` is the simplest probe: it answers `200` when the process is up, and says nothing about sending messages. The site’s status page shows the same state, for whoever prefers to read over calling. ## Next steps With the key in hand, connect a number in [Connect a number](https://lunahia.com.br/en/docs/connect-a-number) and send the first message in [Quickstart](https://lunahia.com.br/en/docs/quickstart). Each route’s contract is in the [API reference](https://lunahia.com.br/en/docs/reference). ## Route details for this guide The [API reference](https://lunahia.com.br/en/docs/reference) says how to call each route, in a few lines. What explains the reason for each decision, the edge cases and the warnings is here, in the order of the reference. ### GET /v1/api-keys The secret never comes back here, or from any other route. Luna stores only a cryptographic digest of it. If you lost a key, revoke it and create another. Use kind=integration to see only integration keys and hide console sessions. ### POST /v1/api-keys Give it only the scopes it needs. A key that just sends messages should not be able to connect numbers or mint other keys. externalId, optional, makes the key belong to ONE of your customers: it only reads and sends through the numbers with that externalId (including the ones connected later with the same label), only creates connect links with it, only sees templates and business accounts of the WABAs of those numbers, and neither lists nor creates webhook endpoints or keys. Another customer's number answers 404, like one that does not exist, and a route outside that set answers 403. Use it to give your customer's customer direct access, or to limit the damage of a leaked key. The externalId cannot be changed after creation. ### POST /v1/api-keys/{id}/revoke Revoking does not delete the row. The date stays on record, so an audit can answer when the access ended. ### GET /v1/subscription capacity is how many numbers the account can keep active at the same time, and activeNumbers is how many are active right now. When activeNumbers reaches capacity, opening a connection session or creating a connect link answers 409 number_capacity_reached; reconnecting a number that already counts is not refused. A capacity lower than the usage never disconnects anyone: it only refuses the next number. status says where the account stands. In the free trial (14 days, 1 number), trialEndsAt carries the end and trialDaysLeft carries the days left, computed here. With the trial over and the account not contracted, or with the account blocked by Helsen, status is suspended and suspendedReason gives the reason: sending and writes are refused, reading and receiving messages keep working, and the number stays connected at Meta. The only billable quantity is how many numbers this customer kept active during the period. No platform event changes this value: messages, conversations, templates, media and sessions do not enter this calculation by any path. Use of the WhatsApp platform is billed by Meta, directly to the end business, on the payment method it registers in its own account. Helsen does not intermediate that payment, does not advance it and does not pass it through. Active means configured capacity, not able to send right now. A number waiting on the customer's payment with Meta is still configured capacity and still counts. A number active for three days counts the same as one active all month: there is no proration. The period is half-open: the start is included, the end is not. inicio and fim come together or not at all: without them, the current month in UTC applies, computed by the API. Send both when you need an answer that does not depend on the clock. The identifier list carries the numbers that counted in the period, so the count can be checked. ### POST /v1/operators/signup The response carries no session. After the 201, authenticate at POST /v1/operators/login with the same email and password. The password is at least 12 characters, with no composition requirement. Length protects more than a mandatory mix of symbols, which only produces predictable passwords. A shorter password answers 400 with the password field and the minimum. That one is safe to say: the rule is the same for everyone and reveals nothing about any account. The new account signs in, reads the documentation, creates and revokes API keys, and integrates against this API. What it cannot do yet is open a number connection session: that waits on the email confirmation, and on nothing else. An email that already has an account gets the same 201, and the owner of the address receives an email saying the account already exists and how to sign in. Answering differently would hand over the list of who has an account for free. ### GET /v1/operators/confirm The link is valid for seven days and is accepted exactly once. Opening it again does not undo the confirmation, and the account stays confirmed. Every rejection leads to the same address, with erro=1. The response does not say whether the token does not exist, expired, or was already used, because distinguishing the three would hand over information about someone else's account. Confirming the email is what unlocks connecting a number: a confirmed account can already open a connection session. ### POST /v1/operators/password/forgot The answer is always 202, with the same body, whether or not an account exists with that email. Saying which one it is would hand over the list of who has an account for free. The email is sent after the response, so timing does not tell them apart either. When the account exists, the link is valid for one hour and can be opened a single time, and a new request invalidates the previous one. Repeated requests for the same account stop producing email after a few per hour, and the answer stays the same. The link points to the console's reset screen. If you integrate through the bare API, finish with POST /v1/operators/password/reset, carrying the token that is in the address. ### POST /v1/operators/password/reset The password follows the same rule as signup: at least 12 characters, with no composition requirement. A password outside the rule answers 400 with the password field and the minimum, before the token is looked at. The token is accepted a single time and is valid for one hour. An unknown, malformed, expired or already used token answers the same 400, with the same body, because telling them apart would hand over information about someone else's account. Changing the password ends every console session of that operator. Integration API keys are not sessions and keep working. ### GET /v1/account It works with a console session and with an integration API key. There is no scope of its own for this read: it asks for numbers:read, the lightest of the read scopes, and a key with no read scope at all gets 403. operatorEmail is the operator's email, and it only exists when the credential is a console session. An integration key has no person behind it, and for it the field comes back null. ### POST /v1/operators/confirmation/resend Console session only: an integration API key has no email to receive the link and gets 403. It answers 202 in both cases. If the account was already confirmed nothing is sent and emailConfirmed is true; otherwise it is false and the email went out. If sending fails it answers 503 and it is worth trying again. There is a ceiling of a few resends per hour, per account, and past it the answer is 429. ### POST /v1/operators/login The rejection is always identical, byte for byte. The API does not distinguish a wrong password from a nonexistent account, because distinguishing them would hand over the list of who has an account for free. The session cannot create or revoke API keys. Re-authentication exists for that. After 10 wrong attempts for the same email within 15 minutes, login for that email answers 429 with Retry-After until the window ends, even with the right password. If you forgot the password, use POST /v1/operators/password/forgot. ### POST /v1/operators/step-up No elevated credential is issued. There is no new secret in this response and no new row in the database: what changes is a timestamp recorded on the session itself, and elevatedUntil is that timestamp. After two hours the password is required again, and reopening the window means confirming it once more. Ending the session ends the window with it, with no separate step. It takes no email: the identity comes from the session itself. That way one operator's password never elevates another operator's session. --- # Connect a number Fonte: https://lunahia.com.br/en/docs/connect-a-number There are three situations: a new number for the Cloud API, a number that keeps working on the WhatsApp Business app on the phone, and a number that is already on another provider’s Cloud API. In all of them, the number and the WhatsApp Business account stay with the end business. And there is a separate question: who connects. If it is your product’s customer, you send a connect link. ## How the connection works The connection happens in the flow Meta calls Embedded Signup. In Meta’s window, the number’s owner chooses their WhatsApp account and number, and authorizes access on the consent screen. Luna exchanges the code from that authorization for permanent access, subscribes the app to the account and registers the number. - There is no QR Code. Each end business needs its own WhatsApp Business account at Meta, with its own payment method. See [the model difference](https://lunahia.com.br/en/migrate-from-evolution-api) if you come from an unofficial library. - Luna serves only numbers with the Brazil country code (+55). On completion, a number whose displayed phone does not start with 55 is **not registered or subscribed**, and the customer’s authorization is not stored: the session ends in `COUNTRY_NOT_SUPPORTED`, with `motivo: "pais-nao-atendido"`, and the `orientacao` explains it to the customer. The link stays open, so the customer can try again with a +55 number. - A new account must have its e-mail confirmed to open the connection. Without it the API answers `403` with `error: "connection_not_released"`, and the `faltando` field says what is missing. - Meta’s window only opens on a domain authorized in Luna’s app, and that domain is the console’s. It opens in one of two ways: inside the console, in the **Números** (Numbers) menu, under **Conectar número** (Connect number), with your account’s operator; or on the page of a connect link, which you send to your customer. The API does not move the window into your product. See [how to connect a number for your customer](#link-de-conexao). ## Connect a number for your customer If your product serves other companies, the one who connects the number is your customer’s business, and not you. Meta’s window only opens on the domain of Luna’s console, so you do not put it inside your product. You create a **connect link** and send it to your customer: it is a Luna page that shows your account name and opens Meta’s window for them. The person who signs in with Facebook and accepts Meta’s terms is their business, and not you on their behalf. 1. Create the link with `POST /v1/onboarding/links`, sending your customer’s identifier in `externalId`. It is free text, 1 to 128 characters, which Luna does not interpret. 2. Send the `url` from the response to your customer, through the channel you already have with them. 3. What tells you the customer finished is the `number.connected` event, delivered to your webhook endpoint with the customer’s `externalId` (see [Receive events](https://lunahia.com.br/en/docs/receive-events)). Polling remains valid as a fallback, for when your endpoint was down: read the link at `GET /v1/onboarding/links/{id}` until `status` becomes `used`, or list the customer’s numbers by `externalId`. ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/links" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "externalId": "cliente-8841" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/onboarding/links', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "externalId": "cliente-8841" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/onboarding/links", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "externalId": "cliente-8841", }, timeout=10, ) print(res.status_code, res.json()) ``` Response ```json { "id": "5b8a0e0e-9a1f-4d1c-8d27-2f0c5f3a7d10", "url": "https://app.lunahia.com.br/conectar/0f2c8e6a-1d3b-4a5c-9e7f-2b4d6a8c0e12.SEGREDO_DO_LINK", "expiresAt": "2026-10-10T14:00:00.000Z", "externalId": "cliente-8841" } ``` > **The `url` comes out once.** No route returns the token again, not even the listing. Whoever has the `url` can connect a number to your account, so treat it as a secret and send it only to the right customer. The account must have its e-mail confirmed, as to open any connection. ### Follow the link You do not need to poll: when the number finishes connecting, Luna delivers the `number.connected` event to your webhook. Use the read below as a fallback, for example to reconcile after an outage of your endpoint, and not as a waiting loop. ```bash curl -X GET "https://api.lunahia.com.br/v1/onboarding/links/YOUR_LINK_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/onboarding/links/YOUR_LINK_ID', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/onboarding/links/YOUR_LINK_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` Response, after the customer connected ```json { "id": "5b8a0e0e-9a1f-4d1c-8d27-2f0c5f3a7d10", "externalId": "cliente-8841", "status": "used", "expiresAt": "2026-10-10T14:00:00.000Z", "usedAt": "2026-10-08T15:30:12.000Z", "numberId": "ed404df1-b420-4ed6-8743-ba1609892e0a" } ``` | `status` | What it means | | --- | --- | | `open` | The customer can still open the link and connect. | | `used` | A connection made through this link completed. `usedAt` carries the instant. | | `expired` | It passed its deadline without being used. | The `numberId` is the same `id` as in `GET /v1/numbers`. It shows up a few moments after `used`, because Luna registers the number right after, and it stays null if the account was connected without a number. To find a customer’s numbers, filter `GET /v1/numbers` with `?externalId=`, using the same label. The comparison is exact, and a label with no number returns an empty list: ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers?externalId=cliente-8841" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers?externalId=cliente-8841', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/numbers?externalId=cliente-8841", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` Every number carries `externalId`, null when it was connected without a link. `GET /v1/onboarding/links` lists the links, newest first, and never carries the `url`. Filters: `?externalId=` (exact match), `?q=` (the **start** of the `externalId`, case-insensitive, for whoever remembers only the start of the customer’s name) and `?status=`. ### What your customer sees - A Luna page, with no login, that says “your account name asked to connect the WhatsApp of your business”, lists what they need at hand, and offers the two choices: a new number, or a number they already use on WhatsApp Business. - Meta’s window opens from that page. When it finishes, the page says “Número conectado. Você já pode fechar esta página.” (Number connected. You can close this page now.) - If they close the window midway, they can try again from the same page while the link is open. - Of your account, the page shows only the name. There is no menu and no way into the console. ### Deadline and revocation - The link is valid for **72 hours** to be opened. After that, the page tells the customer the link expired and to ask you for a new one. - When a connection made through the link completes, it becomes `used` and opens no other session. To connect another number for the same customer, create another link. - To cancel, revoke the link with `DELETE /v1/onboarding/links/{id}`. The `url` starts answering `404`, as if it had never existed, and a connection the customer had already started can no longer be completed through it. The link stays in your list, with `status: "revoked"` and `revokedAt`, and `GET /v1/onboarding/links` accepts `?status=` to filter. Each link also carries `purpose` (`new` or `reconnect`), `lastFailure` (the last attempt that did not work out) and `allowedActions`. ```bash curl -X DELETE "https://api.lunahia.com.br/v1/onboarding/links/YOUR_LINK_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/onboarding/links/YOUR_LINK_ID', { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status); ``` ```python import os import requests res = requests.delete( "https://api.lunahia.com.br/v1/onboarding/links/YOUR_LINK_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code) ``` ### Several links at once, and a lost url `POST /v1/onboarding/links/batch` creates up to 100 links in one call: `{ "links": [{ "externalId": "cliente-1" }, { "externalId": "cliente-2", "redirectUrl": "https://..." }] }`, each item with the same fields as the single link (`externalId`, `redirectUrl` and `numberId`, all optional). Each item goes through the same rules as the single creation, plan capacity included, and the response is `200` with `results`, one per item in the same order: `index`, `status` (`201` or the status of that item’s error), `link` (with the `url`, which appears only here) or `error`. An item that fails does not bring the others down. The `url` appears only at creation. If your customer lost the email with it, `POST /v1/onboarding/links/{id}/reissue` generates another one for the **same** link, with the same `externalId`, the same `redirectUrl` and the same expiry: the old `url` starts answering `404` and the new one appears only in that response. It only works for an open link (`allowedActions` carries `reissue`); used, expired or revoked answers `409` with `link_not_open` and the state in `status`. ## A new number 1. In the console, open **Números**, **Conectar número**, and click **Conectar WhatsApp**. 2. In Meta’s window, the number’s owner chooses the WhatsApp account and the number, and authorizes. 3. Follow along in the console or through the API. The connection code is valid for **30 seconds**, and the console exchanges it the moment it arrives. ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` Response (trimmed) ```json { "id": "ed404df1-b420-4ed6-8743-ba1609892e0a", "metaPhoneNumberId": "123456789012345", "displayNumber": "+55 11 99999-0000", "state": "REGISTERED", "podeRetentar": false, "qualityRating": "GREEN", "orientacao": "Número conectado e operando. Mensagens já entram e saem por ele.", "tetoDeVazaoPorSegundo": null, "sincronizacaoDoHistorico": null, "subscriptionConfirmedAt": "2026-10-06T11:27:47.141Z", "credentialStatus": "active", "podeReconectar": false, "coexistence": false, "ready": true, "connection": { "status": "connected", "canSend": true, "reasons": [] } } ``` `ready` is true when the number is registered and the app subscription is confirmed, that is, when sending is enabled: use it instead of combining `state` and `subscriptionConfirmedAt`. `coexistence` is true once Luna has observed coexistence traffic on the number, and it can turn from `false` to `true` after the connection. ### The summary state: connection To show your customer whether their number is fine, read `connection`, calculated by the API: `status` (`connected`, `connecting`, `action_required` or `disconnected`), `canSend` (whether sending will work now) and `reasons`, the list of causes with `code`, `message` and `solution`, in Portuguese, ready to pass on. `GET /v1/numbers` returns the same block on every number and accepts `?state=`, `?wabaId=` (the WhatsApp Business account id at Meta, `waba.id`), `?qualityRating=` (`GREEN`, `YELLOW`, `RED`, `NA` or `UNKNOWN`), `?connectionStatus=` (one of the four `connection.status` values), `?q=` (prefix search, case-insensitive, over `externalId`, `label` and `displayNumber`; digits alone also find the number without spaces and hyphen), `?ready=`, `?canSend=` (true or false), `?externalId=` (exact match), `?limit=` (1 to 100) and `?cursor=` (the previous page’s `nextCursor`). A parameter the route does not know answers `400` naming it. The `number.action_required` and `number.action_resolved` events announce when the list of causes goes from empty to non-empty, and back; see [Receive events](https://lunahia.com.br/en/docs/receive-events). Each cause in `reasons` also says what to do about it, so your screen does not have to decide: `action` (`send_pin`, `reconnect`, `reconnect_link`, `meta_manager`, `wait` or `contact_helsen`, and null when there is no action), `actionUrl` (the account address in Meta’s WhatsApp Manager, only with `meta_manager`), `docsUrl` (the guide that explains the cause) and `since` (since when the cause has applied). On `GET /v1/numbers/{id}`, `connection.steps` lists the four connection steps (`authorized`, `receiving`, `registered` and `ready`), each `done`, `current` or `pending`, with the third one called "Número vinculado" (Linked number) in coexistence. The `allowedActions` field, on each number in the list and in the detail, is what your account can do with it now: `disconnect`, `reconnect`, `reconnect_link`, `send_pin` and `edit_label`. The decision considers the number’s state, the customer’s authorization, the confirmed e-mail, the suspension and the plan capacity (reconnecting a number that already counts does not ask for a new slot). Show the button when the verb is in the list, not by `state`. When an action would make sense and the account prevents it, `blockedActions` carries the verb and the reason, in Portuguese, for you to show. The scopes of the key that asked are not part of the list. ### A number’s states | `state` | What it means | | --- | --- | | `PENDING`, `REGISTER_SENT` | Registration is under way, and the platform drives it on its own. Do not open another connection: that would duplicate work already queued. | | `REGISTERED` | The number is registered on the Cloud API. | | `PIN_REQUIRED` | The number requires the two-step verification PIN, and the platform does not know it. See [the PIN](#outro-provedor). | | `BLOCKED` | The number used up the registration attempts Meta grants in a 72-hour window. All that is left is waiting for the window to roll. | The `orientacao` field says, in Portuguese, what is happening and what to do. It is written for you to pass on to your customer without rewriting. The `podeRetentar` field says whether the state allows a new connection attempt: the decision is the platform’s, because each registration attempt spends a quota Meta counts per number. > **Look at `subscriptionConfirmedAt`.** It records when the app’s subscription to the account was confirmed. While it is null, no event arrives, and the failure is silent: the number looks perfect and receives nothing. If Meta refuses sending because the end business has no payment method, the number stays registered and sends nothing. It is not a platform error. The `orientacao` says what is missing and where to fix it. ## A number that stays on the phone app (coexistence) Meta calls coexistence the case of a number that today exists only in the WhatsApp Business app on the phone. It has never been through any API. Connected this way, the number **keeps working in the app**, and Luna operates it as well. ### What you need - The **WhatsApp Business** app (not regular WhatsApp) at version **2.24.17 or newer**. - The end business’s account enabled for it on Meta’s side. The option only shows up in the window when it is. - Real prior use of the app. Meta refuses, with an insufficient-activity warning, a number that was just installed or just left regular WhatsApp. The console’s connection screen recommends using the app for a few days, about a week, and trying again. ### How to connect 1. In the console, open **Números**, **Conectar número**, and click **Conectar número que já uso no WhatsApp Business** (Connect a number I already use on WhatsApp Business). 2. In Meta’s window, choose the option to connect the app you already use, not the one to register a new number. 3. The confirmation code arrives as a **message in WhatsApp itself**, in the phone app. ### What changes once connected - The **device’s earlier conversations are imported** into the platform, and show up in `GET /v1/messages` next to the new ones. - What the business owner answers from the phone app **arrives too**, in the recipient’s conversation. - Sending has a **fixed ceiling of 20 messages per second** per number, and it does not rise over time. A number outside coexistence follows a progression Meta raises on its own as quality builds. The `tetoDeVazaoPorSegundo` field says which case yours is: with a value, it is the fixed ceiling; null, `throughputLevel` applies. ### What the number loses and what can disconnect it - On connecting, **all linked devices** (WhatsApp Web, desktop) are unlinked. The business can link them again afterwards, except WhatsApp for Windows and WearOS, which do not work in coexistence. - These stop working on the number: **groups**, voice and video calls, disappearing messages, view once, live location, Channels and the app’s business tools. **Broadcast lists** become read-only. - Meta **disconnects** the number if the primary phone goes about **14 days without use** (or a linked device, about 30 days). The business needs to open WhatsApp Business on the phone now and then. - The imported history covers conversations from the **last 180 days** before connecting. - What the business sends from the phone app **does not open or extend the 24-hour window** and is not billed as Cloud API. What goes out through Luna follows Cloud API pricing as usual. Source: Meta’s documentation on coexistence, `https://developers.facebook.com/documentation/business-messaging/whatsapp/embedded-signup/onboarding-business-app-users`. ### The history import has a deadline Once the deadline passes without finishing, Meta’s platform **disconnects the end business**, and it has to redo the connection on the device. What tells you where the import stands is `GET /v1/numbers/{id}`, in the `sincronizacaoDoHistorico` and `sincronizacaoPrazo` fields: | `sincronizacaoDoHistorico` | What it means | | --- | --- | | null | There is no import for this number. | | `em_curso` | It is running. `sincronizacaoPrazo` says until when. | | `concluida` | It finished, and the older conversations already show up in `GET /v1/messages`. | | `recusada` | The business owner declined to share on the phone. It will not finish, and asking again changes nothing. | - Do not read the percentage on its own. `sincronizacaoProgresso` is a label Meta assigns, and 100% does **not** mean success. What tells you the outcome is `sincronizacaoDoHistorico`, and nothing else. - Null in `sincronizacaoProgresso` means there is no import. Zero is an import that started and has not moved yet. - `sincronizacaoPrazo` is the platform’s estimate: 24 hours from when it saw the import begin. Meta’s own clock starts slightly earlier, so treat the instant as a limit and act with margin. If the import is still running as the deadline approaches, Luna sends your webhook the `history_sync.deadline_approaching` event. The notice goes out before the deadline, never after, and there is one per number. It can repeat, always with the same `event_id`. The current state is at `GET /v1/numbers/{id}/health`. ```json { "version": "2026-11-10", "event_id": "d42ca56e44ef023d52b0a0739dcf3afb0d5054a8b84321c41e432ed6707b043f", "event_type": "history_sync.deadline_approaching", "occurred_at": "2026-10-07T03:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "history_sync": { "prazo": "2026-10-07T09:00:00.000Z" } } ``` ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/health" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/health', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/health", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ## A number coming from another provider Migrating a number that is already on another provider’s Cloud API is a supported path. It needs no new number and loses no existing one. If you come from an unofficial library, read [the Evolution API migration guide](https://lunahia.com.br/en/migrate-from-evolution-api) first, which explains what changes in the model, and the mapping in [Coming from Z-API or the Evolution API](https://lunahia.com.br/en/docs/migrate-from-unofficial-api). If you run customers through another official partner, see [Coming from another official partner](https://lunahia.com.br/en/docs/migrate-from-another-partner). ### The prerequisites are on the end business’s side - Own the WhatsApp Business account. - Have the number released at the previous provider. - Know the two-step verification PIN, or turn that verification off in its WhatsApp Manager. ### The PIN A number already registered on another provider’s Cloud API almost always has two-step verification configured there, and Meta requires the existing PIN to register it again. **There is no endpoint to read or to turn that PIN off**, so it has to come from the end business. When the number is in `PIN_REQUIRED`, give the PIN: > Meta is changing the PIN. In the new account model it no longer uses the PIN you send to validate registration, but it tells you to keep sending a valid six-digit PIN, and it announces that the two-step verification PIN is being retired for eligible Cloud API numbers. Registering an already registered number again passes silently, and Meta’s response can carry a field saying the PIN was not reset: Luna accepts that response without treating it as an error and confirms the registration by reading the number back. If your number never reaches `PIN_REQUIRED`, it is because Meta is not requiring a PIN for it. ```bash curl -X POST "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/pin" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "pin": "123456" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/pin', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "pin": "123456" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/pin", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "pin": "123456", }, timeout=10, ) print(res.status_code, res.json()) ``` - The `pin` has exactly six digits, and the `id` in the URL is Luna’s, not Meta’s. - The PIN is stored encrypted and never comes back through any route. - A wrong PIN is refused by Meta and spends one of the ten registration attempts it grants per number in a 72-hour window. Using them all locks the number until the window rolls. - That is why the platform keeps the last ones. Near the end, the route answers `409` with `error: "register_budget_reserved"`, and the `tentativasRestantes` and `janelaVira` fields say how many are left and when the window turns over. Confirm the PIN with the end business before trying again. - A number that is not waiting for the PIN answers `409` with `error: "pin_not_applicable"` and the current `state`. ## When the authorization expires `credentialStatus` says whether the customer’s authorization is still valid, and `waba.credentialExpiresAt` says until when (null when it does not expire or when Luna has not read it yet; `waba.credentialNeverExpires` tells the two apart). Luna warns **14 days before** the expiry, in the `number.credential_expiring` event (see [Account health](https://lunahia.com.br/en/docs/account-health#credencial)), and the API starts saying `podeReconectar` true in that window. When the authorization dies for good, `credentialStatus` becomes `reauth_required`, and the number has to be reconnected. There are two paths, and both replace that account’s authorization instead of creating a second one, without counting a new number. **Your customer is the one who runs Meta’s window**, so the normal path is the link: create a reconnection link passing `numberId`, and send the `url` to the customer. Their page opens the renewal directly, and the link inherits the number’s `externalId`. ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/links" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "numberId": "00000000-0000-4000-8000-000000000000" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/onboarding/links', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "numberId": "00000000-0000-4000-8000-000000000000" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/onboarding/links", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "numberId": "00000000-0000-4000-8000-000000000000", }, timeout=10, ) print(res.status_code, res.json()) ``` The other path is the reconnection session, for when Meta’s window is opened in your account’s console. If `credentialStatus` is `reauth_required`, or `podeReconectar` is true, open the session: ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/reconnect" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "numberId": "00000000-0000-4000-8000-000000000000" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/onboarding/reconnect', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "numberId": "00000000-0000-4000-8000-000000000000" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/onboarding/reconnect", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "numberId": "00000000-0000-4000-8000-000000000000", }, timeout=10, ) print(res.status_code, res.json()) ``` The returned session is used exactly like a new connection’s, and completing it replaces that account’s authorization instead of creating a second one. A number whose authorization is valid and more than 14 days from expiring answers `409` with `error: "reconnect_not_applicable"` and the current `credentialStatus`, on both routes. A permanently revoked authorization also answers `409`, and the path is a new connection. A number that is not yours answers `404`, the same as a number that does not exist. ## The onboarding routes The console is a client of this same API, with no privileged route. If you need to understand what it does, the cycle of a connection is this: 1. `POST /v1/onboarding/sessions` opens the session and returns `sessionId`, `configId`, `sdkVersion` (the Graph API version for the `FB.init` of Meta’s window, which Luna keeps up to date: do not copy it into your code), `csrfState` and `expiresAt`. Reconnection (`POST /v1/onboarding/reconnect`) and the link’s public page (`GET /v1/public/onboarding-links/{token}`) return the same `sdkVersion`. Until the session is completed, no account exists on Luna’s side. 2. The number’s owner authorizes in Meta’s window, which returns a code. 3. `POST /v1/onboarding/sessions/{id}/complete` exchanges the code for permanent access. The `csrfState` comes back at completion and is compared in constant time. 4. `GET /v1/onboarding/sessions/{id}` shows the state and the `orientacao`. `POST /v1/onboarding/sessions/{id}/abandon` records, as telemetry, which screen the flow stopped on. ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/sessions" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/onboarding/sessions', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/onboarding/sessions", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/sessions/YOUR_SESSION_ID/complete" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "code": "YOUR_CODE_FROM_META", "csrfState": "YOUR_CSRF_STATE" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/onboarding/sessions/YOUR_SESSION_ID/complete', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "code": "YOUR_CODE_FROM_META", "csrfState": "YOUR_CSRF_STATE" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/onboarding/sessions/YOUR_SESSION_ID/complete", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "code": "YOUR_CODE_FROM_META", "csrfState": "YOUR_CSRF_STATE", }, timeout=10, ) print(res.status_code, res.json()) ``` - The code is valid for **30 seconds**. Call the completion the moment it arrives, with no queue, no intermediate work and no cold start on the way. - `wabaId`, `phoneNumberId` and `businessId` are optional. When the browser does not deliver them, Luna finds them through the Graph API from the token itself. What the browser delivers is checked against what Meta granted to that token: if the `wabaId` is not among the granted accounts, or the `phoneNumberId` is not in the account's list of numbers, the session ends in `FAILED` with `motivo: "identificadores-divergentes"` and nothing is stored. Open a new connection. - The completion answers `200` even when a step fails. The body carries the real state (`state`, `terminal`, `motivo`, `podeRetentar`, `proximoPasso`), because a connection that stops halfway is business state, not a request error. - The onboarding routes require the `onboarding:write` scope. > To see every field, open the Onboarding section in the [API reference](https://lunahia.com.br/en/docs/reference). ## Route details for this guide The [API reference](https://lunahia.com.br/en/docs/reference) says how to call each route, in a few lines. What explains the reason for each decision, the edge cases and the warnings is here, in the order of the reference. ### POST /v1/onboarding/sessions Meta's window for this session only opens on a domain registered in Luna's app, and that domain is the console's. It opens inside the console, with your account's operator, or on the connect link page (POST /v1/onboarding/links) when the person connecting is your customer. This route does not move the window into your product. The csrfState is the binding value. It comes back on completion and is compared in constant time. Without it, anyone who discovered a sessionId could complete someone else's connection. Sessions expire. Until one is completed, no account exists on Luna's side. ### GET /v1/onboarding/sessions/{id} Use it to follow progress after completion, or to find out why a connection stalled. Terminal states never advance again, and the guidance says what to do in each one. ### POST /v1/onboarding/sessions/{id}/abandon It does not change session state and it is not required. It exists so the cause of an abandonment can be found later instead of turning into silence. ### POST /v1/onboarding/sessions/{id}/complete The code is valid for thirty seconds. Call this route the moment it arrives, with no queue, no intermediate work and no cold start in the path. wabaId and phoneNumberId are optional on purpose. When the browser does not deliver them, which is what happens in practice, Luna discovers both from the Graph API using the token itself. Send whatever you have. v1 serves +55 numbers only. If the phone of the number the customer picked is not Brazilian, the connection ends in COUNTRY_NOT_SUPPORTED, with reason pais-nao-atendido: the app is not subscribed, the number is not registered and the customer's authorization is not stored. The orientacao field explains it to the customer, and podeRetentar is true, because a +55 number connects right after. It answers 200 even when a step fails. The body carries the session's real state and the reason, because a connection that stops midway is not a request error: it is a business state. ### POST /v1/numbers/{id}/pin The id in the URL is the number: Luna's UUID (the id GET /v1/numbers returns) or Meta's id (metaPhoneNumberId). Both work. Use it when state is PIN_REQUIRED. Meta requires the PIN already configured on the number, not a new one: there is no endpoint to read or to turn off the PIN of a number that already has two step verification, so only the end business knows it. If the number never had two step verification, the value you send becomes its PIN. The PIN is stored encrypted and never comes back from any route. It does not appear in the response, in the access record or in logs. After you submit it the number goes back to the point where the connection carries on, and the next attempt uses the PIN you gave. A wrong PIN is refused by Meta and spends one of the ten registration attempts it grants each number over a 72 hour window. Running those out locks the number until the window rolls, which is why the platform keeps the last ones back: when the budget gets close to the end, this route answers 409 saying how many are left and when the window rolls, instead of spending what remains. Confirm the PIN with the end business before trying again. A number that is not waiting for the PIN returns 409 with its current state. Overwriting the PIN of a number that already connected would leave it with no way back. A number that is not yours returns 404, the same as a number that does not exist. ### POST /v1/onboarding/reconnect Use it when credentialStatus from GET /v1/numbers/{id} is reauth_required. That same endpoint tells you, in podeReconectar, whether this path is available: the decision belongs to the platform, not to you. The session it returns is used exactly like the one for a new connection: take the csrfState through Meta's flow and finish at POST /v1/onboarding/sessions/{id}/complete. The difference is on our side: the session is already bound to the existing account, so finishing it replaces that account's authorisation instead of creating a second one. Reconnection is also admitted before the authorisation dies, when it expires within 14 days (the same warning as the number.credential_expiring event). A number whose authorisation is valid and far from expiring returns 409, and the response says the current state. An authorisation revoked for good also returns 409: that state does not come back, and the way forward is a new connection. A number that is not yours returns 404, the same as a number that does not exist. ### GET /v1/business-accounts wabaId is the account identifier at Meta, and it is the value template creation takes. That is why this route exists: without it, the only place the identifier ever appeared was the onboarding completion response, which is a past event. status carries the last health state Meta announced for the account: restricted, restrictions (with type, deadline and guidance as Meta sent them), disabled and violationType. Meta offers no lookup for that state: Luna reads back the notice it received, the same one that goes out in the account.restricted, account.violation, account.disabled and account.reinstated events. An account Meta never announced anything about comes back with everything in order. credentialExpiresAt and credentialNeverExpires tell you until when the authorization the customer gave Luna is valid: Luna reads the expiry at connection and checks it every hour. When 14 days are left, the number.credential_expiring event warns once per number. To renew, create a link with POST /v1/onboarding/links passing numberId. paymentMethodOnMeta and currency come from the customer's account at Meta: without a payment method, Meta stops delivering service messages after the allowance of 1,000 per number per month. The payment is between the customer and Meta, and Luna does not intermediate it. Null means Luna has not read it yet. The route does not return the credential itself. The state of the customer's authorization comes back as credentialStatus, when you read a phone number. name is the WhatsApp Business account name as Meta reports it, null until Luna has read it. managerUrl is the address of the account in WhatsApp Manager, where the account owner resolves payment, verification and restrictions. phoneNumbers carries the account's numbers, each with id (the same as GET /v1/numbers), displayNumber, externalId and label, in the order they were connected; numbers stays as it was. --- # SaaS with N customers Fonte: https://lunahia.com.br/en/docs/saas-with-n-customers You have a product, your customers have businesses, and each business needs its own WhatsApp inside your product. On Luna, each business connects its own number (the “instance” is the number), and the thread that ties everything together is [`externalId`](https://lunahia.com.br/en/docs/glossary#externalid): the label you give the customer. It comes back on the link, the number, the key, the webhook and every number and link event. This guide follows the path of a SaaS that subscribes to 20 numbers. Each route’s contract, field by field, is in the [API reference](https://lunahia.com.br/en/docs/reference). This guide follows the order in which a product with many customers uses the routes. ## The thread: one externalId per customer The `externalId` is free text of 1 to 128 characters that Luna never interprets. Use the customer’s identifier in your system. It is born on the connect link, goes to the number when the customer connects, and from then on ties the rest together: | Where | What externalId does | | --- | --- | | `POST /v1/onboarding/links` | Tags the link and the number that results from it. | | Every number and link event | Comes in `number.external_id` (and in `link.external_id` on link events). Separates the customers on a single endpoint. Template events and the test event have no customer: see the table in section 3. | | The lists of numbers, messages, conversations and links | The `?externalId=` filter returns only what belongs to the customer, without you keeping a map of numbers. | | `POST /v1/api-keys` | ONE customer’s key: it only sees and uses their numbers. | | `POST /v1/webhooks/endpoints` | ONE customer’s endpoint (`externalIds`), if you prefer one URL per customer. | > A number connected through the console, without a link, is born without an `externalId`. Give it one with `PATCH /v1/numbers/{id}`; the same goes for reusing a number for another customer of yours. ## 1. The plan capacity The plan defines one thing: how many numbers the account keeps active at the same time. With 20 numbers subscribed, you connect 20 customers. `GET /v1/subscription` tells you the capacity and how many are in use, and the 21st link answers `409` with `error: "number_capacity_reached"`. To subscribe or increase it, write to contato@lunahia.com.br. Details in [Plan and numbers](https://lunahia.com.br/en/docs/plan-and-numbers). ```bash curl -X GET "https://api.lunahia.com.br/v1/subscription" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/subscription', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/subscription", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ## 2. One link per customer Create a link with the customer’s `externalId` and send the `url` to them. The `url` is returned **once**: keep it or send it right away. The customer opens Luna’s page, accepts Meta’s terms and connects their number. With `redirectUrl` (https), the page sends them back to your product when the connection ends. > **Testing on the free trial.** The trial has capacity for 1 number. If that number is already connected, `POST /v1/onboarding/links` answers `409` with `error: "number_capacity_reached"`, even with the right body: the capacity is checked before anything else. To see the link flow end to end, disconnect the number (`DELETE /v1/numbers/{id}`, see section 8) and create the link for the test customer, or ask for the capacity to be increased at contato@lunahia.com.br. ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/links" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "externalId": "cliente-42", "redirectUrl": "https://app.example.com/whatsapp/conectado" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/onboarding/links', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "externalId": "cliente-42", "redirectUrl": "https://app.example.com/whatsapp/conectado" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/onboarding/links", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "externalId": "cliente-42", "redirectUrl": "https://app.example.com/whatsapp/conectado", }, timeout=10, ) print(res.status_code, res.json()) ``` For all 20 customers at once, a loop over your list. The script below reads `customers.json`, creates one link per customer and prints the URLs; a capacity `409` shows up in the terminal and the loop goes on. create-links.mjs (Node 18 or newer) ```js // create-links.mjs: one connect link per customer of yours. import { readFile } from 'node:fs/promises'; const API = 'https://api.lunahia.com.br'; const customers = JSON.parse(await readFile('./customers.json', 'utf8')); // customers.json: [{ "externalId": "cliente-1" }, { "externalId": "cliente-2" }] for (const customer of customers) { const res = await fetch(`${API}/v1/onboarding/links`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ externalId: customer.externalId, // where the link page sends your customer back to when the connection ends redirectUrl: `https://app.example.com/whatsapp/done?customer=${customer.externalId}`, }), }); if (!res.ok) { // 409 number_capacity_reached: the plan is full. Disconnect a number or ask for more capacity. console.error(customer.externalId, res.status, await res.json()); continue; } const link = await res.json(); // The url is returned ONCE. Send it to the customer now. console.log(customer.externalId, link.url); } ``` When the connection ends, the page takes the customer to your `redirectUrl` and adds to the query `status` (the final state of the connection), `externalId` (the link label), `numberId` (the number, when Luna has already registered it; right after completing it is usually empty and is left out of the query) and `signature`: ```text https://app.example.com/whatsapp/conectado?status=APP_SUBSCRIBED&externalId=cliente-8841&signature=t%3D1793800000%2Cv1%3D9f2c... ``` ### Check that the return came from Luna Anyone can open your `redirectUrl` with an invented `status`. The `signature` proves Luna built those values: it is the **same signature as webhooks** (`t=,v1=`), made with the secret of the oldest webhook endpoint of your account (the same `whsec_` you already use to validate events), over the text `status=&numberId=&externalId=`, with the values as they are in the query (empty when absent). The instant is valid for 5 minutes: check when the customer arrives, not later. With no webhook endpoint registered, the `signature` is left out, and in that case treat the return as untrusted and read the state at `GET /v1/numbers`. ```js import { verifyLunaSignature } from './verify.mjs'; // the same check as a webhook, over the text the link page signed (the values as they are in the query) export function verifyConnectionReturn(returnUrl, secret, nowMs = Date.now()) { const q = new URL(returnUrl).searchParams; const text = `status=${q.get('status') ?? ''}&numberId=${q.get('numberId') ?? ''}&externalId=${q.get('externalId') ?? ''}`; return verifyLunaSignature(Buffer.from(text), q.get('signature'), secret, nowMs); } ``` ```python from urllib.parse import parse_qs, urlparse from verify import verify_luna_signature def verify_connection_return(return_url, secret, now=None): # the same check as a webhook, over the text the link page signed (the values as they are in the query) q = {k: v[0] for k, v in parse_qs(urlparse(return_url).query).items()} text = f"status={q.get('status', '')}&numberId={q.get('numberId', '')}&externalId={q.get('externalId', '')}" return verify_luna_signature(text.encode(), q.get("signature"), secret, now) ``` The customer can also be recognized on the page: send `displayName` (1 to 120 characters) in `POST /v1/onboarding/links` and it shows "WhatsApp connection for ..." above the title. **The name the Meta window shows cannot be changed:** the window is Meta’s and shows the name of Luna and of the business, not your customer’s. To find a customer’s link, filter by the label: ```bash curl -X GET "https://api.lunahia.com.br/v1/onboarding/links?externalId=cliente-42" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/onboarding/links?externalId=cliente-42', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/onboarding/links?externalId=cliente-42", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` The link is valid for 72 hours, opens once and is revoked with `DELETE /v1/onboarding/links/{id}`. More about the customer’s flow and about coexistence in [Connect a number](https://lunahia.com.br/en/docs/connect-a-number). ## 3. All the events on a single endpoint The recommended path is **one endpoint** for all customers. Register it as in [Receive events](https://lunahia.com.br/en/docs/receive-events), verify the signature, and separate the customers by `number.external_id`. Four events tell the story of a customer’s connection, and all of them carry the `externalId`: | Event | What it says | | --- | --- | | `onboarding.link.completed` | The customer completed the connection through a link. | | `onboarding.link.failed` | An attempt did not work out, with `reason` (abandoned, Meta error, number outside +55, registration blocked) and `step`, the screen where they stopped. | | `onboarding.link.expired` | The link expired unused. Create another. | | `number.connected` | The number is ready: it can send and receive now. | number.connected ```json { "version": "2026-11-10", "event_id": "458470a340db14358f03ac02fde7e3839cb6887f3071c06c57a3d9d456621996", "event_type": "number.connected", "occurred_at": "2026-10-07T13:45:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "coexistence": false } } ``` The router below is the part of your server that decides whom an event belongs to. Call it after verifying the signature; it drops repeats by `event_id` and ignores a label you do not know (answer `2xx` in every case). router.mjs ```js // router.mjs: one webhook endpoint for all your customers. // Call route(event) AFTER verifying the signature (see the Receive events guide). /** externalId -> { onEvent(event) } for each customer of yours. */ export function createRouter(handlers) { const seen = new Set(); return function route(event) { // The same delivery can arrive more than once: drop repeats by event_id. if (seen.has(event.event_id)) return 'duplicate'; seen.add(event.event_id); // number.external_id is on every event that goes through a number; // link events carry it in link.external_id. const customer = event.number?.external_id ?? event.link?.external_id ?? null; if (customer === null) return 'no-customer'; const handler = handlers.get(customer); // A label you do not know, or an event type you do not handle: answer 2xx anyway. if (handler === undefined) return 'unknown-customer'; handler.onEvent(event); return 'handled'; }; } ``` ### Where the externalId is in each event | Event | Where the externalId comes from | | --- | --- | | Messages and contacts: `message.received`, `message.status`, `message.echo`, `contact.*`, `backlog.dropped`, `history_sync.deadline_approaching` | `number.external_id` | | `number.*` (connected, disconnected, quality, payment, action, credential, name) and `account.*` | `number.external_id` | | `onboarding.link.completed` | `link.external_id`, and `number.external_id` of the number that just connected | | The other link ones: `onboarding.link.opened`, `onboarding.link.failed`, `onboarding.link.expired` | `link.external_id` (there is no number yet) | | Templates and the test: `template.status`, `template.category`, `template.quality`, `webhook.test` | Nowhere: they belong to the business account or to the test, not to a customer. The router returns `no-customer`, and only an unfiltered endpoint receives them. | The `number.external_id` is `null` on a number that never got a label. That case, and the events in the last row, are the router’s `no-customer`: handle them apart, or ignore them. > **A single endpoint is a single point of failure.** If it goes down or gets slow, the deliveries of **all** customers wait together: five failures in a row open that endpoint’s circuit breaker, and when it comes back everyone’s backlog arrives at once (see [Receive events](https://lunahia.com.br/en/docs/receive-events#retentativas)). With few customers and a server that only stores and answers `200`, this rarely weighs. If one customer’s code often fails or is slow, or if one customer cannot be delayed by another, use **one endpoint per customer** (section 7): one’s failure does not delay the others. ### A complete server in TypeScript The file below puts it all together: it verifies the signature, answers `200`, drops the repeat and hands each event to the right customer’s code, through a `Map`. The types show that `external_id` can be `null`. Run it with `node server.ts` (Node 24 or newer, which erases the types by itself) and `LUNA_WEBHOOK_SECRET` set. server.ts ```ts // server.ts: run with Node 24 or newer: node server.ts import crypto from 'node:crypto'; import http from 'node:http'; // The fields of the event that this file reads (there are more: see Receive events). interface LunaEvent { event_id: string; event_type: string; number?: { id: string; phone_number_id: string; external_id: string | null } | null; // external_id: null on a number that never got a label link?: { id: string; external_id: string | null } | null; } // 1. Verify the signature (see the Receive events guide for the explanation). const SECRET = process.env.LUNA_WEBHOOK_SECRET ?? ''; const TOLERANCE_SECONDS = 300; function verify(raw: Buffer, header: string | undefined): boolean { // raw: the exact bytes that arrived, never re-serialized JSON const m = /^t=(\d{1,15}),/.exec(header ?? ''); if (!m || !SECRET) return false; const t = Number(m[1]); if (Math.abs(Math.floor(Date.now() / 1000) - t) > TOLERANCE_SECONDS) return false; const expected = crypto.createHmac('sha256', SECRET).update(`${t}.`).update(raw).digest(); let ok = false; // during a secret rotation the header carries two v1 values: check them all for (const [, hex] of (header ?? '').matchAll(/v1=([0-9a-fA-F]{64})/g)) { if (crypto.timingSafeEqual(Buffer.from(hex as string, 'hex'), expected)) ok = true; } return ok; } // 2. The customers: externalId -> the code that handles that customer. type CustomerHandler = (event: LunaEvent) => void | Promise; const customers = new Map([ ['cliente-1', (event) => console.log('cliente-1', event.event_type)], ['cliente-2', (event) => console.log('cliente-2', event.event_type)], ]); const seen = new Set(); // in production: a database or Redis, with an expiry function route(event: LunaEvent): 'duplicate' | 'no-customer' | 'unknown-customer' | 'handled' { if (seen.has(event.event_id)) return 'duplicate'; seen.add(event.event_id); // number.external_id on events of a number; link.external_id on events of a link const customer = event.number?.external_id ?? event.link?.external_id ?? null; if (customer === null) return 'no-customer'; const handler = customers.get(customer); if (handler === undefined) return 'unknown-customer'; // a label you do not know: answer 2xx anyway void Promise.resolve(handler(event)).catch((err) => console.error(customer, 'handler failed', err)); return 'handled'; } // 3. The server: verify, answer, and only then route. http .createServer((req, res) => { const chunks: Buffer[] = []; req.on('data', (chunk: Buffer) => chunks.push(chunk)); req.on('end', () => { const raw = Buffer.concat(chunks); const header = req.headers['x-luna-signature']; if (!verify(raw, typeof header === 'string' ? header : undefined)) { res.writeHead(401).end(); return; } res.writeHead(200).end(); // answer first, work after console.log(route(JSON.parse(raw.toString('utf8')) as LunaEvent)); }); }) .listen(Number(process.env.PORT ?? 3000)); ``` ## 4. Send through a number Find the customer’s numbers by the label and send through one of them. `from` accepts Luna’s UUID or Meta’s id. `?canSend=true` returns only the numbers through which sending works now. ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers?externalId=cliente-42&canSend=true" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers?externalId=cliente-42&canSend=true', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/numbers?externalId=cliente-42&canSend=true", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "from": "YOUR_NUMBER_ID", "to": "5511900000000", "type": "text", "text": { "body": "Seu pedido saiu para entrega." } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID(), }, body: JSON.stringify({ "from": "YOUR_NUMBER_ID", "to": "5511900000000", "type": "text", "text": { "body": "Seu pedido saiu para entrega." } }), }); console.log(res.status, await res.json()); ``` ```python import os import uuid import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", "Idempotency-Key": str(uuid.uuid4()), }, json={ "from": "YOUR_NUMBER_ID", "to": "5511900000000", "type": "text", "text": { "body": "Seu pedido saiu para entrega.", }, }, timeout=10, ) print(res.status_code, res.json()) ``` History and conversations filter by customer too, and sending outside the 24-hour window is by template only. See [Send messages](https://lunahia.com.br/en/docs/send-messages) and [Templates](https://lunahia.com.br/en/docs/templates). With one business account per customer, `GET /v1/templates?wabaId=` or `?phoneNumberId=` shows each one’s templates. ```bash curl -X GET "https://api.lunahia.com.br/v1/messages?externalId=cliente-42&limit=20" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages?externalId=cliente-42&limit=20', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/messages?externalId=cliente-42&limit=20", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ## 5. Each number’s state To show the customer whether their number is fine, read `connection` (the same calculation that decides the events): `status` (`connected`, `connecting`, `action_required` or `disconnected`), `canSend` and `reasons`, each cause with `code`, `message` and `solution` in Portuguese, ready to pass on. ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` Response (trimmed) ```json { "id": "ed404df1-b420-4ed6-8743-ba1609892e0a", "metaPhoneNumberId": "123456789012345", "externalId": "cliente-42", "state": "REGISTERED", "ready": true, "connection": { "status": "connected", "canSend": true, "reasons": [] } } ``` You do not need to poll the 20 numbers: `number.action_required` announces when one starts needing action (authorization expiring, no payment method at Meta, restricted account), and `number.action_resolved` announces when it stops. The list of numbers accepts `?state=`, `?ready=`, `?canSend=`, `?limit=` and `?cursor=` to build the dashboard of all of them at once. number.action_required ```json { "version": "2026-11-10", "event_id": "8832cdd12544436fce3b39d709158baa046091d010b5ed144a289c81b807c710", "event_type": "number.action_required", "occurred_at": "2026-10-28T15:02:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "status": "action_required", "can_send": false, "reasons": [ { "code": "payment_required", "message": "A Meta recusou um envio deste número por falta de método de pagamento na conta de WhatsApp Business do negócio.", "solution": "O dono da conta cadastra o método de pagamento no WhatsApp Manager da Meta. A Luna não intermedeia esse pagamento. Quando um envio voltar a ser aceito, o aviso sai do ar." } ] } } ``` An authorization about to expire is the case that repeats: open a reconnection link with `POST /v1/onboarding/links` passing `numberId`, and the customer renews without counting a new number. The cases are in [Account health](https://lunahia.com.br/en/docs/account-health) and [Payment at Meta](https://lunahia.com.br/en/docs/payment-at-meta). ## 6. One key per customer If your customer’s customer reaches the API directly, or if you want to limit the damage of a leaked key, create a key with `externalId`. It only reads and sends through the numbers with that label (including the ones connected later), only creates links with it, only sees the templates and business accounts of those numbers, and **neither** lists nor creates webhook endpoints or keys, nor reads the plan. Another customer’s number answers `404`, the same as one that does not exist, even if its id is passed on purpose; a route outside the set answers `403`. A key’s `externalId` does not change: to change it, create another. **Whoever creates the key needs the `keys:write` scope.** The key you use to call `POST /v1/api-keys` must have it (in the console, the session gets that power for two hours after you confirm the password). Without the scope, the answer is `403`, and the body says which one is missing: `requiredScope: "keys:write"`. The new key’s scopes are chosen by you, within what a customer’s key can use (messages, numbers, templates and the connect link). ```bash curl -X POST "https://api.lunahia.com.br/v1/api-keys" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "label": "Clínica Exemplo", "scopes": [ "messages:read", "messages:write", "numbers:read" ], "externalId": "cliente-42" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/api-keys', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "label": "Clínica Exemplo", "scopes": [ "messages:read", "messages:write", "numbers:read" ], "externalId": "cliente-42" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/api-keys", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "label": "Clínica Exemplo", "scopes": [ "messages:read", "messages:write", "numbers:read", ], "externalId": "cliente-42", }, timeout=10, ) print(res.status_code, res.json()) ``` The `201` response carries the key’s `secret` (`hlsn_...`) **only once**: store it now, in your database, on that customer’s row, next to the `externalId`. No route returns it afterwards; if you lose it, revoke the key (`POST /v1/api-keys/{id}/revoke`) and create another. ## 7. One webhook per customer (optional) If your product prefers one URL per customer, the endpoint accepts `externalIds` (and `phoneNumberIds`): it only receives the events of numbers with that label, including the ones connected later, and its link events. Absent, it receives from all. `external_id` stays on every event, both ways. The signature, ordering, replay and rejected queue are those of any endpoint. ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://saas.example.com/luna/cliente-42", "externalIds": [ "cliente-42" ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "url": "https://saas.example.com/luna/cliente-42", "externalIds": [ "cliente-42" ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/webhooks/endpoints", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "url": "https://saas.example.com/luna/cliente-42", "externalIds": [ "cliente-42", ], }, timeout=10, ) print(res.status_code, res.json()) ``` ```bash curl -X PATCH "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "externalIds": [ "cliente-42", "cliente-43" ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "externalIds": [ "cliente-42", "cliente-43" ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "externalIds": [ "cliente-42", "cliente-43", ], }, timeout=10, ) print(res.status_code, res.json()) ``` > Each account can have up to **25 endpoints**, the same limit for everyone, an infrastructure one: one per customer of a 20-number plan, with headroom. An endpoint filtered to one customer does not receive another’s events; an event that does not say whom it is about only reaches an unfiltered endpoint. ## 8. Disconnect and swap the customer Customer 21 takes the place of customer 3? Disconnect customer 3’s number with `DELETE /v1/numbers/{id}`: it leaves Luna, stops counting against the capacity and the `number.disconnected` event announces it (`reason: "requested_by_tenant"`). Luna does not call `deregister` at Meta, so as not to take the customer’s number down on another provider or in the app. The history stays. To reuse a number for another customer of yours, change the label with `PATCH /v1/numbers/{id}`. ```bash curl -X DELETE "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID', { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status); ``` ```python import os import requests res = requests.delete( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code) ``` ```bash curl -X PATCH "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "externalId": "cliente-43" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "externalId": "cliente-43" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "externalId": "cliente-43", }, timeout=10, ) print(res.status_code, res.json()) ``` ## In one table | What your product does | How on Luna | | --- | --- | | Onboard a customer | `POST /v1/onboarding/links` with `externalId` and `redirectUrl` | | Know that they connected | `onboarding.link.completed` and `number.connected` | | Know that they gave up | `onboarding.link.failed` and `onboarding.link.expired` | | Send | `POST /v1/messages` with `from` (Luna UUID or Meta id) | | Receive from everyone | One endpoint and the `number.external_id` of each event | | Show the state | `connection` and `number.action_required` / `number.action_resolved` | | Give the customer direct access | `POST /v1/api-keys` with `externalId` | | One URL per customer | `externalIds` on the webhook endpoint | | Offboard a customer | `DELETE /v1/numbers/{id}` | | See the capacity | `GET /v1/subscription` | > Coming from Z-API or Evolution API? The [Coming from Z-API or Evolution](https://lunahia.com.br/en/migrate-from-evolution-api) page translates each instance verb into this list. ## Route details for this guide The [API reference](https://lunahia.com.br/en/docs/reference) says how to call each route, in a few lines. What explains the reason for each decision, the edge cases and the warnings is here, in the order of the reference. ### GET /v1/onboarding/links Each one carries the status (open, used, expired or revoked), the externalId you gave and, once the customer connects, the numberId of the resulting number. It also carries createdAt, purpose (new for a new number, reconnect to renew the authorization of a number that already exists), revokedAt, lastFailure (the last attempt that did not work out, with step, reason and at, the same as the onboarding.link.failed event, or null) and allowedActions (revoke, only on an open link). None carries the token or the url: it only came out at creation. Use ?externalId= to find the links of one of your customers: the comparison is exact, and a label with no link returns an empty list. Use ?status= (open, used, expired or revoked) to filter by state. Revoked links stay in the list. To page through results, send back the nextCursor from the previous response in cursor. Null means the end. ### POST /v1/onboarding/links Meta's connection window only opens on a domain registered in Luna's app. That is why the link points to a page on Luna's console, which shows your account name, explains what will be asked, and opens Meta's window for your customer. The person who signs in with Facebook and accepts Meta's terms is their business, and not you on their behalf. externalId is your own identifier for this customer, free text of 1 to 128 characters. It stays on the link and on the number that results from the connection, and comes back in GET /v1/numbers. redirectUrl, optional, is where the link page takes your customer when the connection ends (https). The page adds to the query status (the final state of the connection), externalId (the link label), numberId (the number, when Luna has already registered it; right after completing it is usually empty and is then left out, and the number.connected event announces when it is ready) and signature, the webhook signature over status, numberId and externalId with the secret of your oldest webhook endpoint, so you can check the return came from Luna (code in SaaS with N customers). Without redirectUrl, the customer stays on Luna's page. displayName, optional, is your customer's name (1 to 120 characters) that the link page shows so they recognize the request. The Meta window that opens next shows the name of Luna and of the business, and that name cannot be changed. The link cycle also arrives by webhook: onboarding.link.completed when the customer completes, onboarding.link.failed when an attempt does not work out (with the reason and the screen where they stopped) and onboarding.link.expired when the link expires unused, all with the externalId. The link is valid for 72 hours to be opened. The response carries the url once: keep it or send it now, because no route returns the token again. Whoever holds the url can connect a number to your account, so treat it as a secret and send it only to the right customer. numberId is optional and turns the link into a RECONNECTION link: your customer's page opens the renewal of that number's authorization directly, without counting a new number. Use it when credentialStatus is reauth_required, or when the number.credential_expiring event warns that the authorization expires within 14 days. The rules are those of POST /v1/onboarding/reconnect: a number that is yours and whose authorization admits reconnection (podeReconectar true); otherwise it answers 409, and a number that is not yours answers 404. Without externalId, the link inherits the number's. To follow along, use GET /v1/onboarding/links/{id}, or list numbers with ?externalId=. To cancel, use DELETE /v1/onboarding/links/{id}. The same conditions as POST /v1/onboarding/sessions apply here: the account must have its e-mail confirmed. ### GET /v1/onboarding/links/{id} What tells you your customer finished is the number.connected event, delivered to your webhook endpoint with the customer's externalId. This read is the fallback, for when your endpoint was down, and not a waiting loop: you do not need to poll. When the status becomes used, usedAt carries the instant and numberId carries the number that resulted. The numberId shows up a few moments after used, because Luna registers the number right after; null on a used link means the account was connected without a number. A link you revoked stays here, with status revoked and revokedAt. Whoever opens its url gets 404, as if it had never existed. ### DELETE /v1/onboarding/links/{id} It also works on a used or expired link, and then it only marks it revoked: the connected number and its externalId stay. The link stays in your list with status revoked. Revoking an already revoked link answers 404. ### GET /v1/public/onboarding-links/{token} The token is the credential, and there is no API key. An unknown, malformed or revoked token answers 404, always the same. An expired or already used link answers 200 with the status, so the page can tell the customer to ask for a new one. The route has a per origin address ceiling. ### POST /v1/public/onboarding-links/{token}/sessions It can be called more than once while the link is open: a customer who closes Meta's window tries again. An expired or already used link answers 410 with the reason. Any other invalid token answers 404. The route has a per origin address ceiling. ### POST /v1/public/onboarding-links/{token}/sessions/{sessionId}/complete It only completes a session opened by this same link. When the connection completes, the link becomes used, and its externalId goes to the number. If the chosen number is not +55, the state is COUNTRY_NOT_SUPPORTED, nothing is connected and the link stays open for a Brazilian number. It answers 200 even when a step fails: the body carries the state and the guidance. The route has a per origin address ceiling. ### POST /v1/public/onboarding-links/{token}/sessions/{sessionId}/abandon It does not change session state. The route has a per origin address ceiling. --- # Plan and numbers Fonte: https://lunahia.com.br/en/docs/plan-and-numbers Luna’s plan defines one thing only: how many numbers your account can keep active at the same time. This guide shows how to read that limit, what to do when it is reached, and how to open a slot. ## The free trial Every new account starts with a 14-day free trial, counted from the confirmation of the sign-up email, with capacity for 1 number. No manual release is needed: after confirming the email, the account connects the number by itself. Helsen can block an account, and the block stops writes and sending the same way the end of the trial does. Automatic billing does not exist yet. To subscribe to a plan, increase the capacity or lift the suspension, write to contato@lunahia.com.br. Use of Meta’s platform is paid by the business that owns the number, directly to Meta, and has no part in any of this. See [Meta costs](https://lunahia.com.br/en/docs/meta-costs). ## Read the plan and the usage `GET /v1/subscription` returns the account’s plan and how many numbers are in use, with nothing for your system to calculate. The scope is `numbers:read`. ```bash curl -X GET "https://api.lunahia.com.br/v1/subscription" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/subscription', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/subscription", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` An account on the free trial ```json { "planName": "Teste grátis", "status": "trial", "suspendedReason": null, "capacity": 1, "activeNumbers": 1, "canConnectNumber": false, "capacityLeft": 0, "capacityNotice": "Esta conta já tem 1 número ativo, o máximo contratado (1). Para conectar outro, desconecte um número (DELETE /v1/numbers/{id}) ou escreva para contato@lunahia.com.br.", "writesAllowed": true, "suspendedNotice": null, "pricePerMonth": null, "currency": null, "contactEmail": "contato@lunahia.com.br", "trialEndsAt": "2026-11-03T13:00:00.000Z", "trialDaysLeft": 5, "periodo": { "inicio": "2026-10-01T00:00:00.000Z", "fim": "2026-11-01T00:00:00.000Z" }, "numerosAtivos": 1, "phoneNumberIds": ["123456789012345"] } ``` | Field | What it says | | --- | --- | | `capacity` | How many numbers the account can keep active at the same time. | | `activeNumbers` | How many numbers are active right now. It is the count the capacity uses. | | `status` | `trial` (trial in progress), `active` (subscribed account), `suspended` (writes and sending paused) or `none` (email not yet confirmed). | | `suspendedReason` | When `status` is `suspended`: `trial_expired` (the trial ended) or `account_blocked` (Helsen blocked the account). | | `trialEndsAt` | When the trial ends. It stays filled in after the account is subscribed, as a record. | | `trialDaysLeft` | The days left until the trial ends, already calculated by the API. | | `planName` | The plan name: Teste grátis during the trial, and the name of the band that holds the capacity afterwards. | | `periodo` | The current period, calculated by the API. Show it as it came. | | `canConnectNumber` | Whether the account can open the connection of a new number now: email confirmed, account not suspended and a free slot in the capacity. It is the same decision the connection opening applies, so show or hide the button by this field. | | `capacityLeft` | How many numbers still fit in the capacity, never negative. Null before the account starts its plan. | | `capacityNotice` | When `canConnectNumber` is `false`, the refusal text, the same the API returns when you try to connect. Null when it can connect. | | `writesAllowed` | `false` only when the account is suspended. Reading, disconnecting a number and revoking a key remain valid. | | `suspendedNotice` | The suspension text, the same as the write refusals. Null when the account is not suspended. | | `pricePerMonth` e `currency` | The monthly value of the contracted capacity band, in reais. Helsen charges for number capacity and nothing else. Null during the free trial and above the last band (Sob consulta, on request). It is never zero. | | `contactEmail` | Helsen’s sales email, to subscribe, increase the capacity or lift the suspension. | When your system shows a usage bar, use `activeNumbers` and `capacity` as they came. A number waiting for the customer’s payment at Meta still counts, because the capacity is of configured numbers, not of numbers able to send right now. ## When the capacity is reached When `activeNumbers` reaches `capacity`, opening a connection session (`POST /v1/onboarding/sessions`) or creating a connect link (`POST /v1/onboarding/links`) answers `409` with `error: "number_capacity_reached"`. The refusal comes **before** the end customer opens Meta’s screen, because the code Meta hands over at the end of the connection is valid for 30 seconds, and Luna does not let your customer get that far just to refuse afterwards. `409` response ```json { "error": "number_capacity_reached", "message": "Esta conta já tem 1 número ativo, o máximo contratado (1). Para conectar outro, desconecte um número (DELETE /v1/numbers/{id}) ou escreva para contato@lunahia.com.br.", "capacity": 1, "activeNumbers": 1 } ``` - Reconnecting a number that already counts against the capacity is **not** refused: it adds none. - A capacity lower than the usage never disconnects anyone. Only the next connection is refused. - The two ways forward are to disconnect a number, or to increase the capacity with sales. **A connect link does not reserve a slot.** The check runs when the link is created and when the session is opened, and again when the number is registered, which is the moment it starts to count. If you create 20 links on an account with capacity 5, the first five customers to finish keep their numbers; the others stay `connecting`: the link becomes `used`, but the number neither counts nor sends, and Luna retries from time to time. If the capacity increases, they connect by themselves; if the retries run out first, the session ends as `FAILED`. Create links as slots are free in `GET /v1/subscription`, or increase the capacity before sending the links. So your end customer is never left waiting, count the slots before handing over each link: `capacityLeft` from `GET /v1/subscription` minus the new-number links still `open` in `GET /v1/onboarding/links?status=open`. Only hand the link over if a slot is left; if none is, increase the capacity first. A reconnection link for a number that already exists takes no new slot. ## Disconnect a number `DELETE /v1/numbers/{id}` takes the number off Luna and opens a slot at once. The scope is `numbers:write`. ```bash curl -X DELETE "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID', { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status); ``` ```python import os import requests res = requests.delete( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code) ``` - The number moves to `DISCONNECTED`, no longer sends, and stops counting against the capacity from that instant. - The `number.disconnected` event, with `reason: "requested_by_tenant"`, is delivered to your endpoints. See [Account health](https://lunahia.com.br/en/docs/account-health). - If it was the last Luna number in that business account, Luna also removes its subscription to the account, and Meta stops sending its events. - Luna does **not** deregister the number at Meta. Your customer’s number keeps working with the other provider or in their phone app. - The history stays. Messages and conversations remain at `GET /v1/messages`, and the number stays at `GET /v1/numbers`, with its `externalId` and `label`. - Repeating the call is safe: an already disconnected number answers `204` again, with no new event. If Meta is unavailable, the call fails without marking anything and can be repeated. - The route keeps working when the trial has ended, precisely to free a slot. ## Connect again To use a disconnected number again, connect it the same way as any number: a connect link or a session. See [Connect a number](https://lunahia.com.br/en/docs/connect-a-number). It counts against the capacity again, and opening the session is refused with `409 number_capacity_reached` if the account is full. ## Name a number `PATCH /v1/numbers/{id}` changes the `externalId` (your identifier for the customer who owns the number) and the `label` (a free, short name, 1 to 128 characters, so you recognize the number). Send only what you want to change: an absent field stays as it is, and `null` clears the field. With `autoRead: true`, Luna marks as read, at Meta, every message the number receives from then on, with no typing indicator, a few seconds after it arrives; the default is `false`, and the field appears in `GET /v1/numbers`. The scope is `numbers:write`, and the response is the whole number. ```bash curl -X PATCH "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "externalId": "cliente-8841", "label": "Atendimento Pinheiros" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "externalId": "cliente-8841", "label": "Atendimento Pinheiros" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "externalId": "cliente-8841", "label": "Atendimento Pinheiros", }, timeout=10, ) print(res.status_code, res.json()) ``` ## When the trial ends Three days before the end, Luna emails the person responsible for the account. With the trial ended and the account not subscribed, `status` becomes `suspended` with `suspendedReason: "trial_expired"`. ### Keeps working - Reading your data (`GET`), including messages, numbers and this plan. - Receiving what arrives and delivering it to your webhook. - The number stays connected at Meta. - Disconnecting a number, to free a slot. ### Pauses, with `403` - Sending messages and the other writes. - Opening a connection session or creating a link. - Messages already in the outbound queue: they are refused, with the same reason. `403` response with the trial ended ```json { "error": "trial_expired", "message": "O teste grátis desta conta terminou. O envio de mensagens e as demais escritas estão pausados até a conta ser contratada. Você continua lendo os seus dados, o número segue conectado na Meta e o que chega continua sendo recebido e entregue ao seu webhook. Para continuar, escreva para contato@lunahia.com.br." } ``` To continue, write to contato@lunahia.com.br. When the account is subscribed, the suspension is lifted and sending resumes, with nothing for your system to redo. The same error body, with `account_blocked`, applies to an account blocked by Helsen. The full list of errors is in [Errors](https://lunahia.com.br/en/docs/errors). > See [the API reference](https://lunahia.com.br/en/docs/reference) for the full fields of each route in this guide. ## Route details for this guide The [API reference](https://lunahia.com.br/en/docs/reference) says how to call each route, in a few lines. What explains the reason for each decision, the edge cases and the warnings is here, in the order of the reference. ### GET /v1/numbers Two fields that look alike and are not: throughputLevel is SPEED, how many messages per second Meta processes; limiteDiarioDeConversas is Meta's MESSAGING LIMIT, set for the business portfolio and not for each number: it counts unique people the business writes to outside the customer service window, in the tiers TIER_250, TIER_2K, TIER_10K, TIER_100K and TIER_UNLIMITED. Neither replaces the other, and neither one counts what has already been used. throughputLevel describes a progression Meta raises on its own as the number builds quality. Not every number follows that progression: a number connected through coexistence has a FIXED ceiling that never goes up. The field that tells you which case you are in is tetoDeVazaoPorSegundo, and it comes out when you read one number and its health, not on this list. podeRetentar tells you whether the state allows another connection attempt. The decision belongs to the platform and not to you, because each registration attempt spends a quota Meta counts per number over a 72 hour window. Exhausting that quota on Meta's side locks the number until the window rolls. orientacao carries, in Portuguese, what is happening with the connection and what to do about it. It is written for you to pass on to your own customer without rewriting it. externalId is the label you gave your customer on the connect link. Use ?externalId= to list only that customer's numbers: the comparison is exact and case sensitive, and a label with no number returns an empty list. connection is the summary state, computed by the API: status (connected, connecting, action_required or disconnected), canSend (whether sending will work now) and reasons, the list of causes with code, message and solution, ready for you to pass on to your own customer. It is what you show on their dashboard instead of combining several fields. ready is the readiness verdict: the number is registered and the app subscription was confirmed. To filter, use ?state= (the number's state), ?ready= and ?canSend= (true or false). To page through results, use ?limit= (1 to 100, 50 if omitted) and send back the nextCursor of the previous response in ?cursor=; null means the end. The cursor is opaque: it carries position, not a count. ### GET /v1/numbers/{id} tetoDeVazaoPorSegundo is the field that tells a ceiling that goes up apart from a ceiling that does not. throughputLevel describes the progression Meta grants as the number builds quality, and it rises over time. A number connected through coexistence, which keeps working in the business phone app, has a fixed ceiling and never enters that progression. With a value, this field gives you that fixed ceiling in messages per second; null, the progression applies and throughputLevel is what describes it. The value comes from what the platform observed in this number traffic, and not from the label Meta returned. sincronizacaoDoHistorico tracks the import of the phone previous conversations on a number connected through coexistence, and there are FOUR situations, not three. Null means there is no import for this number. em_curso means it is running, and sincronizacaoPrazo tells you until when: past that instant without finishing, Meta disconnects the end business. concluida means it finished, and the older conversations already show up in GET /v1/messages. recusada means the business owner declined to share on the phone, so it will not finish and asking again changes nothing. Do not read the percentage on its own. sincronizacaoProgresso is a label Meta assigns, and one hundred per cent does NOT mean success: a refusal arrives carrying whatever progress had already been recorded. What tells you the outcome is sincronizacaoDoHistorico, and nothing else. And absence is not zero progress: null means there is no import, zero means one started and has not moved yet. When Meta refuses sending because the end business has no payment method, the number stays registered and sends nothing. That is not a platform error and there is nothing to do on Helsen's side: the orientacao field says what is missing and where it gets resolved, in text ready for you to pass on to your customer. The awaitingPaymentSince field carries the instant the refusal was seen, and is null when there is no wait. Meta does not announce when payment is fixed and offers no lookup: it only goes back to null when a later send is accepted. The number.payment_required and number.payment_resolved events announce both transitions. waba carries the state of the number's business account: restricted and disabled, read from Meta's last notice; credentialExpiresAt and credentialNeverExpires, until when the authorization the customer gave Luna is valid; and paymentMethodOnMeta and currency, the account's payment method at Meta (without it, Meta stops delivering service messages after the allowance of 1,000 per number per month). They belong to the account and hold for all its numbers; the details are in GET /v1/business-accounts. connection is the summary state of the connection: status, canSend and reasons (code, message and solution of each cause). It is the same calculation that decides the number.action_required and number.action_resolved events. subscriptionConfirmedAt is the field that matters most here. It records when the app's subscription to the account was confirmed by reading it back. Without that subscription no event ever arrives, and the failure is silent: the number looks perfect and receives nothing. credentialStatus tells you whether the customer's authorization is still valid. When it dies, the number has to be reconnected. coexistence and ready are ready-made booleans. coexistence is true once Luna has observed coexistence traffic on this number (the same rule as the number.connected event, and it can turn from false to true after the connection). ready is true when the number is registered and the subscription is confirmed, that is, when sending is enabled: use this field instead of combining state and subscriptionConfirmedAt. ### PATCH /v1/numbers/{id} externalId is your identifier for the customer that owns the number, 1 to 128 characters. It is the thread that ties the number to your customer: ?externalId= on GET /v1/numbers, the number.connected event and the ones after it carry the same value. label is a free, short name, 1 to 128 characters, so you can recognize the number. Luna interprets neither. Send only what you want to change. An absent field stays as it is, and null clears it. The body needs at least one of the two. Repeating the same request leaves the same state. The response is the whole number, as in GET /v1/numbers/{id}. A number that is not yours answers 404, the same as a number that does not exist. ### DELETE /v1/numbers/{id} What happens: the number moves to the DISCONNECTED state, stops sending, and the number.disconnected event, with reason requested_by_tenant, is delivered to your endpoints. If it was the last Luna number on that business account, Luna also removes its subscription on the account, and Meta stops sending its events. What does NOT happen: Luna does not deregister the number at Meta. Your customer's number keeps working on the other provider or on their phone app, and stays registered at Meta. History stays: messages and conversations are still in GET /v1/messages, and the number is still in GET /v1/numbers with its externalId and label. To use the number again, connect it again with a connect link (POST /v1/onboarding/links) or with POST /v1/onboarding/sessions. That counts toward the capacity again, and is refused with 409 number_capacity_reached if the account is full. Repeating the call is safe: a number already disconnected answers 204 again, with no new event. If Meta is unavailable, the call fails without marking anything and can be repeated. The route keeps working with the free trial over, precisely to free a slot. A number that is not yours answers 404, the same as a number that does not exist. --- # Receive events Fonte: https://lunahia.com.br/en/docs/receive-events Luna delivers to your server everything that arrives on your numbers and every state change of the messages you sent. Each delivery is a `POST` with a JSON body and a signature that proves the origin. This guide shows how to receive, verify and handle it. ## Register the endpoint In the console, use **Integração** (Integration), **Webhooks**. Through the API, `POST /v1/webhooks/endpoints` with the `webhooks:write` scope: ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/webhooks/luna" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "url": "https://example.com/webhooks/luna" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/webhooks/endpoints", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "url": "https://example.com/webhooks/luna", }, timeout=10, ) print(res.status_code, res.json()) ``` `201` response ```json { "id": "5c0e9a52-3a0e-4c3f-9f3e-0b3f6f1a2c77", "url": "https://example.com/webhooks/luna", "createdAt": "2026-10-06T14:00:00.000Z", "updatedAt": "2026-10-06T14:00:00.000Z", "previousSecretExpiresAt": null, "paused": false, "pausedAt": null, "lastDeliveryAt": null, "lastFailureAt": null, "lastHttpStatus": null, "secret": "whsec_EXAMPLE_NOT_A_REAL_SECRET" } ``` - The `secret` appears in this response and in the rotation’s, and in no other. Luna keeps only its encrypted form. If you lose it, rotate to get a new one. - The URL must use `https`, with no embedded user and password, and must point to a public address on the internet. - Internal-network, loopback and cloud-metadata addresses are refused at registration **and** at each delivery, because a name can change address between registration and the call. - Luna does not follow redirects. Register the final URL. - `GET /v1/webhooks/endpoints` lists what exists (`webhooks:read` scope). Whoever has not registered one yet gets `200` with an empty list, not `404`. ```bash curl -X GET "https://api.lunahia.com.br/v1/webhooks/endpoints" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/webhooks/endpoints", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ## Change the URL, pause, test and remove All of this is also possible in the console, under **Integração** (Integration), **Webhooks**. Through the API, the routes need the `webhooks:write` scope. An endpoint that is not yours answers `404`, the same as one that does not exist. - Each customer can have up to **25 endpoints**, and each event is delivered to all the active ones that accept it. A registration above the limit answers `409` with `error: "webhook_endpoint_limit"`. The limit is an infrastructure one and is the same for everyone, and removing an endpoint frees the slot. - The endpoint representation carries the state: `paused` and `pausedAt`, and the trace of the last delivery, in `lastDeliveryAt` (the last one your server accepted), `lastFailureAt` (the last one it did not accept) and `lastHttpStatus` (the status of the last attempt, or `null` if the server did not respond). They are instants and a status, not a history: Luna does not count deliveries. The trace is written at most every 10 seconds per endpoint. The history, attempt by attempt, is in `GET /v1/webhooks/endpoints/{id}/deliveries`. - If your server sits behind a gateway that requires a fixed token, register own headers in `headers`, on the `POST` or the `PATCH`: `{ "headers": { "X-Gateway-Token": "TOKEN" } }`, up to **5**. Luna sends them on every delivery to that endpoint, the test event included. The name must be a valid HTTP header name and cannot be a transport one (`content-type`, `host`, `content-length` and the like) or `x-luna-*`; the value has up to 1024 visible ASCII characters. The **values are secret**: they stay encrypted and no response returns them, only the names, in `headerNames`. On the `PATCH`, the object you send replaces the previous one and `{}` removes them all. The `X-Luna-Signature` signature, with timestamp, remains the proof of origin: the own header is only there to get through the gateway. - `GET /v1/webhooks/endpoints/{id}/deliveries` lists the delivery attempts to the endpoint over the **last 7 days**, newest first, one row per attempt: `eventId`, `eventType`, `status` (`success` or `failed`), `httpStatus` (`null` when your server did not respond), `durationMs`, `attempt` and `at`. Filters: `status`, `eventType` and `since`. It pages by `cursor`, with no total. It is metadata only: it does not carry the body sent or what your server answered. The console shows the same list on the endpoint, under **Integração** (Integration), **Webhooks**. ### Change the URL `PATCH /v1/webhooks/endpoints/{id}` with the new `url`. It goes through the same validation as registration (`https` and a public address). **The secret stays the same**: you point to another server without reconfiguring verification. Changing the URL clears `lastDeliveryAt`, `lastFailureAt` and `lastHttpStatus`, because they described the old server. The response is the endpoint, as in `GET`. ```bash curl -X PATCH "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/webhooks/luna-novo" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "url": "https://example.com/webhooks/luna-novo" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "url": "https://example.com/webhooks/luna-novo", }, timeout=10, ) print(res.status_code, res.json()) ``` ### Pause and resume With `paused: true` the endpoint stops receiving. **The events that occur during the pause are not delivered afterwards**: pausing does not postpone, it discards. Whatever was already queued for it is discarded too. With `paused: false` it receives again whatever occurs from that moment on. If you only want to check your setup without losing anything, use the test below. ```bash curl -X PATCH "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "paused": true }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "paused": true }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "paused": True, }, timeout=10, ) print(res.status_code, res.json()) ``` ```bash curl -X PATCH "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "paused": false }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "paused": false }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "paused": False, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Choose the event types By default the endpoint receives **all** types, including the ones Luna creates later. With `eventTypes` you choose which ones it receives, at registration (`POST /v1/webhooks/endpoints`) or later (`PATCH /v1/webhooks/endpoints/{id}`). The list you send **replaces** the previous one, and an empty list goes back to receiving all. The filter is by type only, never by content, conversation or sender, and holds from then on: what happened before and was filtered is not delivered afterwards. The endpoint representation returns `eventTypes`, with an empty list when it receives all. `GET /v1/webhooks/event-types` lists the types `eventTypes` accepts, each with a sentence. ```bash curl -X PATCH "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "eventTypes": [ "message.received", "message.status", "account.restricted", "account.disabled" ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "eventTypes": [ "message.received", "message.status", "account.restricted", "account.disabled" ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "eventTypes": [ "message.received", "message.status", "account.restricted", "account.disabled", ], }, timeout=10, ) print(res.status_code, res.json()) ``` With many customers, the endpoint can also be limited to **customers** and **numbers**: `externalIds` (the labels you gave the customers) and `phoneNumberIds` (Luna’s UUID or Meta’s id; the response returns Meta’s ids, the same as `phone_number_id`). With the list filled in, the endpoint only receives the events of numbers with one of these labels or ids, including the ones connected later (`externalIds`), and their link events. Absent or empty, it receives from all. The filter applies where events are published, like the type one, and an event that does not say whom it is about only reaches an unfiltered endpoint. It is how you get one URL per customer; the recommended path is still a single endpoint, separating by `number.external_id`. See [SaaS with N customers](https://lunahia.com.br/en/docs/saas-with-n-customers). > **With the list filled in, a new type does not reach you until you add it.** Whoever wants everything leaves `eventTypes` empty. `webhook.test` is not in the list: it only goes out when you ask for the test. ### Webhook per number (like the “instance” on other platforms) If you come from Z-API, Evolution or uazapi, you are used to giving each instance its own webhook URL. On Luna the number is the instance, and the same `POST /v1/webhooks/endpoints` accepts `phoneNumberIds`: the endpoint receives only the events of those numbers. Pass Luna’s UUID (the `id` from `GET /v1/numbers`) or the `metaPhoneNumberId`; a number that is not in the account answers `400`. ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/webhooks/numero-1", "phoneNumberIds": [ "YOUR_PHONE_NUMBER_ID" ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "url": "https://example.com/webhooks/numero-1", "phoneNumberIds": [ "YOUR_PHONE_NUMBER_ID" ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/webhooks/endpoints", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "url": "https://example.com/webhooks/numero-1", "phoneNumberIds": [ "YOUR_PHONE_NUMBER_ID", ], }, timeout=10, ) print(res.status_code, res.json()) ``` To change the URL of just that number later, update its endpoint with `PATCH /v1/webhooks/endpoints/{id}` and the new `url` (the `id` is in `GET /v1/webhooks/endpoints`). The other endpoints do not change. Numbers that are in no filter keep reaching only the unfiltered endpoints. ```bash curl -X PATCH "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/webhooks/luna-novo" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "url": "https://example.com/webhooks/luna-novo" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "url": "https://example.com/webhooks/luna-novo", }, timeout=10, ) print(res.status_code, res.json()) ``` For numbers that are **still to be connected**, the id does not exist yet and `phoneNumberIds` will not do. Give the customer an `externalId` (when creating the connect link, or later with `PATCH /v1/numbers/{id}`) and register the endpoint with `externalIds`: it receives from every number with that `externalId`, including the ones connected later. If both lists are filled in, a number belongs to the endpoint if it matches either one. ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/webhooks/cliente-42", "externalIds": [ "cliente-42" ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "url": "https://example.com/webhooks/cliente-42", "externalIds": [ "cliente-42" ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/webhooks/endpoints", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "url": "https://example.com/webhooks/cliente-42", "externalIds": [ "cliente-42", ], }, timeout=10, ) print(res.status_code, res.json()) ``` In the console the same is under **Integração** (Integration), **Webhooks** (each address says whom it serves) and in each number’s detail, in the **Avisos deste número** (this number’s notices) section. ### Send a test event `POST /v1/webhooks/endpoints/{id}/test` sends **one** `webhook.test` event now, signed, with the same headers, the same signature and the same destination defenses as a real delivery, and returns the result in the response itself. It works on a paused endpoint, which is the point: check before resuming. The test writes nothing to the endpoint, so `lastDeliveryAt` keeps talking about real deliveries. To exercise your code with another type, send `{ "eventType": "number.action_required" }` (any type from `GET /v1/webhooks/event-types`): Luna delivers an example of that type, with a made-up body and `test: true` in the envelope. Check that field before acting on the event: it never comes on a real event. The simulated events of [Test mode](https://lunahia.com.br/en/docs/test-mode) also come with `test: true`. `GET /v1/webhooks/endpoints` carries `limit` (the maximum number of endpoints), `canCreate` and, on each endpoint, `deliveryStatus` (`ok`, `failing`, `paused` or `never_delivered`), and the type list groups each one in `group` and `groupLabel`. ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID/test" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID/test', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID/test", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` `200` response ```json { "delivered": true, "statusCode": 200, "durationMs": 184, "failure": null } ``` | Field | What it is | | --- | --- | | `delivered` | `true` when your server answered `2xx`, the same criterion as a real delivery. | | `statusCode` | The status your server returned, or `null` if there was no response. | | `durationMs` | How long the call took, in milliseconds. | | `failure` | `null` when delivered. Otherwise, one of: `timeout` (the server did not answer in time), `connection` (could not connect: DNS, TLS or a closed port), `destination_not_allowed` (the URL no longer points to a public address), `response_too_large` (the response went over the size Luna reads) or `http_status` (the server answered outside `2xx`, including a redirect, which Luna does not follow). | The body your server answered does not come back, on purpose. The limit is **5 tests per minute per customer**, the same for everyone, because each call is an outbound request to your server. Above that, `429` with `Retry-After`. ### Remove `DELETE /v1/webhooks/endpoints/{id}` answers `204`, and the endpoint stops receiving. The events that were already queued for it are discarded when they arrive, not redelivered. The rejected-queue items that pointed to it are deleted along with it, because with no endpoint there is nowhere to requeue them. **This cannot be undone**, and the secret is lost too. To stop receiving without losing anything, pause. ```bash curl -X DELETE "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID', { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status); ``` ```python import os import requests res = requests.delete( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code) ``` ### Developing on your machine Luna only accepts a public `https` URL, so `http://localhost:3000` is refused. To develop on your machine, expose your local server through an https tunnel (any tunnel service works), register the public URL it gives you and use `PATCH` to change the URL when the tunnel changes. The secret stays the same. To stop receiving while the tunnel is closed, pause the endpoint. ## How Luna delivers - Each delivery is a `POST` to your URL, with `Content-Type: application/json` and the `X-Luna-Signature` header. - Any `2xx` answer counts as delivered. Luna waits up to **10 seconds** for the answer. - Anything else counts as a failure: `4xx`, `5xx`, a `3xx` redirect, a timeout and a connection error. - The body of your answer is discarded. A body above 64 KB counts as a failure, so answer empty. - Answer first and work afterwards. If your handling is slow, write the event to a queue of your own and return `2xx` right away. ## The delivery guarantees They are written without euphemism, because whoever pays for a duplicate is your product’s end consumer: - Delivery is at-least-once: the same delivery can arrive more than once, and this happens in practice, not just in theory. A timeout reached after your server has already processed the request produces exactly that case. - Order is guaranteed within a conversation, and template.status events are ordered among themselves per business account, since a template belongs to no conversation, template.category and template.quality events join that same order, and number and account events (number.* and account.*) are ordered among themselves per number. It is not guaranteed across conversations: two events from different conversations can arrive in any order, and an event from a slow conversation can arrive after a newer event from another one. - Idempotency is your duty, and the event_id is what the platform gives you to fulfil it. It is stable: the same delivery, repeated, carries the same event_id. Keep the ones you have processed and drop the repeats. - If your endpoint stays down for too long, the platform drops what piled up, and you lose those events: they will not be resent. When that happens you receive a backlog.dropped event stating how many were dropped and for what period. That notice is not dropped along with the backlog it describes. - New event types can appear without the contract version changing. If your server receives an event_type it does not know, answer 2xx and ignore the event. The version only changes when the shape of an existing type changes, and that comes with notice and a deadline. - On a number connected in coexistence, if the import of earlier conversations is still in progress when its deadline approaches, you receive a history_sync.deadline_approaching event carrying the number and the deadline as an instant. That deadline is the platform's estimate: 24 hours from when it saw the import begin. Meta's own clock starts slightly earlier, so treat the instant as a limit and act with margin. Once the deadline passes without completion, the Meta platform disconnects the end business and it has to redo the connection on the device. The notice is sent before the deadline and never after, and there is a single one for the number: like any delivery, it can repeat, always with the same event_id, and a number that redoes the connection later does not receive a second notice. The current state of the import is at GET /v1/numbers/{id}/health. ## The events Every event has the same envelope, and `event_type` says which type it is. The examples below are built from the published contract: | Field | What it is | | --- | --- | | `version` | The contract version, a date (today `2026-11-10`). It only changes when the shape of an existing type changes, and that comes with notice and a deadline. A new event type does not make it rise. The `2026-10-28` version added the `number` object to every event, explained below, and `2026-11-04` added `unsupported`, `edit`, `revoke` and `order` to the content of `message.received` and `message.echo`; if you read the JSON ignoring the fields you do not know, you do not need to change anything. | | `event_id` | The event’s stable identifier, 64 hexadecimal characters. The same delivery, repeated, carries the same `event_id`. Use it to drop repeats. | | `event_type` | `message.received`, `message.status`, `message.echo`, `contact.identity_changed`, `contact.preferences_changed`, `backlog.dropped`, `history_sync.deadline_approaching`, `template.status`, `template.category`, `template.quality`, `number.connected`, `number.disconnected`, `number.quality_changed`, `number.display_name_reviewed`, `number.credential_expiring`, `number.payment_required`, `number.payment_resolved`, `number.action_required`, `number.action_resolved`, `onboarding.link.opened`, `onboarding.link.completed`, `onboarding.link.failed`, `onboarding.link.expired`, `account.restricted`, `account.violation`, `account.disabled`, `account.reinstated`, `account.update`, `account.limit_changed`, `account.alert` or `webhook.test`. | | `occurred_at` | When the event occurred, in ISO 8601, UTC, with milliseconds and the trailing `Z`. | | `phone_number_id` | The number’s identifier at Meta, the same `metaPhoneNumberId` that `GET /v1/numbers` returns. It is `null` in `webhook.test`, which does not go through any number, and in template events, because a template belongs to the business account. | | `number` | The number the event went through: `id` (Luna’s, the same as in `GET /v1/numbers`), `phone_number_id` (Meta’s) and `external_id` (the label you gave your customer, or `null`). It is in every event that goes through a number, and it is `null` in `webhook.test` and in template events. In `number.*` events the same object also carries the event’s own fields. | ### Separate the events of each of your customers With many customers, the recommended way is **one endpoint** for all of them. Every event already says whose it is: `number.external_id` is the label you gave the customer when creating the connect link (or in `PATCH /v1/numbers/{id}`), and `number.id` and `number.phone_number_id` are the number’s two identifiers. Your server reads `external_id`, finds the customer and hands the event to their code. `external_id` is `null` on a number that never got a label; give it one with `PATCH /v1/numbers/{id}`. Routing by external_id (Node) ```js // external_id -> the function that handles that customer const handlers = new Map(); function handle(event) { const customer = event.number?.external_id; const handler = customer ? handlers.get(customer) : undefined; // no label, or an event you do not handle: answer 2xx and ignore if (!handler) return; handler(event); } ``` ### `message.received` A message that arrived from a correspondent, **complete**: the text, and also the button they tapped, the media with its caption, the location, the contacts, the reaction, the answer to a Flow, an order from a catalog, the edit or deletion of a message, the notice of a type the Cloud API does not deliver, the message they quoted, the ad they came from and the name they display. Every field is always present, and is null when it does not apply to the type. Text ```json { "version": "2026-11-10", "event_id": "a2f4909b0fd2db8ab8b1bfe4e16487f49b86113e27bf8c3c9d10a2d0fefebc72", "event_type": "message.received", "occurred_at": "2026-10-06T14:02:11.482Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "b6d84033-a8e8-4db9-aab6-565ce203cc51", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "text", "text": "Oi! Queria saber o status do meu pedido.", "profile_name": "Maria Souza", "media": null, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` A tap on a reply button of a message you sent. The `id` you gave the button comes back in `message.interactive.id`, and `message.context.wamid` is the message that had the buttons. `text` stays null: the button’s title is in `interactive.title`. Button tap ```json { "version": "2026-11-10", "event_id": "1fd66b6f86489c36c3552f14dbf49f50df6b2d946c259f7b0eaa0ef88f58adb5", "event_type": "message.received", "occurred_at": "2026-10-06T14:05:40.120Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "7d1c4b8e-2a3f-4e5d-9c6b-1f0a2b3c4d5e", "wamid": "wamid.EXAMPLE_BUTTON_CLICK", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "interactive", "text": null, "profile_name": "Maria Souza", "media": null, "interactive": { "type": "button_reply", "id": "rastrear", "title": "Rastrear pedido", "description": null, "name": null, "response_json": null }, "button": null, "location": null, "contacts": null, "reaction": null, "context": { "wamid": "wamid.EXAMPLE_MESSAGE_WITH_BUTTONS", "from": "5511900000001", "forwarded": null, "frequently_forwarded": null }, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` An image with a caption. The caption is in `message.media.caption`, not in `text`, so you do not treat it as a text message. The file comes from the link in `message.media.url`, which downloads **without an API key** (see [Send messages](https://lunahia.com.br/en/docs/send-messages#midia)), or from `GET /v1/messages/{id}/media`, with a key and the event’s `message.id`. Image with caption ```json { "version": "2026-11-10", "event_id": "0ab56cecd18b825ebeb4548219cb8fe392fec9e56301e52be1086f3c734ace86", "event_type": "message.received", "occurred_at": "2026-10-06T14:07:03.900Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "4c9e2d1a-8b7f-4a6c-b5d3-0e1f2a3b4c5d", "wamid": "wamid.EXAMPLE_IMAGE", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "image", "text": null, "profile_name": "Maria Souza", "media": { "mime_type": "image/jpeg", "sha256": "EXAMPLE_SHA256_OF_THE_FILE", "caption": "A nota fiscal do pedido", "filename": null, "voice": null, "animated": null, "url": "https://api.lunahia.com.br/v1/media/6f1a2b3c-4d5e-4f60-8a7b-9c0d1e2f3a4b.EXEMPLO_DO_SEGREDO_DE_43_CARACTERES_AAAAAAAA" }, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` Someone who adopted a WhatsApp username can write **without the phone number showing**. In that case `message.wa_id` is **null** and the correspondent is `message.user_id`, the BSUID. Treat `wa_id` as optional and `user_id` as the contact key when the phone is missing. The guide [Users without a phone number (BSUID)](https://lunahia.com.br/en/docs/users-without-phone) explains what changes in your system. Without a phone number (BSUID only) ```json { "version": "2026-11-10", "event_id": "e2f81dd079e4419dac363779655be694a25cc502b7646be51cdac4b0cfc276fb", "event_type": "message.received", "occurred_at": "2026-11-03T14:02:11.482Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "c8a1e5d2-6f3b-4a7c-9e0d-1b2c3d4e5f60", "wamid": "wamid.EXAMPLE_NO_PHONE", "wa_id": null, "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": "mariasouza", "type": "text", "text": "Oi! Queria saber o status do meu pedido.", "profile_name": "Maria Souza", "media": null, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` The answer to a Flow you sent arrives as `interactive` with `type: "nfm_reply"`. The answers are in `message.interactive.response_json`, **as JSON text, uninterpreted**: run `JSON.parse` on your side, and use the `flow_token` you sent to know which send it belongs to. Flow answer ```json { "version": "2026-11-10", "event_id": "b9714a025db0a22bd3a63f9dfd9aa52aed7ddcae4efde825dfb2fa41e1736dd2", "event_type": "message.received", "occurred_at": "2026-11-04T14:12:30.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "a4b9d2e3-6c7f-4081-9bac-1d2e3f4a5b6c", "wamid": "wamid.EXAMPLE_FLOW_REPLY", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "interactive", "text": null, "profile_name": "Maria Souza", "media": null, "interactive": { "type": "nfm_reply", "id": null, "title": null, "description": null, "name": "flow", "response_json": "{\"flow_token\":\"EXAMPLE_FLOW_TOKEN\",\"nome\":\"Maria Souza\",\"data\":\"2026-11-10\"}" }, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` An order built in a catalog arrives with `type: "order"` and the items in `message.order.items`. Quantity and price come out as text, the way Meta sent them. Luna only delivers the order: it does not charge, does not compute a total and never handles the money. Catalog order ```json { "version": "2026-11-10", "event_id": "1eaa360e693d1a7366e66ba81d7bee362a56c2b4f4ef4854e43ad35861bd7ae1", "event_type": "message.received", "occurred_at": "2026-11-04T14:10:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "f3a8c1d2-5b6e-4f70-8a9b-0c1d2e3f4a5b", "wamid": "wamid.EXAMPLE_ORDER", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "order", "text": null, "profile_name": "Maria Souza", "media": null, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": { "catalog_id": "EXAMPLE_CATALOG_ID", "text": "Quero estes dois, por favor.", "items": [ { "product_retailer_id": "sku-001", "quantity": "2", "item_price": "49.90", "currency": "BRL" }, { "product_retailer_id": "sku-002", "quantity": "1", "item_price": "15.00", "currency": "BRL" } ] } } } ``` | `message` field | What it is | | --- | --- | | `id` | The message’s identifier at Luna, a UUID. It is the `id` that `GET /v1/messages/{id}/media`, `POST /v1/messages/{id}/read`, `POST /v1/messages/{id}/typing` and `POST /v1/messages/{id}/replay` take. | | `wamid` | The message’s identifier at Meta. | | `wa_id` | The correspondent’s phone number at Meta, in E.164 without the plus sign. **It can be null**: when the user wrote without the phone number showing, use `user_id`. | | `user_id` | The correspondent’s BSUID, as Meta sent it (for example `US.13491208655302741918`). Null when Meta has not sent it for this conversation yet. | | `parent_user_id` | The parent BSUID, only when Meta sends it (`US.ENT.…`). Null otherwise. | | `username` | The username, only when the correspondent adopted one. Null otherwise. | | `type` | The message type, in Meta’s vocabulary. | | `text` | The text, when the type is text. Null on the other types. | | `profile_name` | The name the correspondent displays on WhatsApp. Null when Meta did not send it. | | `media` | Image, video, audio, document or sticker: `mime_type`, `sha256`, `caption`, `filename` (documents only), `voice` (audio only) and `animated` (stickers only). `type` says which one. Meta’s identifier and URL do not come, because you do not hold the token that opens them. | | `interactive` | The choice made on an interactive message: `type` (`button_reply`, `list_reply` or `nfm_reply`), the button or item’s `id` and `title`, the list item’s `description`, and, on a Flow answer, `name` and `response_json` (the JSON text Meta sent, uninterpreted). | | `button` | A tap on a template quick-reply button: `payload` and `text`. | | `location` | The shared location: `latitude`, `longitude`, `name`, `address` and `url`. | | `contacts` | The shared contact cards, a list. Each one carries `name`, `phones`, `emails` and `org`. | | `reaction` | The reaction: the `wamid` of the message that received it, and `emoji`. `emoji` is null when the reaction was removed. | | `context` | The message the correspondent quoted when replying (`wamid`, `from`), and whether it was forwarded (`forwarded`, `frequently_forwarded`). | | `referral` | The Click to WhatsApp ad or post that led the correspondent to write: `source_type`, `source_id`, `source_url`, `headline`, `body`, `media_type` and `ctwa_clid`. | | `unsupported` | Present when `type` is `unsupported`: the correspondent sent something the Cloud API does not deliver. It carries `code`, `title` and `details`, as Meta sent them (code `131051` is "message type not supported"). There is no content to read: use the notice so your agent can answer that it cannot see that. | | `edit` | Present when `type` is `edit`: the correspondent edited a message. It carries the `wamid` of the edited message and, when the new content is text, `type` and `text`. **The exact shape of the edit notice is still to be confirmed in Meta’s documentation**: if a field comes null, the raw envelope kept the rest. | | `revoke` | Present when `type` is `revoke`: the correspondent deleted a message for everyone. It carries the `wamid` of the deleted message. **The exact shape is still to be confirmed in Meta’s documentation**, as with the edit. Luna does not delete anything it already stored: you decide what to do with the deleted message. | | `order` | The order built in a catalog: `catalog_id`, `text` and `items`, each item with `product_retailer_id`, `quantity`, `item_price` and `currency`, as Meta sent them. | - The names inside these fields are Meta’s. Whoever has read the Cloud API documentation recognises `interactive.id`, `location.latitude` and `context`. - The event’s `id` is what you pass to the routes. To read the message, `GET /v1/messages/{id}`. To find it from a `wamid` you already stored, `GET /v1/messages?wamid=...`. - The same shape comes out in `content`, in `GET /v1/messages` and in `GET /v1/messages/{id}`, with the same names. There it is null on a message you sent. - To download a media file, make a `GET` on the `message.media.url` link, with no key: the link is valid for 30 days, is the same on every redelivery of the notice and is sensitive data (do not log it). `url` is null when the message has no media Luna can obtain. If Luna is still downloading the file from Meta, the answer is `409` with `Retry-After`: try again. With a key, `GET /v1/messages/{id}/media` with the `message.id` remains valid. See [Send messages](https://lunahia.com.br/en/docs/send-messages#midia). ### `message.status` A state change of a message you sent. Each state is its own event, with its own `event_id`. Sent ```json { "version": "2026-11-10", "event_id": "464e089a80690f1792db6249678ddeced5ad5be0d46d95e2daa263779f7d92e5", "event_type": "message.status", "occurred_at": "2026-10-06T14:02:14.090Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "status": "sent", "error_code": null, "error": null, "pricing": { "billable": false, "pricing_model": "PMP", "type": "free_customer_service", "category": "service" }, "callback_data": "atendimento-8841" } } ``` Failure ```json { "version": "2026-11-10", "event_id": "6a79ec64bfea6acc67135d032067fd6261aa568c3aea35af7999790a7730cf69", "event_type": "message.status", "occurred_at": "2026-10-06T14:02:15.311Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "status": "failed", "error_code": 131026, "error": { "code": 131026, "title": "Message undeliverable", "message": "Message undeliverable" }, "pricing": null, "callback_data": null } } ``` | `message` field | What it is | | --- | --- | | `id` | The message’s identifier at Luna, the same one `POST /v1/messages` returned when you sent it. Null when the status belongs to a message Luna does not know. | | `wamid` | The message’s identifier at Meta. Null when Meta refused the send before accepting the message: it never had an identifier, and `id` is the key. | | `wa_id` | The correspondent’s phone number at Meta. Null when the conversation is BSUID only: use `user_id`. | | `user_id`, `parent_user_id`, `username` | The correspondent’s BSUID, the parent BSUID and the username, as in `message.received`. All always present, and null when they do not apply. | | `status` | The state, in Meta’s vocabulary: `sent`, `delivered`, `read`, `played` or `failed`, and `canceled`, which is Luna’s and goes out when you cancel a queued message with `DELETE /v1/messages/{id}` (Meta never received it, and `wamid` and `error` are null). New states can appear, and whoever does not know a value should ignore the event. | | `error_code` | Meta’s error code when the state is a failure. Null on the others. | | `error` | The first error Meta reported, with `code`, `title` and `message`, when the state is a failure. Null on the others. The reason in Portuguese and the recommended action are in `GET /v1/messages/{id}`. | | `pricing` | The cost Meta applied to the message, with its names: `billable`, `pricing_model`, `type` and `category`. Meta reports it only on `sent` and on one of `delivered` and `read`, so it is null on the other states. The values of `type` and `category` are Meta’s and can gain new ones: do not treat them as a closed list. It is the classification for you to display, not the invoice. See [Meta costs](https://lunahia.com.br/en/docs/meta-costs#conferir). | | `callback_data` | The label you sent in `callbackData` when sending the message, returned as it came, in every status (including `failed`). Null when the send carried no label. See [Send messages](https://lunahia.com.br/en/docs/send-messages). | - Meta does not emit `delivered` when delivery and reading coincide. `sent` followed straight by `read` is a valid sequence, not a lost event. - The `id` ties the event to the message you sent: it is the one `POST /v1/messages` returned, and it works in `GET /v1/messages/{id}`. The `wamid` stays in the event for whoever prefers Meta as the key, and `GET /v1/messages?wamid=...` finds it. Use the `id` as the key, because the `wamid` is null when Meta refuses the send. - A failure arrives as `message.status` with `status: "failed"` in two ways. Meta can accept the message and report the failure later, and then the `wamid` is filled in. Or it can refuse the send in its own response (revoked token, number without WhatsApp, wrong template parameter, payment method): Luna marks the message as failed right away, does not retry, and you receive the same event, with a null `wamid` and Meta’s `error`. A passing failure at Meta, such as a timeout, is not a failure: Luna retries on its own and you do not receive `failed`. - For the reason of a failure, in Portuguese and with the recommended action, read `GET /v1/messages/{id}`. See [Errors](https://lunahia.com.br/en/docs/errors#envio). ### `message.echo` The business owner answered a customer from the WhatsApp Business app on the phone. **It only occurs on a number connected in coexistence.** The shape is the one of `message.received`, with one difference that matters: `message.wa_id` is the **recipient**, the customer the owner wrote to, and not whoever wrote. When the conversation is BSUID only, `wa_id` is null and the recipient is `message.user_id`. ```json { "version": "2026-11-10", "event_id": "01b53d46e858f6ab6c89e183ef9509d703f665f6cfe2eb1d6bb185df56224d88", "event_type": "message.echo", "occurred_at": "2026-10-07T13:02:30.250Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "9a3e6b14-5c2d-4f81-b7a0-2d8e1c4f6a93", "wamid": "wamid.EXAMPLE_ECHO", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "text", "text": "Oi, Maria! Já separei o seu pedido, sai hoje.", "profile_name": null, "media": null, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` > **This is the signal for your agent to stay quiet.** When a human answered, pause your agent for that conversation (the key is `phone_number_id` plus `message.wa_id`) and resume it only by a rule you define, for example after an interval with no human reply. Without this, the agent answers on top of the business owner. Revoking or editing a message on the phone does not generate this event. ### `contact.identity_changed` The contact changed phone number (`user_changed_number`) or BSUID (`user_changed_user_id`). Luna links the new identity to the **same conversation**, without moving the history, and tells your system, which is the one that keeps the contact on your side. Use `previous_user_id` and `user_id` to update the record. `wa_id`, `previous_user_id` and the two parent BSUIDs can be null, and the values arrive as Meta sent them. It is a Meta system message: it is not `message.received` and it does not open the service window. ```json { "version": "2026-11-10", "event_id": "f73a65b1f155f86f94e0886ad29bac662a822fabf796b626cdf865c7060f0db9", "event_type": "contact.identity_changed", "occurred_at": "2026-11-03T15:20:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "contact": { "wamid": "wamid.EXAMPLE_IDENTITY_CHANGE", "change_type": "user_changed_user_id", "wa_id": null, "user_id": "BR.98765432109876543210", "previous_user_id": "BR.13491208655302741918", "parent_user_id": null, "previous_parent_user_id": null } } ``` ### `contact.preferences_changed` The contact changed a preference at Meta, today the one about receiving marketing messages: they asked to stop (for example `preference.value` equal to `stop`) or accepted again. `preference.category`, `preference.value` and `preference.detail` arrive **as Meta sent them**, with no closed list, and any of them can be null. **Luna does not block any send because of the notice**: your system decides, and should stop sending marketing to whoever asked. The event goes out in the same ordering group as the contact’s conversation. > **It only arrives if the `user_preferences` field is subscribed on the Meta app**, and that subscription is made in Meta’s dashboard, once, by whoever administers the app. The exact shape of the body Meta sends on that field is still to be confirmed in its documentation: Luna reads it tolerantly, and whatever Meta sends beyond what is here stays in the raw envelope for 7 days. With no user identifier in the notice (neither `wa_id` nor `user_id`), there is no event. ```json { "version": "2026-11-10", "event_id": "4236ccfb21e7cec359d1e1b5b5f3f8e65cb3e8a8db0fc86e4d95da037796e97c", "event_type": "contact.preferences_changed", "occurred_at": "2026-11-04T16:45:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "contact": { "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "profile_name": "Maria Souza" }, "preference": { "category": "marketing_messages", "value": "stop", "detail": "User requested to stop marketing messages" } } ``` ### `backlog.dropped` The platform dropped events from your endpoint’s backlog and **will not resend them**. This is the notice, and it is not dropped along with what it describes. ```json { "version": "2026-11-10", "event_id": "f76937420c2e818b87ce9b6acc5cb192c059ed2e33cda23339d5cf650b762ce5", "event_type": "backlog.dropped", "occurred_at": "2026-10-06T14:30:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "backlog": { "motivo": "idade", "quantidade": 37, "janela_inicio": "2026-10-06T09:00:00.000Z", "janela_fim": "2026-10-06T14:30:00.000Z" } } ``` | `backlog` field | What it is | | --- | --- | | `motivo` | `idade` (age), when the messages got too old to act on. `volume`, when the endpoint’s backlog went over the platform’s ceiling. | | `quantidade` | How many events were dropped in this occurrence. | | `janela_inicio` | The oldest event dropped. | | `janela_fim` | The newest event dropped. | When this happens, reconcile from the history: `GET /v1/messages` returns what came in and went out, newest first. ### `history_sync.deadline_approaching` The history import notice of a number in coexistence. The object carries the deadline and nothing else. See [Connect a number](https://lunahia.com.br/en/docs/connect-a-number#coexistencia). ```json { "version": "2026-11-10", "event_id": "d42ca56e44ef023d52b0a0739dcf3afb0d5054a8b84321c41e432ed6707b043f", "event_type": "history_sync.deadline_approaching", "occurred_at": "2026-10-07T03:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "history_sync": { "prazo": "2026-10-07T09:00:00.000Z" } } ``` ### `template.status` Meta approved, rejected, paused or disabled a template. It has no number and no conversation (`phone_number_id` is `null`): the template belongs to the business account. Template events are ordered among themselves per business account. In `template`, `external_id` is the label of the customer that owns the template: the `externalId` of the account’s numbers when all of them have the same one, and `null` when the account has numbers of different customers, when some number has no label and when it has no connected number (in those cases tie the event to the customer by `waba_id`; `template.category` and `template.quality` carry the same field). Also in `template`, `id` is Luna’s identifier, the same as in `GET /v1/templates`, `waba_id` is the template’s business account (the `wabaId` of the same route, to tie the event to one of your customers without reading another route) and `reason` is the reason Meta gave for the rejection or the pause, or `null` when it gives none (approvals come with no reason). `status` is Meta’s text, and new values can appear. ```json { "version": "2026-11-10", "event_id": "821d41ec2c33a28abe8a0baf97db034baaef1dbe511a6e546a37eca4ad565c65", "event_type": "template.status", "occurred_at": "2026-10-07T13:20:00.000Z", "phone_number_id": null, "number": null, "template": { "id": "3f6a1c52-9d4e-4b87-a1f0-5e2c7b9d8a14", "name": "confirmacao_de_pedido", "language": "pt_BR", "waba_id": "102290129340398", "external_id": "cliente-8841", "status": "REJECTED", "category": "UTILITY", "reason": "INVALID_FORMAT" } } ``` ### `number.connected` A number finished connecting and is registered on the Cloud API. It is the signal that your customer completed the connection you opened with [the connect link](https://lunahia.com.br/en/docs/connect-a-number): you do not need to poll `GET /v1/numbers`. `number.external_id` is the label you gave the customer when creating the link, and `number.id` is Luna’s identifier for the number, and `number.waba_id` is its business account (the `waba.id` of `GET /v1/numbers`). `number.coexistence` is `true` when Luna has already observed coexistence traffic on it, and it can be `false` at the instant of connection and change later: the current value is the `coexistence` field of `GET /v1/numbers/{id}`. To know whether sending is already cleared, read the `ready` field of the same route. ```json { "version": "2026-11-10", "event_id": "458470a340db14358f03ac02fde7e3839cb6887f3071c06c57a3d9d456621996", "event_type": "number.connected", "occurred_at": "2026-10-07T13:45:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "coexistence": false } } ``` > The notice is sent once per number, and only to whoever has an active endpoint. If your endpoint did not exist yet, or was paused, when the number became ready, you receive it if you register or resume the endpoint within 24 hours; after that it is never sent, and `GET /v1/numbers` remains the source of truth. ### `number.payment_required` e `number.payment_resolved` The number’s payment at Meta, in its two transitions. `number.payment_required` is sent when Meta refuses a send for lack of a payment method on the business that owns the account (error `131042`) and the number enters the wait. `number.payment_resolved` is sent when a send is accepted again. It is sent **once per transition**, not for every refused message: refused messages arrive as `message.status` with `status: "failed"`. In `number`, `id` is Luna’s identifier, `external_id` is the label you gave the customer, and `awaiting_payment_since` (only on `number.payment_required`) is the same value as `awaitingPaymentSince` in `GET /v1/numbers/{id}`. The [Payment at Meta](https://lunahia.com.br/en/docs/payment-at-meta) guide explains what to do and what to tell your customer. Entered the wait ```json { "version": "2026-11-10", "event_id": "50a49cee4b216c529e3f7cdd0be525f8902ff6aff66439e004dfe34a0c979fcf", "event_type": "number.payment_required", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "awaiting_payment_since": "2026-10-13T12:00:00.000Z" } } ``` Sending again ```json { "version": "2026-11-10", "event_id": "6a956161dd17bb975533e63286e811ae62b77b3350107945952b2e53f0a9d1e2", "event_type": "number.payment_resolved", "occurred_at": "2026-10-13T15:30:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841" } } ``` ### `number.display_name_reviewed` The number’s display name (what the contact sees instead of the phone number) goes through a Meta review. This event is sent when the state of that review changes, for example from `pending_review` to `approved` or `declined`. `number.status` is the same `displayNameStatus` as `GET /v1/numbers/{id}`: `approved`, `pending_review`, `declined`, `expired` or `none`; new values can appear. `number.name` is the name the state refers to: the requested name, when there is a request, otherwise the name in use. Meta does not send the reason for a refusal in this query, and Luna does not return one. Luna checks each number’s name periodically, so the event arrives with a delay of up to about an hour. An approved name only takes effect after the number is registered again, as the [What the number does at Meta](https://lunahia.com.br/en/docs/number-on-meta#nome-de-exibicao) guide explains. ```json { "version": "2026-11-10", "event_id": "23fd01fabc59f4c9ffda20955726e7e3e19c6a05cf609197c8b3c0aef8405e76", "event_type": "number.display_name_reviewed", "occurred_at": "2026-11-04T14:20:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "status": "declined", "name": "Clínica Sorriso Centro" } } ``` ### `number.action_required` e `number.action_resolved` The notice your system shows its customer: **the number needs action**. `number.action_required` is sent when the list of causes in `connection` goes from empty to non-empty, and `number.action_resolved` when it empties. It is the same calculation as `connection` in `GET /v1/numbers` and `GET /v1/numbers/{id}`: `status`, `can_send` and `reasons`, each cause with `code` (for your code to compare), `message` and `solution` (in Portuguese, ready to pass on). The causes: `pin_required`, `registration_blocked`, `credential_invalid`, `credential_expired`, `credential_expiring`, `payment_required`, `payment_method_missing`, `account_restricted`, `account_disabled`, `trial_expired` and `account_blocked`; new codes can appear. A cause does not always stop sending: `can_send` says whether sending will work now. The event is sent **once at the transition**, not at every change of the list; if you need the current state, read `connection`. A number you disconnect does not produce `number.action_resolved`: `number.disconnected` already announced it. Needs action ```json { "version": "2026-11-10", "event_id": "8832cdd12544436fce3b39d709158baa046091d010b5ed144a289c81b807c710", "event_type": "number.action_required", "occurred_at": "2026-10-28T15:02:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "status": "action_required", "can_send": false, "reasons": [ { "code": "payment_required", "message": "A Meta recusou um envio deste número por falta de método de pagamento na conta de WhatsApp Business do negócio.", "solution": "O dono da conta cadastra o método de pagamento no WhatsApp Manager da Meta. A Luna não intermedeia esse pagamento. Quando um envio voltar a ser aceito, o aviso sai do ar." } ] } } ``` No longer needs action ```json { "version": "2026-11-10", "event_id": "3279de99ef1bc2ade5d88bde7a2fd878b8faabddc179b8dceebded74d5b7394b", "event_type": "number.action_resolved", "occurred_at": "2026-10-28T15:40:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "status": "connected", "can_send": true } } ``` ### `onboarding.link.opened`, `onboarding.link.completed`, `onboarding.link.failed` and `onboarding.link.expired` The cycle of the [connect link](https://lunahia.com.br/en/docs/connect-a-number) you sent a customer, with their `externalId` in `link.external_id`. `onboarding.link.opened`: the customer opened the link for the first time (`link.opened_at`), once per link and not again when they come back to the page; it tells you who opened and got stuck without completing. `onboarding.link.completed`: the customer completed the connection (the link becomes `used`); `link.waba_id` is the account the customer connected, even when the account came with no number, and `link.number_id` carries the number when Luna has already registered it (`number` then comes in the same shape as the number events, with phone and `waba_id`); `number.connected` announces when it is ready. `onboarding.link.failed`: an attempt did not work out, once per attempt (`link.session_id`), and the link stays open until it expires. `link.reason` says why: `abandoned` (the customer closed Meta’s window, and `link.step` is the screen where they stopped), `error` (Meta’s window reported an error, in `link.error_code`), `failed` (Luna tried to complete and could not), `country_not_supported` (the number is not +55) or `registration_blocked` (Meta blocked registration for 72 hours). `onboarding.link.expired`: the link expired unused, and a used link never produces this event. All four go out once, and `number` is `null` when the event has no number yet. The guide for [a SaaS with many customers](https://lunahia.com.br/en/docs/saas-with-n-customers) uses all four. Link opened ```json { "version": "2026-11-10", "event_id": "b8a277c5c9377c213ee4c3b79c3e83829f3bef5f69521db1a0434da05acfbc1d", "event_type": "onboarding.link.opened", "occurred_at": "2026-10-28T15:21:40.000Z", "phone_number_id": null, "number": null, "link": { "id": "7c3e5a19-2b4d-4f60-8a1e-9d0b3c5f7a21", "external_id": "cliente-8841", "opened_at": "2026-10-28T15:21:40.000Z" } } ``` Connection completed ```json { "version": "2026-11-10", "event_id": "fd3596b2273541c7a77c69cb8a2ddb0e060052ddc84f251b5a76961053b578b1", "event_type": "onboarding.link.completed", "occurred_at": "2026-10-28T15:30:12.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398" }, "link": { "id": "7c3e5a19-2b4d-4f60-8a1e-9d0b3c5f7a21", "external_id": "cliente-8841", "used_at": "2026-10-28T15:30:12.000Z", "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b" } } ``` Attempt that did not work out ```json { "version": "2026-11-10", "event_id": "cabf3f3478bda2efd0e9a3726d503dbcd575bec16cc0ccf5fc65cdcb4c88cea3", "event_type": "onboarding.link.failed", "occurred_at": "2026-10-28T15:12:40.000Z", "phone_number_id": null, "number": null, "link": { "id": "7c3e5a19-2b4d-4f60-8a1e-9d0b3c5f7a21", "external_id": "cliente-8841", "session_id": "2e8f4b60-1a3c-4d57-9b0e-6c7d8e9f0a12", "reason": "abandoned", "step": "phone_number_setup", "error_code": null } } ``` Expired link ```json { "version": "2026-11-10", "event_id": "1df73af80cf86f74267290bc13fcd1f82551997dd79845170b35c78f40b563ad", "event_type": "onboarding.link.expired", "occurred_at": "2026-10-31T15:00:00.000Z", "phone_number_id": null, "number": null, "link": { "id": "7c3e5a19-2b4d-4f60-8a1e-9d0b3c5f7a21", "external_id": "cliente-8841", "expired_at": "2026-10-31T15:00:00.000Z" } } ``` ### `account.restricted`, `account.violation`, `account.disabled`, `account.reinstated` and `account.update` The health of the number’s WhatsApp Business account: restriction, policy violation, deactivation, reinstatement, and any other Meta account notice (`account.update`, with its raw `event` and the rest in `details`). The notice belongs to the **account**, and Luna delivers it **once for every connected number of it**: they all have the same `waba_id` inside the `waba` object. What each one means and what to do is in [Account health](https://lunahia.com.br/en/docs/account-health). Restricted account ```json { "version": "2026-11-10", "event_id": "d3b1b97cb8b69ac0bf9db087b5200febbea3dcbcc8d0a4108913592b51fdaf29", "event_type": "account.restricted", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "restrictions": [ { "restriction_type": "RESTRICTED_ADD_PHONE_NUMBER_ACTION", "expiration": "2026-11-13T12:00:00Z", "remediation": null } ] } } ``` Policy violation ```json { "version": "2026-11-10", "event_id": "a2fa828795bf24fd8e7460738c1a1e11a1bcd278fc09a0d238f92ba8c5994441", "event_type": "account.violation", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "violation_type": "ALCOHOL_VIOLATION" } } ``` Deactivated account ```json { "version": "2026-11-10", "event_id": "b0308dcc1ab6324eaea0474f1bcdec28146d3a6eb62668a1425fb3a7d6aad778", "event_type": "account.disabled", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "ban_date": "2026-10-13" } } ``` Reinstated account ```json { "version": "2026-11-10", "event_id": "135a9c7b3f192a7cab5ea55f68e0a8113e8d8e80acaa0ae8dad7f20aaf61f2db", "event_type": "account.reinstated", "occurred_at": "2026-10-14T09:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "ban_date": null } } ``` Another account notice ```json { "version": "2026-11-10", "event_id": "f663ad9f077e865db5d29245db96fe579e9aaa487bdf2f9d91a6e535af3d7949", "event_type": "account.update", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "event": "ACCOUNT_DELETED", "details": {} } } ``` ### `account.limit_changed`, `number.disconnected` and `number.quality_changed` `account.limit_changed`: Meta changed the account limit (`daily_conversation_limit` and `max_phone_numbers_per_waba`), which holds for all its numbers. `number.disconnected`: the number is no longer connected to Luna, and `reason` says which Meta notice caused it. `number.quality_changed`: the number’s quality rating changed. Meta has no webhook for quality, so this event arrives with a delay of up to about an hour. See [Account health](https://lunahia.com.br/en/docs/account-health). Account limit ```json { "version": "2026-11-10", "event_id": "a3bddf693de91539edaebb432d0d4f936b40822085cafa5c7864ae149756dbff", "event_type": "account.limit_changed", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "daily_conversation_limit": "TIER_2K", "max_phone_numbers_per_waba": null } } ``` Disconnected number ```json { "version": "2026-11-10", "event_id": "0dfe4e31d4e40e4a5da6d3f42f0d44b660f67ce551b2a43966e5fb0390fcd741", "event_type": "number.disconnected", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "reason": "PARTNER_APP_UNINSTALLED", "disconnection_reason": null, "initiated_by": null } } ``` Number quality ```json { "version": "2026-11-10", "event_id": "cc81de4eb28ad6a80e39c6cca13eb4b6db12f223f3c1346552cbc24795bcdbbe", "event_type": "number.quality_changed", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "previous_quality_rating": "GREEN", "quality_rating": "YELLOW" } } ``` ### `number.credential_expiring` and `account.alert` `number.credential_expiring`: the authorization your customer gave Luna expires within 14 days (`credential_expires_at`). It is sent once per expiry and per number, and renewal is done with a reconnection link (`POST /v1/onboarding/links` with `numberId`). `account.alert`: an alert Meta sent about the account (the `account_alerts` field), with `alert_type`, `alert_severity`, `alert_status`, `alert_description` and the rest in `details`, all as Meta sent it. Both are explained in [Account health](https://lunahia.com.br/en/docs/account-health#credencial). Authorization about to expire ```json { "version": "2026-11-10", "event_id": "33b03111fe7f1f225626ece55b50955389e78742a6b99059f05be056ce2b2260", "event_type": "number.credential_expiring", "occurred_at": "2026-11-21T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "credential_expires_at": "2026-12-05T12:00:00.000Z" } } ``` Meta alert about the account ```json { "version": "2026-11-10", "event_id": "fb613a0660724669d9251d4185488ec26409b34345c592b908ce9747b8430f99", "event_type": "account.alert", "occurred_at": "2026-10-19T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "entity_type": "WABA", "entity_id": "102290129340398", "alert_severity": "INFORMATIONAL", "alert_status": "ACTIVE", "alert_type": "INCREASED_CAPABILITIES_ELIGIBILITY_DEFERRED", "alert_description": "Messaging limit increase deferred.", "details": {} } } ``` ### `template.category` and `template.quality` Like `template.status`, they have no number and no conversation (`phone_number_id` is `null`), carry `template.waba_id` and are sent in order with it, per business account. `template.category`: Meta changed, or announced it will change, a template category. The advance notice carries `correct_category` and `scheduled_for`, and the change made carries `previous_category` and `new_category`. **The category changes the price Meta charges the business**, and a change from `UTILITY` to `MARKETING` raises it; see [Templates](https://lunahia.com.br/en/docs/templates). `template.quality`: the template’s quality score changed, and a low score comes before a pause. Category advance notice ```json { "version": "2026-11-10", "event_id": "67e825cdeb1f139ea3f76761c2e087a272352caca49dea9ab471383293a8ca07", "event_type": "template.category", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": null, "number": null, "template": { "id": "3f6a1c52-9d4e-4b87-a1f0-5e2c7b9d8a14", "name": "pedido_confirmado", "language": "pt_BR", "waba_id": "102290129340398", "external_id": "cliente-8841", "category": "UTILITY", "previous_category": null, "new_category": null, "correct_category": "MARKETING", "scheduled_for": "2026-10-14T17:46:40.000Z" } } ``` Category changed ```json { "version": "2026-11-10", "event_id": "a088e870f11e399bc1d40266c5d07e18d0b13da6d1cf4d2021cbb232451ed86d", "event_type": "template.category", "occurred_at": "2026-10-14T17:46:40.000Z", "phone_number_id": null, "number": null, "template": { "id": "3f6a1c52-9d4e-4b87-a1f0-5e2c7b9d8a14", "name": "pedido_confirmado", "language": "pt_BR", "waba_id": "102290129340398", "external_id": "cliente-8841", "category": "MARKETING", "previous_category": "UTILITY", "new_category": "MARKETING", "correct_category": null, "scheduled_for": null } } ``` Template quality ```json { "version": "2026-11-10", "event_id": "8624296410fe8b7631164b57d667847f22145595d3bac4ae644e32930aab9321", "event_type": "template.quality", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": null, "number": null, "template": { "id": "3f6a1c52-9d4e-4b87-a1f0-5e2c7b9d8a14", "name": "pedido_confirmado", "language": "pt_BR", "waba_id": "102290129340398", "external_id": "cliente-8841", "previous_quality_score": "GREEN", "new_quality_score": "YELLOW" } } ``` ### `webhook.test` The test event. **It only arrives when you ask for it**, at `POST /v1/webhooks/endpoints/{id}/test`: Luna never sends it on its own. It has no number and no conversation (`phone_number_id` is `null`), and the object carries the endpoint id, so you know which one was tested when two point to the same URL. It is signed like any delivery, and it is a good case to exercise your verification. ```json { "version": "2026-11-10", "event_id": "6af3f85d8fedc8bb0f6d5bb6b4631e324574c539763c25cf113fd40db822cea8", "event_type": "webhook.test", "occurred_at": "2026-10-07T12:00:00.000Z", "phone_number_id": null, "number": null, "webhook_test": { "endpoint_id": "5c0e9a52-3a0e-4c3f-9f3e-0b3f6f1a2c77" } } ``` ## Verify the signature Anyone can send a `POST` to your URL. The signature is what proves the delivery came from Luna. **Verify before handling the event.** Each delivery carries a header: **In plain words.** You and Luna share a secret: the `secret` that the registration response returns, which starts with `whsec_`. Before sending each event, Luna mixes the secret with the event’s content and writes the result in the `X-Luna-Signature` header, like a stamp. Whoever does not know the secret cannot make an identical stamp. On receiving, you redo the same mix and see whether the stamp matches: if it does, the event came from Luna and nobody changed it on the way. **Why it matters.** Your webhook’s address is public. Without checking the stamp, anyone can send a fake event (a “paid order”, for example) and your system would act as if it were real. 1. From the header, take the number after `t=` (the instant Luna signed) and the values after `v1=` (the stamps). 2. Join the `t`, a dot and the **body exactly as it arrived** (the same bytes, without opening the JSON and building it again), and do the mix with your secret: that is HMAC-SHA256, which every language has ready-made. 3. Compare the result with each `v1`. Equal to any: you can trust it. Different from all: answer `401` and ignore the event. ```http X-Luna-Signature: t=1760000000,v1=3f1c0a9e5b7d2c4a6e8f0b1d3c5a7e9f2b4d6c8a0e1f3a5b7c9d1e3f5a7b9c1d ``` 1. Read `t`, the signing instant in seconds since 1970. Refuse the delivery if it is more than **300 seconds** from your clock, in either direction. That stops someone replaying a captured request. 2. Compute the HMAC-SHA256 of the text `t` + `.` + **raw body**, with the endpoint’s secret as the key, and write the result in hexadecimal. The secret is the whole string, `whsec_` included. 3. Compare the result with **each** `v1=` value in the header, in constant time. If any is equal, the signature is valid. - Use the **exact bytes** that arrived. If you parse the JSON and serialize it again, the key order or escaping can change, and the signature fails intermittently. In Express, use `express.raw({ type: "application/json" })` on this route. In Flask, `request.get_data()`. In FastAPI, `await request.body()`. - Compare in constant time (`timingSafeEqual`, `compare_digest`), never with `==`. - During a secret rotation the header carries **two** signatures, `v1=` repeated. You know one of them, and it can be the second. That is why the code checks them all. - Answer `401` to an invalid signature. Luna counts only `2xx` as delivered, so a `401` is never taken for success. ### The verification function Save as `verify.mjs` (Node) or `verify.py` (Python): ```js import crypto from 'node:crypto'; const TOLERANCE_SECONDS = 300; // rawBody: the exact bytes received (a Buffer), never re-serialized JSON. export function verifyLunaSignature(rawBody, header, secret, nowMs = Date.now()) { if (typeof header !== 'string' || !secret) return false; // 1. The header carries the instant t and the signature v1. const m = /^t=(\d{1,15}),/.exec(header); if (!m) return false; const t = Number(m[1]); // 2. Refuse what is too old (a recorded delivery replayed later). if (Math.abs(Math.floor(nowMs / 1000) - t) > TOLERANCE_SECONDS) return false; // 3. Redo the calculation with your secret and compare it with v1. const expected = crypto .createHmac('sha256', secret) .update(`${t}.`) .update(rawBody) .digest(); // During a secret rotation the header carries two v1 values: check them all. let ok = false; for (const [, hex] of header.matchAll(/v1=([0-9a-fA-F]{64})/g)) { if (crypto.timingSafeEqual(Buffer.from(hex, 'hex'), expected)) ok = true; } return ok; } ``` ```python import hashlib import hmac import re import time TOLERANCE_SECONDS = 300 def verify_luna_signature(raw_body, header, secret, now=None): # raw_body: the exact bytes received, never re-serialized JSON. if not header or not secret: return False # 1. The header carries the instant t and the signature v1. m = re.match(r"^t=(\d{1,15}),", header) if not m: return False t = int(m.group(1)) # 2. Refuse what is too old (a recorded delivery replayed later). now = time.time() if now is None else now if abs(int(now) - t) > TOLERANCE_SECONDS: return False # 3. Redo the calculation with your secret and compare it with v1. expected = hmac.new( secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256 ).hexdigest() # During a secret rotation the header carries two v1 values: check them all. ok = False for sig in re.findall(r"v1=([0-9a-fA-F]{64})", header): if hmac.compare_digest(sig.lower(), expected): ok = True return ok ``` ### A complete server Save as `server.mjs` or `server.py`, next to the previous file, and run with `LUNA_WEBHOOK_SECRET` set: ```js import http from 'node:http'; import { verifyLunaSignature } from './verify.mjs'; const SECRET = process.env.LUNA_WEBHOOK_SECRET; // whsec_... const seen = new Set(); // in production: a database or Redis, with an expiry async function handle(event) { switch (event.event_type) { case 'message.received': // wa_id can be null (user without a phone number): user_id is then the key console.log('received', event.message.wa_id ?? event.message.user_id, event.message.text); break; case 'message.status': console.log('status', event.message.wamid, event.message.status); break; default: console.log('ignored', event.event_type); // new types can appear } } http .createServer((req, res) => { const chunks = []; req.on('data', (chunk) => chunks.push(chunk)); req.on('end', () => { const raw = Buffer.concat(chunks); if (!verifyLunaSignature(raw, req.headers['x-luna-signature'], SECRET)) { res.writeHead(401).end(); return; } res.writeHead(200).end(); // answer first, work after const event = JSON.parse(raw.toString('utf8')); if (seen.has(event.event_id)) return; // at-least-once: drop repeats seen.add(event.event_id); handle(event).catch((err) => console.error('handler failed', err)); // the handler never runs on the request thread: the work goes to a queue }); }) .listen(Number(process.env.PORT ?? 3000)); ``` ```python import json import os import queue import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from verify import verify_luna_signature SECRET = os.environ["LUNA_WEBHOOK_SECRET"] # whsec_... seen = set() # in production: a database or Redis, with an expiry seen_lock = threading.Lock() events = queue.Queue() # the handler never runs on the request thread: the work goes to a queue def handle(event): kind = event["event_type"] if kind == "message.received": # wa_id can be null (user without a phone number): user_id is then the key print("received", event["message"]["wa_id"] or event["message"]["user_id"], event["message"]["text"]) elif kind == "message.status": print("status", event["message"]["wamid"], event["message"]["status"]) else: print("ignored", kind) # new types can appear def worker(): # one worker takes the events one at a time (call the LLM here, not in the request) while True: event = events.get() try: handle(event) except Exception as err: # a failure in one event must not stop the worker print("handler failed", repr(err)) class Handler(BaseHTTPRequestHandler): def do_POST(self): raw = self.rfile.read(int(self.headers.get("Content-Length", 0))) header = self.headers.get("X-Luna-Signature") if not verify_luna_signature(raw, header, SECRET): self.send_response(401) self.send_header("Content-Length", "0") self.end_headers() return self.send_response(200) # answer first, work after self.send_header("Content-Length", "0") self.end_headers() event = json.loads(raw) with seen_lock: repeated = event["event_id"] in seen # at-least-once: drop repeats seen.add(event["event_id"]) if not repeated: events.put(event) threading.Thread(target=worker, daemon=True).start() ThreadingHTTPServer(("", int(os.environ.get("PORT", "3000"))), Handler).serve_forever() ``` > The in-memory `Set` in the example disappears when the process restarts. In production, keep the processed `event_id`s in a database or Redis, with an expiry, and drop the repeats. ### Check by hand, in the terminal To see the calculation happen, or to debug a `401` you do not understand, do step 2 in the terminal with `openssl`. The example uses a made-up secret and body; swap in your secret, the header’s `t` and the bytes of the body your server received: ```bash SEGREDO='whsec_EXEMPLO_NAO_E_UM_SEGREDO' T=1760000000 CORPO='{"ok":true}' printf '%s' "$T.$CORPO" | openssl dgst -sha256 -hmac "$SEGREDO" | awk '{print $NF}' ``` Result ```text 22c562eb3e7a1c918e80953b5b95428cd92c8d3942fc77a190d116b53aa68258 ``` An `X-Luna-Signature: t=1760000000,v1=` header followed by that result would be valid for that secret and body. `printf` (not `echo`) keeps the terminal from adding a line break to the body, which would change the result. > Services that show what arrived at your URL, such as webhook.site, are good for **seeing** the event, but copying the body from the screen can change spaces and line breaks, and the signature stops matching. Check inside your server, with the bytes it received. ## Retries, rejected events and replay ### When delivery fails - Luna tries again with a growing wait. Each wait’s ceiling is 30 seconds, 90 seconds, 4.5 minutes, 13.5 minutes and 40.5 minutes, and then 1 hour between the following attempts. Each attempt’s wait is drawn between half and the full value. - Five failures in a row open a circuit breaker: Luna stops hitting the endpoint and lets one probe through per minute. Three successes in a row close it. When the endpoint is back, the backlog is delivered at a growing pace, so as not to knock it over again. - When the retry policy is exhausted, Luna gives up and the event goes to the **rejected queue**. - Separately, an endpoint’s backlog has two ceilings: 10,000 pending events and six hours of age. The oldest is dropped when either is passed, and you receive `backlog.dropped`. - These values are technical and identical for every customer. ### The rejected queue An event gets here after the retry policy is exhausted. It is not delivered again on its own: either you requeue it, or it stays there until retention expires. Every event type gets here, `message.echo` and `template.status` included; on the latter the `wamid` is null, because there is no message. `webhooks:read` scope to list and `webhooks:write` to requeue. ```bash curl -X GET "https://api.lunahia.com.br/v1/webhooks/dlq?limit=50" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/dlq?limit=50', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/webhooks/dlq?limit=50", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` `200` response ```json { "items": [ { "id": "0b6f6f2a-6d3e-4b8e-9a52-2f3c1d4e5a60", "endpointId": "5c0e9a52-3a0e-4c3f-9f3e-0b3f6f1a2c77", "eventType": "message.received", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "rejectedAt": "2026-10-06T16:00:00.000Z", "failureReason": "http_5xx", "requeuedAt": null } ], "nextCursor": null } ``` - `failureReason` is the class of the last failure: `http_4xx` (your server understood and refused), `http_5xx` (accepted and broke), `timeout`, `conexao` (connection), `destino_recusado` (destination refused) or `reenvio_pedido` (replay requested). The last one is not a failure: it is a replay you asked for yourself at `POST /v1/messages/{id}/replay`, and it is born with `requeuedAt` filled in. - The response carries no total, on purpose. To know how many items there are, page until `nextCursor` comes back null. `limit` goes up to 100. - The event body does not come in the list. Requeue it to receive it at your endpoint, signed like any other delivery. ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/dlq/YOUR_DLQ_ITEM_ID/reenfileirar" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/dlq/YOUR_DLQ_ITEM_ID/reenfileirar', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/webhooks/dlq/YOUR_DLQ_ITEM_ID/reenfileirar", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` The response is `202`: the request was recorded, and delivery happens asynchronously. Repeating the call for the same item answers `409` with `error: "already_requeued"` and the instant of the first request, and does not republish again. If your endpoint is still down, delivery will be postponed and retried by the usual policy. Requesting in bulk does not speed it up. ### Replay a message’s event To test your endpoint, or to recover the event of a message you already have, ask for a replay. The scope is `webhooks:write`, not `messages:*`: the scope follows the effect, and the effect is causing a delivery at your endpoint. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/replay" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/replay', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/replay", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` `202` response ```json { "deliveryId": "9f2a1b0c-3d4e-4f5a-8b9c-0d1e2f3a4b5c", "requestedAt": "2026-10-06T18:30:00.000Z" } ``` - Each request produces a new delivery, with its own `deliveryId`. Calling twice produces two deliveries, not an error. - The replay does not skip the queue or any defense. - The replayed event’s `event_id` is **the same** as the original’s. It comes from the message (the `wamid` and the contact, or the `wamid` and the state), not from the delivery. If your server drops the `event_id`s it has already seen, it will drop the replay too: to test, take that `event_id` out of your seen list before asking. The `deliveryId` in the response identifies the replay request, not the event. - The event replayed depends on the message: for a received message it is the `message.received`; for a sent one it is its **latest `message.status`** (`sent`, `delivered`, `read`, `failed` or `canceled`), with the same format and the same signature as the original, and it is the most recent `message.status`, not the whole list. The replay goes out marked as a requested replay (`failureReason: "reenvio_pedido"` in `GET /v1/webhooks/dlq`), the same as the received one. A sent message that Meta has not accepted yet, or that has no `message.status` yet, answers `400`, and its state is at `GET /v1/messages/{id}`. An endpoint that does not receive the type (`eventTypes`) does not count as a destination for the replay. - With no active endpoint (none registered, or all paused) the answer is `409` with `error: "no_webhook_endpoint"`, not a `202` that does not come true. ## Rotate the secret Rotate when the secret leaks, or when you lose it. Rotation does not take your integration down: ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID/rotacionar" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID/rotacionar', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID/rotacionar", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` - The response carries the new secret, exactly once. - The previous secret keeps producing a valid signature for **seven days**. During that period each delivery carries both signatures in the same header. - `previousSecretExpiresAt` says when the previous one stops being valid. While it is in the future, the endpoint is in the middle of a rotation. - Rotating again before the window ends drops the older of the two: there are never three valid secrets. ### The secret leaked: revoke the previous one right away The seven days protect your integration, and in a leak they become a risk: whoever has the old secret keeps signing deliveries that look legitimate. To end the overlap, rotate with `revokePrevious: true`. The previous one stops being valid at once, and `previousSecretExpiresAt` comes back null. ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID/rotacionar" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "revokePrevious": true }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID/rotacionar', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "revokePrevious": true }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID/rotacionar", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "revokePrevious": True, }, timeout=10, ) print(res.status_code, res.json()) ``` > The cost is this: deliveries already sent signed only with the old secret fail verification on your side. Switch the secret in your configuration right after rotating. > Each route’s full contract is in the [API reference](https://lunahia.com.br/en/docs/reference), in the Webhooks section. ## Route details for this guide The [API reference](https://lunahia.com.br/en/docs/reference) says how to call each route, in a few lines. What explains the reason for each decision, the edge cases and the warnings is here, in the order of the reference. ### GET /v1/webhooks/endpoints The signing secret does NOT come here, and it does not come from any route. It goes out exactly once, in the response to registration and to rotation: Luna stores only the encrypted form of it. If you lost it, rotate to receive a new one: there is no recovery path, and that is by design. Use this route to find out whether an endpoint already exists before registering one. A customer with no endpoint at all receives 200 with an empty list, not 404. When previousSecretExpiresAt is in the future, that endpoint is in the middle of a rotation: deliveries carry two signatures, and both are valid until that instant. ### POST /v1/webhooks/endpoints The secret appears in this response and in no other. Store it the moment you receive it: Luna keeps only the encrypted form of it, and no route hands it back. If you lose it, rotate to get a new one. The URL must use https and must point to a public address on the internet. Internal network, loopback and cloud metadata addresses are refused here and again at the moment of every delivery, because a name can change address between registration and the call. Luna does not follow redirects: register the final URL. eventTypes, optional, chooses the event types this endpoint receives (for example, only message.received and message.status). Absent or empty, it receives all of them, including the types Luna creates later. The filter is by type only, never by content or sender. externalIds and phoneNumberIds, optional, limit the endpoint to customers of yours and to numbers: it only receives the events of numbers with one of these externalId (including the ones connected later) or with one of these ids (Luna's UUID or Meta's id), and the connect link events with the externalId. Absent or empty, it receives from all. It is how you get one URL per customer of yours; external_id stays on every event, both ways. The filter is by identifier only, and the signature, order, replay and rejected queue are those of any endpoint. Each customer can have up to 25 endpoints, and every event is delivered to all the active ones that accept its type and customer. With 25 already registered, the response is 409 (webhook_endpoint_limit): remove one with DELETE /v1/webhooks/endpoints/{id} to free the slot. The limit is an infrastructure one and the same for everyone. ### GET /v1/webhooks/event-types The list grows when Luna creates a new type, without changing the contract version. The webhook.test event is not in it: it only goes out when you ask for an endpoint test. ### GET /v1/webhooks/endpoints/{id} The secret does not come back here, and it comes back from no route. Luna keeps only the encrypted form of it. While previousSecretExpiresAt is in the future, the endpoint is mid-rotation: deliveries carry two signatures, and both are valid until that instant. ### PATCH /v1/webhooks/endpoints/{id} The new URL goes through the same validation as registration (https and a public address), and the signing secret stays the same: you point to another server without reconfiguring verification. Changing the URL clears lastDeliveryAt, lastFailureAt and lastHttpStatus, because they described the old server. paused: true pauses. A paused endpoint receives no new events, and the events that occur during the pause are NOT delivered afterwards: pausing does not postpone, it discards. Whatever was already queued for it is discarded too. paused: false resumes, and it starts receiving whatever occurs from that moment on. Pausing an already paused endpoint does not change pausedAt. eventTypes replaces the list of event types the endpoint receives: the list you send replaces the previous one, and an empty list goes back to receiving all. The filter holds from then on, and is by type only. What happened before and was filtered is not delivered afterwards. externalIds and phoneNumberIds replace, the same way, the customers and numbers the endpoint receives events from: the list you send replaces the previous one, and an empty list goes back to receiving from all. phoneNumberIds takes Luna's UUID or Meta's id and returns Meta's ids, the same ones events carry in phone_number_id. headers replaces, the same way, the own headers Luna sends on every delivery: the object you send replaces the previous one, and {} removes them all. The registration rules apply (up to 5, a valid and non-reserved header name, an ASCII value of up to 1024 characters). The values are secret and never come back; the response carries only the names, in headerNames. You can test a paused endpoint with POST /v1/webhooks/endpoints/{id}/test before resuming it. An endpoint that is not yours answers 404, the same as one that does not exist. Returns the endpoint as GET /v1/webhooks/endpoints/{id} does. ### DELETE /v1/webhooks/endpoints/{id} What happens to what was still pending: events already on the delivery queue for this endpoint are discarded when they arrive, and are neither redelivered nor sent to the rejected queue. The items already on the rejected queue (GET /v1/webhooks/dlq) that pointed to it are deleted along with it: with no endpoint, there is nowhere to requeue them. This cannot be undone, and the signing secret is lost too. To stop receiving without losing anything, pause with PATCH. Removing frees one slot of the limit of 25 endpoints per customer. An endpoint that is not yours answers 404, the same as one that does not exist. ### GET /v1/webhooks/endpoints/{id}/deliveries It is the history that GET /v1/webhooks/endpoints/{id} does not have: one row per delivery attempt to the endpoint, over the last 7 days. Each event can show up several times (the same eventId, with attempt 1, 2, 3...) until your server accepts it or Luna gives up; what it gave up delivering is in GET /v1/webhooks/dlq. httpStatus is null when your server did not respond (timeout, connection refused, an address that stopped being public). status is success for 2xx and failed for everything else, redirects included, which Luna does not follow. The list does not carry the body sent, the headers or what your server answered, and it has no total: page by nextCursor until it comes back null. An endpoint that is not yours answers 404, the same as one that does not exist. ### POST /v1/webhooks/endpoints/{id}/test It works on a paused endpoint, which is the point: check before resuming. delivered is true when your server answered 2xx. When it is not, failure says why (timeout, connection, destination_not_allowed, response_too_large or http_status) and statusCode carries the status it returned. The body your server answered does not come back, on purpose. The webhook.test event only exists when you ask for it: Luna never sends it on its own. It has no number and no conversation (phone_number_id is null) and carries the endpoint id in webhook_test.endpoint_id. The limit is 5 tests per minute per customer, the same for everyone, because each call is an outbound request to your server. Above that, 429 with Retry-After. An endpoint that is not yours answers 404, the same as one that does not exist. ### POST /v1/webhooks/endpoints/{id}/rotacionar The previous secret keeps producing a valid signature for seven days, and during that window every delivery carries both signatures in the same header. This exists so that rotating does not take down your integration: you switch the configuration on your side whenever you can, inside the window, without losing a delivery. The exact instant the previous one stops being valid comes in previousSecretExpiresAt. Rotating again before the window ends discards the older of the two: at no point do three secrets exist. If the previous secret leaked, send the body {"revokePrevious": true}: it stops being valid at once, and previousSecretExpiresAt comes back null. The cost is that deliveries already sent signed only with it fail verification on your side, so switch your configuration right away. With no body, nothing changes. ### GET /v1/webhooks/dlq An event lands here after the retry policy has been exhausted: exponential backoff, circuit breaker and progressive drain having already been applied. It is not delivered again on its own: either you requeue it, or it stays here until retention expires. Every event type lands here, message.echo and template.status included. template.status has no message, so the wamid comes back null, and requeueing it delivers the same template state event. The response carries no total and no count, on purpose: Luna does not count deliveries, and no number in this API feeds billing. To find out how many items there are, page until nextCursor comes back null. The event body does not come back here. Requeue it to receive it on your endpoint, signed like any other delivery. Each item carries numberId and externalId (the number the event went through and your label for its customer; null on template.* and when the message is no longer in Luna), attempts (how many times Luna tried to deliver that event) and lastHttpStatus (what your endpoint answered on the last attempt, null when it did not answer). They are the diagnosis of ONE delivery, not sums. allowedActions carries requeue while the item has not been requeued. Filter with ?endpointId=, ?externalId= and ?requeued= (true or false). ### POST /v1/webhooks/dlq/{id}/reenfileirar Repeating the call for the same item answers 409 with the instant of the first request, and does not republish it. This exists so that two clicks, or a retry of yours, do not produce two deliveries of the same event. Requeueing does not jump the queue and does not skip the defenses: if your endpoint is still down, delivery is deferred and retried by the usual policy, without a single request going out. You do not need to wait for your server to come back before asking, but asking in bulk will not speed anything up either. An item that is not yours answers 404, same as an item that does not exist. --- # Send messages Fonte: https://lunahia.com.br/en/docs/send-messages One route sends every message type: `POST /v1/messages`. The `type` field says which one, and a body without `type` is read as text. This guide covers the types, the 24-hour window rule, idempotency and how to follow delivery. ## The basics - The API key needs the `messages:write` scope. - `from` is the origin number: **Luna’s UUID** (the `id` that `GET /v1/numbers` returns) or **Meta’s id** (the `metaPhoneNumberId`). Both work. - `to` is the recipient’s phone with country and area code, digits only, without the plus sign. For example, `5511999990000`. In this version Luna starts conversations only with Brazilian phones: they start with `55` and have 12 or 13 digits. Any other format (no country code, or from another country) answers `400` with `campos: [{campo: "to"}]`, except for someone who already wrote to your number: that conversation can still be answered. - The response is `202` with the message’s `id` at Luna and `status: "queued"`. It exists before Meta answers. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "text": { "body": "Olá! Recebemos seu pedido e já estamos preparando." } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID(), }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "text": { "body": "Olá! Recebemos seu pedido e já estamos preparando." } }), }); console.log(res.status, await res.json()); ``` ```python import os import uuid import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", "Idempotency-Key": str(uuid.uuid4()), }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "text": { "body": "Olá! Recebemos seu pedido e já estamos preparando.", }, }, timeout=10, ) print(res.status_code, res.json()) ``` `202` response ```json { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "status": "queued" } ``` Text goes up to 4096 characters, the same limit as the Cloud API. Luna counts in UTF-16 units, so an emoji can count as 2: Meta's documentation does not say how it counts, and Luna prefers refusing too much to letting Meta refuse later. With `preview_url: true` in `text`, Meta fetches the first URL in the text to build a preview. It is off by default. ### Why `202` and not `200` The tightest limit on Meta’s platform is the per-recipient one: it tolerates a short burst and, after it, one message every six seconds. Luna runs with margin on those numbers (a burst of 30 and one every 7 seconds), so the first messages of a conversation go out at once and only the later ones wait. An agent that answers in bursts trips it on its own. Luna accepts, queues and delivers to Meta at the pace it allows, and that limit never comes back to you as a `429`. The `wamid` and the delivery state arrive later, over the webhook. All the limits, with the numbers, are in [Limits and pacing](https://lunahia.com.br/en/docs/limits-and-pacing). ### Which identifier to use Every place that takes a **number** accepts both of its identifiers: Luna’s UUID (the `id` of `GET /v1/numbers`) and Meta’s id (the `metaPhoneNumberId`, the same one events carry in `phone_number_id`). Use whichever your system already stores. An id that is not yours answers `404` (or an empty list, in a filter), the same as one that does not exist. | Where | Which identifier | | --- | --- | | `POST /v1/messages`, `from` | The number: Luna’s UUID or Meta’s id. | | The `/v1/numbers/{id}`, `.../health` and `.../media` routes | The number: Luna’s UUID or Meta’s id. | | The `phoneNumberId` filter of `GET /v1/messages`, `/v1/conversations` and `/v1/templates` | The number: Luna’s UUID or Meta’s id. | | The `externalId` filter of messages, conversations, links and numbers | The label you gave the customer. It filters everything that is theirs, without you keeping a map of numbers. | | `GET /v1/messages/{id}` | The message’s `id` at Luna, the same one the `202` returned. | | `reaction.message_id` | The `wamid` of the message receiving the reaction. | ## Mark as read and show “typing” Both routes act on a **received** message, and are synchronous: they answer `200` when Meta accepts. The reason is that a signal like this loses its value with time. `messages:write` scope. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/read" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/read', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/read", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ```bash curl -X POST "https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/typing" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/typing', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/typing", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` - A message you sent, a message that is not yours and a message that does not exist all answer `404`, all alike. - Meta’s platform has no standalone typing indicator. Calling `/typing` **also marks the message as read**. There is no way to do one without the other. - The indicator goes away on its own when you reply, capped at 25 seconds on Meta’s side. There is no route to turn it off, and none is needed. ### A label of yours on the send Send `callbackData` (1 to 512 characters) in `POST /v1/messages` to tie the message to something of yours, like the customer or the support case, without keeping an id table. Luna passes it on to Meta (`biz_opaque_callback_data`, [Meta documentation](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/status)), stores it with the message and returns it as it came in `callback_data` of **every** `message.status` (`sent`, `delivered`, `read`, `failed`) and in `callbackData` of `GET /v1/messages` and `GET /v1/messages/{id}`. It works on any message type, template included, and with the test key the simulated statuses carry it too. Luna does not interpret it. **Do not put personal data in it**: it travels in every event. ### Typing on the send itself To make a reply look written by a person, send `typingMs` (1 to 25000, in milliseconds) in `POST /v1/messages`. Luna turns the typing indicator on at the **last message the contact sent**, waits that long and only then sends. The wait does not hold up the other conversations of your number: the order within the conversation is the usual one, and the `202` comes back right away. - It only works inside the service window. If the conversation has no received message in the last 24 hours (for example, a template to start a conversation), Luna **ignores** `typingMs` and sends right away, without an error. - As with `/typing`, turning the indicator on **also marks that received message as read**. - If Meta refuses the indicator, the message goes out anyway, without waiting. During the wait the message is still in the queue and can be canceled with `DELETE /v1/messages/{id}`. - The wait counts toward the time until the send: the `sent` event arrives `typingMs` later, plus the normal queue time. ## The 24-hour window Free-form text only goes out to someone who wrote to your number in the last 24 hours. Outside that window, the only path is a **template approved by Meta**. Sending the template does not reopen the window: it opens when the contact writes to or calls your number, and restarts with each new contact from them. Until then, free-form text is still refused. Template and reaction go through even with the window closed. (The [glossary](https://lunahia.com.br/en/docs/glossary#janela) has the short definition.) Luna applies the rule for you: outside the window, a free-form message is refused with `409` **before** any call to Meta, because a call refused over there is spent for nothing and counts as an error against your number. `409` response ```json { "error": "window_closed", "message": "A janela de atendimento desta conversa está fechada. Só é possível enviar mensagem livre até 24 horas depois da última mensagem do contato.", "fechadaEm": "2026-10-05T14:02:11.482Z", "acaoRecomendada": "Para falar com este contato agora, envie um template aprovado. A mensagem livre volta a ser aceita quando o contato responder, porque é a resposta dele que abre a janela. Se este contato escreveu há pouco e a janela devia estar aberta, confira o campo to: use o telefone do evento recebido (wa_id). A Luna já acha a conversa do celular brasileiro com e sem o nono dígito, mas qualquer outra diferença no telefone não encontra a conversa. Se o contato escreveu sem telefone (só com BSUID), envie com recipient igual ao user_id do evento, e não com to." } ``` This response carries no `Retry-After`, on purpose: the window does not open with time. It opens when the contact writes or calls, and sending a template does not open it. Repeating the request only repeats the refusal. If the contact wrote a moment ago and the window still shows as closed, check the `to`: use the phone of the event (`wa_id`). Meta delivers some Brazilian mobiles without the ninth digit (`553190009991`) and others with it (`5531990009991`), and Luna finds the conversation in both spellings: a text send goes to the `wa_id` Meta used, and lands in the same conversation. Any other difference in the phone (a wrong digit, no area code) finds no conversation, and Luna sees it as a contact who never wrote. A template does not look up the conversation and goes to the phone as you wrote it. If the contact wrote **without a phone number** (BSUID only), the event's `wa_id` is null: send with `recipient`, equal to the event's `user_id`, and not with `to`. See [Users without a phone number (BSUID)](https://lunahia.com.br/en/docs/users-without-phone). ### Check the window before sending `GET /v1/conversations` returns one row per correspondent, per number, from the most active to the most idle. `messages:read` scope. Each conversation carries `numberId` (the Luna number, the same id as `GET /v1/numbers`, equal to `phoneNumberId`), `externalId` (the label you gave to the customer who owns the number, or null) and `contactName`, the name the correspondent shows on WhatsApp, as Meta sent it on the latest received message that carried one (null if they never sent it). To find a person’s conversations, filter by `?waId=`, with exact match (a Brazilian mobile number matches with and without the ninth digit): it returns their conversation on each number. ```bash curl -X GET "https://api.lunahia.com.br/v1/conversations?phoneNumberId=YOUR_NUMBER_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/conversations?phoneNumberId=YOUR_NUMBER_ID', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/conversations?phoneNumberId=YOUR_NUMBER_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` `200` response (trimmed) ```json { "data": [ { "id": "0f2c8e6a-1d3b-4a5c-9e7f-2b4d6a8c0e12", "waId": "5511999990000", "phoneNumberId": "7a1c9d3e-5f2b-4c8a-9d6e-1b3f5a7c9e11", "displayNumber": "+55 11 99999-0000", "lastMessage": { "direction": "inbound", "type": "text", "bodyText": "Oi! Queria saber o status do meu pedido.", "createdAt": "2026-10-06T14:02:11.482Z" }, "windowOpen": true, "windowExpiresAt": "2026-10-07T14:02:11.482Z", "windowSource": "usuario" } ], "nextCursor": null } ``` - `windowOpen: true` means you can send a free-form message to that correspondent now. `false` means the path is a template. - `windowExpiresAt` says when the window closes, and `windowSource` says what opened it: `usuario` (user), `anuncio` (ad) or `desconhecido` (unknown). The value `template` exists in the vocabulary and is no longer written, because sending a template does not open the window. When there is no known window, the fields come back null or false, never absent. - The conversation `id` is what `GET /v1/messages?conversationId=` accepts. The `phoneNumberId` filter takes Luna’s UUID or Meta’s id, and `externalId` filters by the numbers of one of your customers. - A limitation worth knowing: grouping is by the `waId` the platform recorded. If the identifier Meta recorded differs from the one typed at send time, the same person can show up in two conversations. - The response carries no count at all: no total, no counter per correspondent. ## Idempotency Send the `Idempotency-Key` header if you retry. With it, repeating the request does not produce a second send. The text example above already sends it, with a new UUID on each call. - The header is optional. Whoever does not retry does not need it. - The accepted format is 1 to 255 visible characters, no space (a UUID fits easily). An empty header, a longer one or one with a space answers `400` with `campos: [{campo: "Idempotency-Key"}]`, and nothing is sent. If you do not want idempotency, do not send the header. - The key is a value **you** choose for each logical message. One UUID for each message works. Reuse the same key only when retrying the same message. - The same key with the **same body** returns the original message, with the same `202` and the same `id`. The same key with a **different body** answers `409` with `error: "idempotency_key_reused"`, and nothing is sent: a key identifies one message, not a conversation. For a new message, use a new key. - **For an AI agent, the key is deterministic.** Instead of a new UUID on each attempt, use a key that comes from the message you are answering, such as `resp-`, with the received message’s `id`. Webhook delivery is at least once, and your handling can run twice for the same event: with the same key, both attempts become a single reply. The complete loop is in [AI agent](https://lunahia.com.br/en/docs/ai-agent#idempotencia). - The key’s scope is your account: the same key on two accounts is accepted on both. - The guarantee also holds when the retry crosses the turn of the month. ## Reply with a quote To reply to a specific message, so the contact sees the quote, send `context.message_id` on any text, media, location, contacts or interactive send. It accepts Luna’s `id` (the `message.id` of the `message.received` event, or the `id` this send returned) **or** Meta’s `wamid`. Luna swaps the `id` for the `wamid` before sending. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "text": { "body": "Sim, o seu pedido sai hoje." }, "context": { "message_id": "YOUR_MESSAGE_ID" } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID(), }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "text": { "body": "Sim, o seu pedido sai hoje." }, "context": { "message_id": "YOUR_MESSAGE_ID" } }), }); console.log(res.status, await res.json()); ``` ```python import os import uuid import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", "Idempotency-Key": str(uuid.uuid4()), }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "text": { "body": "Sim, o seu pedido sai hoje.", }, "context": { "message_id": "YOUR_MESSAGE_ID", }, }, timeout=10, ) print(res.status_code, res.json()) ``` - **Template and reaction do not accept it.** Meta does not allow quoting in those two types, and Luna answers `400` with `campo: "context"` and the reason, before queueing. - **The `id` has to be a message from the same conversation**: the same number and the same recipient. An `id` that does not exist, that belongs to another account or another conversation answers `400` with `campo: "context.message_id"`. - **The quoted message must already have been accepted by Meta.** A message you just sent only has a `wamid` after `sent`. Before that, Luna answers `400` and asks you to try again. - With `Idempotency-Key`, repeating the request quoting by `id` or by the `wamid` of the same message counts as the same body. ## The message types All of them use `POST /v1/messages` with `from`, `to` and `type`. Below, only what changes in each type. All but reaction and template require the window to be open. > **The body is strict.** A field Luna does not know, at any level, answers `400` with the field name and the reason `Campo não reconhecido por esta rota.`, instead of being silently dropped. If your send came back `202`, every field you sent was read. That is why what belongs to the type goes **inside the type’s object**, never at the top of the body: `image.caption`, `document.filename`, `location.latitude`. ### Text `type: "text"` (or omitted), with `text.body` from 1 to 4096 characters. It is the example in the previous section. ### Image `type: "image"`, with `image.link` **or** `image.id`, never both. `image.caption` up to 1024 characters. See [media](#midia) to choose between `link` and `id`. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "image", "image": { "link": "https://example.com/pedido.jpg", "caption": "Seu pedido saiu para entrega." } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "image", "image": { "link": "https://example.com/pedido.jpg", "caption": "Seu pedido saiu para entrega." } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "image", "image": { "link": "https://example.com/pedido.jpg", "caption": "Seu pedido saiu para entrega.", }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Document `type: "document"`, with `document.link` or `document.id`. `document.filename` (up to 240 characters) is the name the file shows under for the recipient, and `document.caption` is up to 1024. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "document", "document": { "id": "YOUR_MEDIA_ID", "filename": "nota-fiscal.pdf", "caption": "Sua nota fiscal." } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "document", "document": { "id": "YOUR_MEDIA_ID", "filename": "nota-fiscal.pdf", "caption": "Sua nota fiscal." } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "document", "document": { "id": "YOUR_MEDIA_ID", "filename": "nota-fiscal.pdf", "caption": "Sua nota fiscal.", }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Video `type: "video"`, with `video.link` or `video.id`, and `video.caption` up to 1024 characters. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "video", "video": { "id": "YOUR_MEDIA_ID", "caption": "Veja como montar." } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "video", "video": { "id": "YOUR_MEDIA_ID", "caption": "Veja como montar." } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "video", "video": { "id": "YOUR_MEDIA_ID", "caption": "Veja como montar.", }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Audio `type: "audio"`, with `audio.link` or `audio.id`. Audio has no caption. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "audio", "audio": { "id": "YOUR_MEDIA_ID" } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "audio", "audio": { "id": "YOUR_MEDIA_ID" } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "audio", "audio": { "id": "YOUR_MEDIA_ID", }, }, timeout=10, ) print(res.status_code, res.json()) ``` **Voice message.** With `audio.voice: true`, the audio arrives as a voice message (the bubble with the waveform), not as a file. Meta requires an **.ogg file with the OPUS codec**. Luna does not convert audio: convert before sending. If `audio.link` ends in an audio extension that is not OGG, such as `.mp3`, Luna answers `400` and says so, instead of spending the send. With `audio.id`, Luna cannot see the file type, and the check is Meta’s: the wrong file comes back as `message.status` with `failed`. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "audio", "audio": { "link": "https://example.com/resposta.ogg", "voice": true } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "audio", "audio": { "link": "https://example.com/resposta.ogg", "voice": true } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "audio", "audio": { "link": "https://example.com/resposta.ogg", "voice": True, }, }, timeout=10, ) print(res.status_code, res.json()) ``` Convert an MP3 (for example, a speech synthesizer’s voice) to OGG with OPUS, with ffmpeg ```text ffmpeg -i entrada.mp3 -c:a libopus -b:a 32k -ar 48000 -ac 1 saida.ogg ``` ### Sticker `type: "sticker"`, with `sticker.link` or `sticker.id`. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "sticker", "sticker": { "id": "YOUR_MEDIA_ID" } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "sticker", "sticker": { "id": "YOUR_MEDIA_ID" } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "sticker", "sticker": { "id": "YOUR_MEDIA_ID", }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Location `type: "location"`, with `location.latitude` (-90 to 90) and `location.longitude` (-180 to 180), and optional `location.name` and `location.address`, up to 1000 characters. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "location", "location": { "latitude": -19.9227, "longitude": -43.9451, "name": "Praça da Liberdade", "address": "Belo Horizonte, MG" } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "location", "location": { "latitude": -19.9227, "longitude": -43.9451, "name": "Praça da Liberdade", "address": "Belo Horizonte, MG" } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "location", "location": { "latitude": -19.9227, "longitude": -43.9451, "name": "Praça da Liberdade", "address": "Belo Horizonte, MG", }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Contacts `type: "contacts"`, with a list of one to twenty cards. Each card requires `name.formatted_name`, and accepts `phones`, `emails`, `addresses`, `urls`, `org` and `birthday` (`YYYY-MM-DD`). ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "contacts", "contacts": [ { "name": { "formatted_name": "Ana Souza", "first_name": "Ana", "last_name": "Souza" }, "phones": [ { "phone": "+55 11 99999-0001", "type": "CELL" } ] } ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "contacts", "contacts": [ { "name": { "formatted_name": "Ana Souza", "first_name": "Ana", "last_name": "Souza" }, "phones": [ { "phone": "+55 11 99999-0001", "type": "CELL" } ] } ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "contacts", "contacts": [ { "name": { "formatted_name": "Ana Souza", "first_name": "Ana", "last_name": "Souza", }, "phones": [ { "phone": "+55 11 99999-0001", "type": "CELL", }, ], }, ], }, timeout=10, ) print(res.status_code, res.json()) ``` ### Reaction `type: "reaction"`, with the `wamid` of the message receiving the reaction in `reaction.message_id` and the `emoji`. Send an empty `emoji` to remove a reaction you had put. It goes through even with the window closed. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "reaction", "reaction": { "message_id": "wamid.EXAMPLE_NOT_A_REAL_ID", "emoji": "👍" } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "reaction", "reaction": { "message_id": "wamid.EXAMPLE_NOT_A_REAL_ID", "emoji": "👍" } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "reaction", "reaction": { "message_id": "wamid.EXAMPLE_NOT_A_REAL_ID", "emoji": "👍", }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Interactive: reply buttons `type: "interactive"` with `interactive.type: "button"`. One to three buttons. Each button’s `id` (up to 256 characters) comes back in the `message.received` event when it is tapped, in `message.interactive.id`, and the `title` is up to 20 characters. The body (`body.text`) goes up to 1024, and the footer (`footer.text`) up to 60. The header (`header`) is optional, and can be text (up to 60 characters), image, video or document. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "button", "body": { "text": "Podemos confirmar a entrega para amanhã?" }, "action": { "buttons": [ { "type": "reply", "reply": { "id": "confirma", "title": "Confirmar" } }, { "type": "reply", "reply": { "id": "remarca", "title": "Remarcar" } } ] } } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "button", "body": { "text": "Podemos confirmar a entrega para amanhã?" }, "action": { "buttons": [ { "type": "reply", "reply": { "id": "confirma", "title": "Confirmar" } }, { "type": "reply", "reply": { "id": "remarca", "title": "Remarcar" } } ] } } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "button", "body": { "text": "Podemos confirmar a entrega para amanhã?", }, "action": { "buttons": [ { "type": "reply", "reply": { "id": "confirma", "title": "Confirmar", }, }, { "type": "reply", "reply": { "id": "remarca", "title": "Remarcar", }, }, ], }, }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Interactive: list `interactive.type: "list"`. `action.button` is the label of the button that opens the list (up to 20 characters). One to ten sections, and one to ten rows per section. Each row has `id` (up to 200), `title` (up to 24) and an optional `description` (up to 72). The section `title` is up to 24 characters. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "list", "body": { "text": "Qual horário fica melhor?" }, "action": { "button": "Ver horários", "sections": [ { "title": "Manhã", "rows": [ { "id": "h09", "title": "09:00" }, { "id": "h10", "title": "10:00", "description": "Primeiro horário livre" } ] } ] } } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "list", "body": { "text": "Qual horário fica melhor?" }, "action": { "button": "Ver horários", "sections": [ { "title": "Manhã", "rows": [ { "id": "h09", "title": "09:00" }, { "id": "h10", "title": "10:00", "description": "Primeiro horário livre" } ] } ] } } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "list", "body": { "text": "Qual horário fica melhor?", }, "action": { "button": "Ver horários", "sections": [ { "title": "Manhã", "rows": [ { "id": "h09", "title": "09:00", }, { "id": "h10", "title": "10:00", "description": "Primeiro horário livre", }, ], }, ], }, }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Interactive: link button `interactive.type: "cta_url"`. One button with `display_text` (up to 20 characters) and `url` (up to 2048), in `action.parameters`. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "cta_url", "body": { "text": "Acompanhe o seu pedido pelo link." }, "action": { "parameters": { "display_text": "Acompanhar", "url": "https://example.com/pedido/88213" } } } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "cta_url", "body": { "text": "Acompanhe o seu pedido pelo link." }, "action": { "parameters": { "display_text": "Acompanhar", "url": "https://example.com/pedido/88213" } } } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "cta_url", "body": { "text": "Acompanhe o seu pedido pelo link.", }, "action": { "parameters": { "display_text": "Acompanhar", "url": "https://example.com/pedido/88213", }, }, }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Interactive: location request `interactive.type: "location_request_message"`. Only `body.text` (up to 1024 characters): Luna sets the `send_location` action, which shows the contact the "Send location" button. The answer arrives in `message.received` with `type: "location"`, in the `message.location` field. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "location_request_message", "body": { "text": "Para calcular o frete, compartilhe a sua localização." } } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "location_request_message", "body": { "text": "Para calcular o frete, compartilhe a sua localização." } } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "location_request_message", "body": { "text": "Para calcular o frete, compartilhe a sua localização.", }, }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Interactive: address request `interactive.type: "address_message"`, with `body.text` and, in `action.parameters`, `country` (two letters, the default is `BR`) and, if you want, `values` (fields already filled in), `saved_addresses` (up to 20) and `validation_errors`. The address field names are the ones Meta defines for the country, and Luna passes them on as they came. **Meta documents this feature for few countries, and whether it works for Brazil is still to be confirmed in Meta’s documentation**: when it does not, Meta refuses the send and the reason arrives in the `message.status` event. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "address_message", "body": { "text": "Confirme o endereço de entrega." }, "action": { "parameters": { "country": "BR" } } } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "address_message", "body": { "text": "Confirme o endereço de entrega." }, "action": { "parameters": { "country": "BR" } } } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "address_message", "body": { "text": "Confirme o endereço de entrega.", }, "action": { "parameters": { "country": "BR", }, }, }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Interactive: media carousel `interactive.type: "carousel"`, with `body.text` and two to ten cards in `action.cards`. Each card has `card_index` (0 to 9, no repeats), `header` with an image or a video (by `id` or `link`, as in media), an optional `body.text` (up to 160 characters) and a link button in `action.parameters` (`display_text` and `url`). The limits on cards and text are Meta’s, and they are still to be confirmed in its documentation. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "carousel", "body": { "text": "Veja as novidades da semana." }, "action": { "cards": [ { "card_index": 0, "header": { "type": "image", "image": { "link": "https://example.com/camiseta.jpg" } }, "body": { "text": "Camiseta básica" }, "action": { "parameters": { "display_text": "Comprar", "url": "https://example.com/camiseta" } } }, { "card_index": 1, "header": { "type": "image", "image": { "link": "https://example.com/bone.jpg" } }, "body": { "text": "Boné" }, "action": { "parameters": { "display_text": "Comprar", "url": "https://example.com/bone" } } } ] } } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "carousel", "body": { "text": "Veja as novidades da semana." }, "action": { "cards": [ { "card_index": 0, "header": { "type": "image", "image": { "link": "https://example.com/camiseta.jpg" } }, "body": { "text": "Camiseta básica" }, "action": { "parameters": { "display_text": "Comprar", "url": "https://example.com/camiseta" } } }, { "card_index": 1, "header": { "type": "image", "image": { "link": "https://example.com/bone.jpg" } }, "body": { "text": "Boné" }, "action": { "parameters": { "display_text": "Comprar", "url": "https://example.com/bone" } } } ] } } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "carousel", "body": { "text": "Veja as novidades da semana.", }, "action": { "cards": [ { "card_index": 0, "header": { "type": "image", "image": { "link": "https://example.com/camiseta.jpg", }, }, "body": { "text": "Camiseta básica", }, "action": { "parameters": { "display_text": "Comprar", "url": "https://example.com/camiseta", }, }, }, { "card_index": 1, "header": { "type": "image", "image": { "link": "https://example.com/bone.jpg", }, }, "body": { "text": "Boné", }, "action": { "parameters": { "display_text": "Comprar", "url": "https://example.com/bone", }, }, }, ], }, }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Interactive: Flow `interactive.type: "flow"`. The Flow has to exist and be published on the number’s business account, in the WhatsApp Manager: Luna only **sends** it, it does not create or publish Flows. Identify it with `flow_id` **or** `flow_name` (exactly one, otherwise `400`), give the button label in `flow_cta` and, to tie the answer to this send, pass a `flow_token`. `flow_action_payload` opens the Flow on a screen (`screen`) with the `data` you choose. Use `mode: "draft"` to test a Flow that is not published yet. The contact’s answer arrives in `message.received` as `interactive.type: "nfm_reply"`, with the answers in `response_json`. See [Receive events](https://lunahia.com.br/en/docs/receive-events). ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "flow", "body": { "text": "Agende a sua visita em poucos toques." }, "action": { "parameters": { "flow_id": "1234567890", "flow_cta": "Agendar", "flow_token": "agendamento-88213", "flow_action_payload": { "screen": "INICIO", "data": { "nome": "Ana" } } } } } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "flow", "body": { "text": "Agende a sua visita em poucos toques." }, "action": { "parameters": { "flow_id": "1234567890", "flow_cta": "Agendar", "flow_token": "agendamento-88213", "flow_action_payload": { "screen": "INICIO", "data": { "nome": "Ana" } } } } } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "flow", "body": { "text": "Agende a sua visita em poucos toques.", }, "action": { "parameters": { "flow_id": "1234567890", "flow_cta": "Agendar", "flow_token": "agendamento-88213", "flow_action_payload": { "screen": "INICIO", "data": { "nome": "Ana", }, }, }, }, }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Interactive: catalog product `interactive.type: "product"` and `"product_list"`. Luna only **sends** the message from a catalog that already exists on the number’s business account: it does not create, read or edit a catalog or product. `action.catalog_id` is the catalog identifier, and `product_retailer_id` is the product’s content ID (the SKU) in it. If none of the products sent exists in the catalog, Meta refuses it, and the reason arrives in `message.status` with `failed`. - `product` shows one product. `body` and `footer` are optional (body up to 1024 characters, footer up to 60), and it takes no `header`. - `product_list` shows a list: `header` (always `type: "text"`, up to 60 characters) and `body` are required, `footer` is optional. `action.sections` has one to ten sections, each with a `title` (up to 24 characters) and `product_items`, and **at most 30 products in total**. With more than one section, every one needs a `title`. Breaking one of these rules answers `400` with the field, before the `202`. - Like every interactive message, they require the 24-hour window to be open. When the customer picks items and sends the cart, the reply arrives in `message.received` with `order`. - The text limits are those of the other interactive messages. Meta’s docs fix the 30-product ceiling; Meta checks the rest, and a refusal from it arrives as `failed`. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "product", "body": { "text": "Esta é a ração que você pediu." }, "footer": { "text": "Estoque limitado" }, "action": { "catalog_id": "1234567890", "product_retailer_id": "RACAO-10KG" } } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "product", "body": { "text": "Esta é a ração que você pediu." }, "footer": { "text": "Estoque limitado" }, "action": { "catalog_id": "1234567890", "product_retailer_id": "RACAO-10KG" } } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "product", "body": { "text": "Esta é a ração que você pediu.", }, "footer": { "text": "Estoque limitado", }, "action": { "catalog_id": "1234567890", "product_retailer_id": "RACAO-10KG", }, }, }, timeout=10, ) print(res.status_code, res.json()) ``` ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "product_list", "header": { "type": "text", "text": "Mais vendidos" }, "body": { "text": "Escolha à vontade." }, "action": { "catalog_id": "1234567890", "sections": [ { "title": "Rações", "product_items": [ { "product_retailer_id": "RACAO-10KG" }, { "product_retailer_id": "RACAO-3KG" } ] }, { "title": "Petiscos", "product_items": [ { "product_retailer_id": "OSSO-1" } ] } ] } } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "product_list", "header": { "type": "text", "text": "Mais vendidos" }, "body": { "text": "Escolha à vontade." }, "action": { "catalog_id": "1234567890", "sections": [ { "title": "Rações", "product_items": [ { "product_retailer_id": "RACAO-10KG" }, { "product_retailer_id": "RACAO-3KG" } ] }, { "title": "Petiscos", "product_items": [ { "product_retailer_id": "OSSO-1" } ] } ] } } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "interactive", "interactive": { "type": "product_list", "header": { "type": "text", "text": "Mais vendidos", }, "body": { "text": "Escolha à vontade.", }, "action": { "catalog_id": "1234567890", "sections": [ { "title": "Rações", "product_items": [ { "product_retailer_id": "RACAO-10KG", }, { "product_retailer_id": "RACAO-3KG", }, ], }, { "title": "Petiscos", "product_items": [ { "product_retailer_id": "OSSO-1", }, ], }, ], }, }, }, timeout=10, ) print(res.status_code, res.json()) ``` ### Template `type: "template"`, with `template.name` and `template.language.code` (for example `pt_BR`, which must match the approved language) and the `components` that fill the variables. It is what opens a conversation outside the window. See [Templates](https://lunahia.com.br/en/docs/templates#enviar). ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "confirmacao_de_pedido", "language": { "code": "pt_BR" }, "components": [ { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana" } ] } ] } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID(), }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "confirmacao_de_pedido", "language": { "code": "pt_BR" }, "components": [ { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana" } ] } ] } }), }); console.log(res.status, await res.json()); ``` ```python import os import uuid import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", "Idempotency-Key": str(uuid.uuid4()), }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "confirmacao_de_pedido", "language": { "code": "pt_BR", }, "components": [ { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana", }, ], }, ], }, }, timeout=10, ) print(res.status_code, res.json()) ``` ## Media Image, video, audio, document and sticker accept two ways of pointing at the file. Use one or the other, never both. - `link`: the file’s public URL, which Meta downloads at send time. It must answer without authentication. - `id`: the identifier of a file you already uploaded. With it Meta does not need to download anything from your infrastructure, sending is faster, and you reuse the same file across messages. Meta keeps an uploaded file for 30 days. After that, upload again. ### Audio in MP3 A voice message (`audio.voice: true`) requires **OGG with the OPUS codec**, and Luna **does not convert** audio: convert before sending or uploading the file. If your voice is in MP3 (for example, the output of a speech synthesizer), convert it with ffmpeg. The command below produces OPUS at 48 kHz, mono, which is what a WhatsApp voice message uses. Convert MP3 to OGG with OPUS ```text ffmpeg -i entrada.mp3 -c:a libopus -b:a 32k -ar 48000 -ac 1 saida.ogg ``` ### Upload a file `POST /v1/numbers/{id}/media`, as `multipart/form-data`, in the `file` field. The `id` in the URL is the number’s **at Luna**. `messages:write` scope. The response carries the `mediaId`, not a URL: Meta’s download URL expires in five minutes, and a stored URL is born wrong. ```bash curl -X POST "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/media" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -F "file=@./pedido.jpg;type=image/jpeg" ``` ```js import { readFile } from 'node:fs/promises'; const form = new FormData(); form.append( 'file', new Blob([await readFile('./pedido.jpg')], { type: 'image/jpeg' }), 'pedido.jpg', ); const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/media', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, body: form, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/media", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, files={"file": ("pedido.jpg", open("pedido.jpg", "rb"), "image/jpeg")}, timeout=10, ) print(res.status_code, res.json()) ``` `200` response ```json { "mediaId": "1425835918205946" } ``` A file above the platform ceiling (100 MiB, the same for every customer) is refused with `413` before any call to Meta. ### Download through the notice link The `message.received` notice (and `message.echo`) already carries the link to download the file in `message.media.url`, shaped like `https://api.lunahia.com.br/v1/media/{token}`. Make a `GET` on it, **without** an API key, and follow the redirect: the answer is a `302` to a signed URL that lasts a few minutes. - Whoever has the link downloads the file. Treat it as sensitive data: do not log it, do not send it over a channel you do not control and do not store it where other people can read it. - The link is the same on every redelivery and every replay of the notice, and is valid for 30 days counted from the message receipt. After that, and for a link that does not exist, the answer is `404`. The media keeps coming out of `GET /v1/messages/{id}/media`, with a key, until the end of the 90-day retention. - The notice can arrive before Luna finishes downloading the file from Meta. In that case the link answers `409` with `error: "media_not_ready"`, `estado: "pendente"` and the `Retry-After` header, in seconds: wait that long and try again. `falhou` (failed) and `expirado` (expired) also answer `409`, without `Retry-After`. - `url` is null when the message has no file Luna can obtain (Meta sent no identifier, or the fetch deadline passed). - The route has a per-minute request ceiling per source address, the same for everyone. Downloading and saving the file through the link, waiting while Luna is still downloading: ```js import { writeFile } from 'node:fs/promises'; const EXTENSIONS = { 'image/jpeg': '.jpg', 'image/png': '.png', 'audio/ogg': '.ogg', 'application/pdf': '.pdf' }; // Downloads the file from the media.url of a message.received notice. async function downloadFromLink(link, name, attempts = 6) { for (let i = 0; i < attempts; i++) { const res = await fetch(link); // no Authorization header: the token inside the link is the credential. Never log the link. if (res.status === 409) { // 409 media_not_ready: Luna is still downloading from Meta, wait what Retry-After says and try again const seconds = Math.min(Number(res.headers.get('retry-after') ?? 5), 30); await new Promise((resolve) => setTimeout(resolve, seconds * 1000)); continue; } if (res.status === 404) return null; // 404: the link expired (30 days) or never existed. GET /v1/messages/{id}/media still works, with a key. if (!res.ok) throw new Error('media link answered ' + res.status); const type = (res.headers.get('content-type') ?? '').split(';')[0]; const file = name + (EXTENSIONS[type] ?? ''); await writeFile(file, Buffer.from(await res.arrayBuffer())); return file; } return null; } console.log(await downloadFromLink(process.env.LUNA_MEDIA_URL, 'arquivo')); ``` ```python import os import time import urllib.error import urllib.request EXTENSIONS = {"image/jpeg": ".jpg", "image/png": ".png", "audio/ogg": ".ogg", "application/pdf": ".pdf"} def download_from_link(link, name, attempts=6): # Downloads the file from the media.url of a message.received notice. for _ in range(attempts): try: # no Authorization header: the token inside the link is the credential. Never log the link. with urllib.request.urlopen(link, timeout=60) as file: data = file.read() extension = EXTENSIONS.get(file.headers.get_content_type(), "") except urllib.error.HTTPError as err: if err.code == 409: # 409 media_not_ready: Luna is still downloading from Meta, wait what Retry-After says and try again time.sleep(min(int(err.headers.get("Retry-After", "5")), 30)) continue if err.code == 404: return None # 404: the link expired (30 days) or never existed. GET /v1/messages/{id}/media still works, with a key. raise with open(name + extension, "wb") as out: out.write(data) return name + extension return None print(download_from_link(os.environ["LUNA_MEDIA_URL"], "arquivo")) ``` ### Download media the customer sent `GET /v1/messages/{id}/media` returns a signed URL, issued by Luna, for the media it has already stored. `messages:read` scope. It is the path with a key, and it remains valid next to the notice link: use it for an old message, or when the link has expired. ```bash curl -X GET "https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/media" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/media', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID/media", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` `200` response ```json { "url": "https://EXAMPLE.r2.cloudflarestorage.com/EXAMPLE_BUCKET/midia/EXAMPLE_KEY?X-Amz-Expires=300&X-Amz-Signature=EXAMPLE", "expiraEm": "2026-10-06T14:07:11.482Z" } ``` - The URL expires in a few minutes and is a bearer credential: whoever holds it downloads the file, without presenting a key. Do not store it, do not log it, and do not send it over a channel you do not control. When it expires, call the route again. - If the media has not been fetched yet, the response is `409` with `error: "media_not_ready"` and the current `estado`, with no URL. `pendente` (pending) and `falhou` (failed) come back on their own, because the sweep retries within Meta’s seven-day window. `expirado` (expired) is final. - A message **with no media** (a text one, for example) answers `404 not_found`, the same as a message that does not exist or belongs to another customer: there is no separate error. `409 media_not_ready` is only for media that exists and has not been fetched yet. - The URL points to Luna’s storage, never to Meta, and does not carry a brand domain. Downloading and saving the file (the URL is already signed, so the second call does **not** carry `Authorization`): ```js import { writeFile } from 'node:fs/promises'; const API = process.env.LUNA_API_URL ?? 'https://api.lunahia.com.br'; const KEY = process.env.LUNA_API_KEY; const EXTENSIONS = { 'image/jpeg': '.jpg', 'image/png': '.png', 'audio/ogg': '.ogg', 'application/pdf': '.pdf' }; // Downloads the media of a received message. async function downloadMedia(messageId) { const res = await fetch(API + '/v1/messages/' + messageId + '/media', { headers: { Authorization: 'Bearer ' + KEY }, }); if (res.status === 404) return null; // a message with no media answers 404, the same as one that does not exist if (res.status === 409) return null; // media_not_ready: Luna is still fetching it, try again in a few seconds if (!res.ok) throw new Error('media route answered ' + res.status); const link = await res.json(); // the URL is already signed and lasts a few minutes: no Authorization header const file = await fetch(link.url); const type = (file.headers.get('content-type') ?? '').split(';')[0]; const name = messageId + (EXTENSIONS[type] ?? ''); await writeFile(name, Buffer.from(await file.arrayBuffer())); return name; } console.log(await downloadMedia(process.env.LUNA_MESSAGE_ID)); ``` ```python import json import os import urllib.error import urllib.request API = os.environ.get("LUNA_API_URL", "https://api.lunahia.com.br") KEY = os.environ["LUNA_API_KEY"] EXTENSIONS = {"image/jpeg": ".jpg", "image/png": ".png", "audio/ogg": ".ogg", "application/pdf": ".pdf"} def download_media(message_id): # Downloads the media of a received message. req = urllib.request.Request( f"{API}/v1/messages/{message_id}/media", headers={"Authorization": f"Bearer {KEY}"}, ) try: with urllib.request.urlopen(req, timeout=15) as res: link = json.load(res) except urllib.error.HTTPError as err: if err.code == 404: return None # a message with no media answers 404, the same as one that does not exist if err.code == 409: return None # media_not_ready: Luna is still fetching it, try again in a few seconds raise # the URL is already signed and lasts a few minutes: no Authorization header with urllib.request.urlopen(link["url"], timeout=60) as file: data = file.read() extension = EXTENSIONS.get(file.headers.get_content_type(), "") name = message_id + extension with open(name, "wb") as out: out.write(data) return name print(download_media(os.environ["LUNA_MESSAGE_ID"])) ``` ## Follow delivery The main path is the webhook: each state change arrives as `message.status`, and so does a failure, including the refusal Meta gives in its own response to the send (in it the event’s `wamid` is null, and `id` is the key). See [Receive events](https://lunahia.com.br/en/docs/receive-events#eventos). To look a message up on the spot, or to reconcile, use `GET /v1/messages/{id}` (`messages:read` scope). ```bash curl -X GET "https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/messages/YOUR_MESSAGE_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` `200` response ```json { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "wamid": null, "content": null, "status": "failed", "criadaEm": "2026-10-06T14:02:11.000Z", "enviadaEm": null, "entregueEm": null, "lidaEm": null, "erros": [ { "codigo": 131026, "categoria": "nao_entregavel", "mensagem": "O destinatário não pode receber esta mensagem: o número não tem WhatsApp, ou não existe.", "acaoRecomendada": "Confira o número do destinatário e reenvie para o número correto. Repetir o envio para o mesmo número não muda o resultado.", "original": { "error": { "message": "Message undeliverable", "type": "OAuthException", "code": 131026, "fbtrace_id": "EXAMPLE_TRACE_ID" } } } ] } ``` - `wamid` is Meta’s identifier, the same one the events carry, and it is null until Meta has accepted the send. `content` carries what the message holds besides its text, in both directions. On a **received** message, with Meta’s names, the same content as the `message.received` event. On a **sent** message, what you sent, read back, so support can answer "what did the bot send this customer?": in `template`, the `name`, the `language` and the variable values (`variables`); in `sent_interactive`, the `body`, the buttons (`buttons`) or items (`items`) and the URL button’s address (`cta.url`); in `media`, the caption and the `filename`, without the file link; and `location`, `reaction`, `contacts` and `context` as on a received one. It is null on a sent text message (the text is in `bodyText`). - `status` is the latest state of a sent message, in the order of the table below. It is null on a received message, which has no delivery state. - `enviadaEm` (sent), `entregueEm` (delivered) and `lidaEm` (read) are null while the step has not happened. `lidaEm` also stays null when the recipient turns read receipts off. - `erros` lists what went wrong, in order of occurrence, and is empty when nothing did. See [Errors](https://lunahia.com.br/en/docs/errors#envio). - `pricing` is the cost Meta applied to the message, with its names (`billable`, `pricing_model`, `type`, `category`), and it is null until Meta has reported it. See [Meta costs](https://lunahia.com.br/en/docs/meta-costs#conferir). - The response carries no attempt count or any usage number. ## The message states The state only moves forward. A message goes through them in this order, and may skip steps: Meta does not send `delivered` when delivery and reading coincide, so `sent` followed by `read` is normal. | State | Where it shows | Meaning | | --- | --- | --- | | `queued` | Only in the send `202` response | The message was accepted and is in the outbound queue. It is what Luna calls the `accepted` state at accept time. | | `accepted` | `GET /v1/messages/{id}` and the list, right after the `202` | Still in the queue: Meta has not received the message. | | `sent` | Lookup and `message.status` event | Meta accepted the send. | | `delivered` | Lookup and event | It reached the recipient’s device. | | `read` | Lookup and event | The recipient read it. It does not come if they turned read receipts off. | | `played` | Lookup and event | The recipient played the voice message. | | `failed` | Lookup and event | The message did not go out or did not arrive. The reason is in `erros` and, in the event, in `error_code`. It is the highest state: nothing replaces it afterwards. | | `canceled` | Lookup and event | You canceled the message in the queue with `DELETE /v1/messages/{id}` and Meta never received it. It is terminal. Only a message still in `accepted` can be canceled; once the send goes out, the answer is `409`. | ### The history `GET /v1/messages` returns what came in and went out, newest first. Filter by number with `phoneNumberId`, by one of your customers with `externalId`, by correspondent with `conversationId` or `waId` (the phone number, digits only; a Brazilian mobile number matches with and without the ninth digit), and by `wamid` to find the message behind an event. Each message carries `content` with what it holds besides its text: on a received one, the same content as the `message.received` event; on a sent one, what you sent (the template with its variables, the buttons, the caption). `limit` goes from 1 to 100. To page through, send the previous response’s `nextCursor` back in the `cursor` parameter. When it comes back null, you are done. The cursor is opaque: do not try to build one by hand. A parameter the route does not know answers `400` naming it. ```bash curl -X GET "https://api.lunahia.com.br/v1/messages?conversationId=YOUR_CONVERSATION_ID&limit=20" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages?conversationId=YOUR_CONVERSATION_ID&limit=20', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/messages?conversationId=YOUR_CONVERSATION_ID&limit=20", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` `200` response (trimmed) ```json { "data": [ { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "direction": "outbound", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "type": "text", "bodyText": "Olá! Recebemos seu pedido e já estamos preparando.", "content": null, "status": "delivered", "waId": "5511999990000", "displayNumber": "+55 11 99999-0000", "createdAt": "2026-10-06T14:02:11.000Z" } ], "nextCursor": null } ``` > On a `429`, `409` or another error, see [Errors](https://lunahia.com.br/en/docs/errors). The full contract of `POST /v1/messages` is in the [API reference](https://lunahia.com.br/en/docs/reference), in the Messages section. ## Route details for this guide The [API reference](https://lunahia.com.br/en/docs/reference) says how to call each route, in a few lines. What explains the reason for each decision, the edge cases and the warnings is here, in the order of the reference. ### GET /v1/messages Filter by number with phoneNumberId, which takes Luna's UUID or Meta's id. Filter by one of your customers with externalId, the label you gave in the connection link: only what went through their numbers comes back. Filter by correspondent with conversationId, the id returned by GET /v1/conversations. Filter by wamid, the Meta identifier that webhook events carry, to find the message behind an event. Filter by waId, the correspondent's phone number, digits only: a Brazilian mobile number matches with and without the ninth digit. Filter by userId, the correspondent's BSUID, when they wrote without a phone number. A parameter the route does not know answers 400 naming it, instead of being ignored. To page through results, send back the nextCursor from the previous response. When it comes back null, you have reached the end. The content field carries what the message holds besides its text, in both directions. On a received one, with Meta's own field names, the same ones as the message.received event. On a sent one, what you sent, read back: template (name, language and variable values), sent_interactive (body, buttons or items and the URL button's address), media (caption and file name, without the link), location, reaction, contacts and context. It is null on a sent text message, which is in bodyText. Each message carries numberId (Luna's number, the id from GET /v1/numbers), externalId (the number's label), conversationId and errorSummary: when the message failed, the code, message and recommended action of the last error, without Meta's original body (it stays in erros, at GET /v1/messages/{id}). To find what failed, filter with ?status=failed. ?direction= (inbound or outbound), ?since= (inclusive) and ?until= (exclusive), in ISO 8601, filter too. createdAt is the date of the message: the one Meta reported, when it is known, and the date it reached Luna otherwise. A conversation imported from the app history (coexistence) carries the real dates, up to 180 days back, and the order of the list, ?since=, ?until= and the cursor all use that same date. To fetch only what arrived after your last call, do not use ?since=: a message imported later has an old date. Use the message.received and message.echo events. The cursor is opaque: it carries position, not a count. Do not try to build one by hand. format=csv answers text/csv, one row for each message returned, with the same filters and the same order: id, direction, wamid, type, bodyText, status, waId, userId, displayNumber, numberId, externalId, conversationId, errorCode, errorMessage and createdAt. Without format=csv the limit goes up to 100; with it, the default and the maximum are 1000 rows per call. If there is more, the next page comes in the X-Luna-Next-Cursor header (absent on the last one): send it in cursor and repeat until the header disappears. The message text comes from outsiders; a cell that would start with =, +, - or @ goes out with an apostrophe in front, so the spreadsheet does not run it as a formula. ### POST /v1/messages Why 202 and not 200: the tightest limit on Meta's platform is the per-recipient one: after a short burst, one message every six seconds. An agent that answers in bursts trips it on its own. Queueing is the product, and returning 429 would just hand the problem back to you under another name. from is the origin number: Luna's UUID (the id GET /v1/numbers returns) or Meta's id (metaPhoneNumberId). Both work. to is the recipient's phone with country and area code, digits only, without the plus sign. In this version Luna starts conversations only with Brazilian phones (they start with 55 and have 12 or 13 digits); any other format is refused with 400, except for someone who already wrote to your number. To answer someone who wrote to you, use the wa_id that came in the event: Meta delivers some Brazilian mobiles without the ninth digit, and Luna finds the conversation with and without it, but no other difference in the phone, so the window shows as closed. For someone who wrote without a phone number (BSUID), send recipient with the event's user_id, in place of to: one of the two, never both, and neither answers 400. An authentication template does not go to a BSUID (Meta requires the phone number) and is refused with 400 before Meta. See [Users without a phone number (BSUID)](https://lunahia.com.br/en/docs/users-without-phone). Send the Idempotency-Key header if you retry. With it, repeating a request does not produce a second send. The same key with the same body returns the original message; the same key with a different body answers 409 idempotency_key_reused, and nothing is sent. This route sends every message type: text, image, video, audio, document, sticker, location, contacts, reaction, interactive and template. The type field says which one; a body without it is read as text, so integrations written before the other types existed keep working unchanged. The service window is enforced here: outside it, free-form messages are refused with 409 before any call to Meta, because a call refused over there is spent for nothing and counts as an error against your number. The response says when the window closed and what to do. Template and reaction go through even with the window closed. A template is the way to start a conversation outside the window, but sending one does not reopen it: the window opens when the contact writes back. Until then, free-form text is still refused with 409. Check GET /v1/conversations to see the window state before you try. When you send a template with a media header, the media goes in the header component of the send, and each message supplies its own. The handle used when the template was created is only the example Meta reviews: it does not become the delivered content, and there is nothing to reuse from it here. To choose between a link and a media identifier, the same recommendation published on POST /v1/numbers/{id}/media applies. To reply by quoting a message, send context.message_id with Luna's id (the message.id of the message.received event, or the id a send returned) or with Meta's wamid. Luna swaps the id for the wamid before sending. Only a message from the same conversation can be quoted, and only one Meta already accepted. Template and reaction do not accept context: the answer is 400, with the reason. To send audio as a voice message, send audio.voice: true with an .ogg file using the OPUS codec. Luna does not convert audio: a link whose extension is another audio format, such as .mp3, is refused with 400. To convert an MP3: ffmpeg -i entrada.mp3 -c:a libopus -b:a 32k -ar 48000 -ac 1 saida.ogg. The body is strict: a field Luna does not know, at any level, answers 400 with the field name, instead of being silently dropped. If the send came back 202, every field you sent was read. ### GET /v1/conversations The order follows real activity and not the date the conversation was opened: one opened months ago and active today comes first. lastMessage carries the newest message of that conversation, and it is content, not a statistical summary. The date of lastMessage and the order follow the message date (the one Meta reported, when known): a conversation imported from the history does not jump to the top for having been imported today. A conversation with no message yet returns a null lastMessage and stays on the list. Each row says whether the service window is open. windowOpen true means you can send a free-form message to that correspondent now; false means the way forward is a template, and free-form messages are accepted again once the contact writes back. windowExpiresAt says when it closes, and windowSource says what opened it: usuario (the contact wrote), anuncio (ad) or desconhecido (unknown). When there is no known window, the three come back null or false, never absent. No count comes out of this route. No total, no counter by correspondent, no aggregate by period. The nextCursor carries position and not quantity, and you should not try to build one by hand. Filter by number with phoneNumberId, which takes Luna's UUID or Meta's id. Filter by one of your customers with externalId, the label you gave in the connection link. To page through results, send back the nextCursor from the previous response. When it comes back null, you have reached the end. Filter by correspondent with waId (the phone number) or userId (the BSUID). Since the BSUID, waId can be null: someone who wrote without the phone number showing has the conversation identified by userId, with parentUserId and username when Meta sends them. When the same conversation carries both, it is one conversation, and its id did not change. One limitation worth knowing before you integrate: the grouping key is waId, the identifier the platform recorded for that correspondent. When the identifier Meta recorded differs from the one typed on the way out, the same human correspondent shows up as two conversations, with two identifiers. Luna returns what the platform recorded and does not guess equivalence, because guessing would be wrong in both directions. ### GET /v1/messages/{id}/media The URL expires in a few minutes and is a bearer credential: whoever holds it downloads the file, without presenting any key. Do not store it, do not put it in logs, and do not send it over a channel you do not control. When it expires, call this route again. The URL never points at Meta. It points at Luna's storage, on the provider's object API domain, because signed URLs do not work with custom domains, so do not expect a branded domain here. If the media has not been fetched yet, the response is 409 with the current state and no URL: pendente and falhou come back on their own, because the sweep retries inside Meta's seven-day window; expirado is final, because past that window the identifier no longer resolves and there is no second key. A message that is not yours returns 404, the same as a message that does not exist. ### GET /v1/media/{token} Whoever has the link downloads the file, with no key. Treat it as sensitive data: do not log it, do not send it over a channel you do not control and do not store it where other people can read it. The token has 256 bits, and the calling address has a per-minute ceiling, the same for everyone. The link is valid for 30 days counted from the message receipt. After that, and for a token that does not exist, the answer is 404, the same in both cases. The media keeps coming out of `GET /v1/messages/{id}/media`, with a key, until the end of the 90-day retention. Ready media answers 302 with `Location` pointing to a signed URL that is valid for a few minutes. Ask for the link again (not the signed URL) when you need to download once more: each call issues a fresh signature. The response carries `cache-control: no-store` and `referrer-policy: no-referrer`. The notice can arrive before Luna finishes downloading the file from Meta. In that case the answer is 409 `media_not_ready` with `estado: "pendente"` and the `Retry-After` header, in seconds: wait that long and call again. `falhou` and `expirado` also answer 409, without `Retry-After`. ### POST /v1/messages/{id}/read This route is synchronous, unlike sending. The reason is that a read receipt loses value with time: the one that arrives half an hour later has already been read, on the other side, as an absence of reading. Queueing it would deliver the signal once it no longer means anything. It only works for a received message. A message you sent, a message that is not yours and a message that does not exist all return the same 404. It is a call to the platform like any other, and it counts against the same pace of your number that sending uses. ### POST /v1/messages/{id}/typing This route is synchronous, and it is the one that depends on that the most: a queued typing indicator would be delivered after the presence had already ended. It is not a late delivery: it is a false statement about the present. One thing to know before you integrate: Meta's platform has no standalone indicator. The indicator is a field of the same body that marks a message as read, and it needs the identifier of a received message to know which conversation to show it in. So calling this route ALSO marks that message as read. There is no way to do one without the other. The indicator clears on its own when you answer, with a ceiling of twenty five seconds on Meta's side. There is no route to turn it off, and none is needed. It counts against the same pace of your number that sending uses. ### POST /v1/numbers/{id}/media The id in the URL is the number: Luna's UUID (the id GET /v1/numbers returns) or Meta's id (metaPhoneNumberId). Both work. Use the identifier instead of a link when sending media: with it Meta does not have to download anything from your infrastructure, sending is faster, and you can reuse the same file across several messages. The identifier is good for thirty days. After that, upload the file again. The response carries no URL, and that is a decision rather than an omission: Meta's download URL expires in five minutes, so a stored URL is a value that is wrong from birth, and a retry using it would fail every time, long after the cause had passed. A file above the ceiling is refused with 413 before any call to Meta, so none of your calls are spent. The ceiling is the same for every customer: it exists for infrastructure capacity, and it does not vary. ### GET /v1/messages/{id} The wamid field is Meta's identifier, the same one webhook events carry: use it to match a received event to this message. It is null until Meta has accepted the send. The content field carries what the message holds besides its text, in both directions. On a received one, with Meta's own field names, the same ones as the message.received event. On a sent one, what you sent, read back: template (name, language and variable values), sent_interactive (body, buttons or items and the URL button's address), media (caption and file name, without the link), location, reaction, contacts and context. It is null on a sent text message, which is in bodyText. The erros field carries the list of what went wrong, in the order it happened. Each item has the explanation in Portuguese and the recommended action, and it carries the original field alongside: Meta's error body, with no rewriting and no filtering, which is what its support recognises. The fbtrace_id inside it is what makes a support ticket move when our explanation is not enough. Take care when passing the response on: the original field may contain the end consumer's phone number and excerpts of the conversation. Treat it with the same care as the rest of your message content before handing it to a third party. The list brings together what Meta refused at send time and what it reported afterwards, through status events. You do not need to know which of the two each item came from: in both cases it refused something, and the recommended action is the one that fixes it. The response carries no retry count, no cost and no consumption figure of any kind. For the full history of your messages, use GET /v1/messages. A message that is not yours returns 404, the same as a message that does not exist. ### DELETE /v1/messages/{id} Only a message still in the outbound queue (accepted) can be canceled. It becomes canceled, a terminal state that nothing replaces, Meta never receives it, and the message.status event with status canceled reaches your webhook. The 204 is already the confirmation: the message will not go out. The event only goes out when its turn comes in the conversation queue, which can take from a few seconds to a minute if many messages were ahead of it or a long typingMs was set. Canceling and sending never both happen: Luna decides in the database, in a single write, which one came first. If the send was already reserved or the message already left, the answer is 409 message_not_cancelable, with the current state in status. Check the result with GET /v1/messages/{id}. It only works for a message you sent. A received message, a message that is not yours and a message that does not exist all return the same 404. ### POST /v1/messages/{id}/replay Each request produces a new delivery, with its own deliveryId. Calling twice produces two deliveries, not an error: the second request is a request, not a repeated click. Use the deliveryId to tell the replay you asked for apart from an automatic retry after a failure. A replay does not jump the queue and does not skip any defence. If your endpoint is down, delivery is deferred and retried by the usual policy, without a single request going out. Asking in bulk will not speed anything up. A received message replays its message.received. A sent message replays its latest message.status, the same as the original and marked as a requested replay; if Meta has not accepted the message yet or no status has arrived, the response is 400. If you have not registered a webhook endpoint yet, the response is 409: there is nowhere to deliver to, and a 202 here would be a confirmation that never comes true. A message that is not yours returns 404, the same as a message that does not exist. The response carries no count of anything, on purpose: no number in this API feeds billing. --- # AI agent: the complete loop Fonte: https://lunahia.com.br/en/docs/ai-agent An AI agent that answers on WhatsApp always does the same loop: it receives an event, checks that it came from Luna, answers fast, thinks and sends the reply. This guide brings the whole loop in code that runs when pasted, in Python (only the standard library) and in Node (only `fetch`), and explains each step. The intelligence is yours: the code calls an `answer` function, which you swap for your model. Each route’s contract, field by field, is in the [API reference](https://lunahia.com.br/en/docs/reference). The small-print terms (24-hour window, template, idempotency) are in the [glossary](https://lunahia.com.br/en/docs/glossary). ## The loop, in eight steps 1. **Receive** Luna’s `POST` at your address and **verify the signature** of the bytes that arrived. Invalid signature: `401` and stop. See [Receive events](https://lunahia.com.br/en/docs/receive-events#assinatura). 2. **Answer `200` right away.** Luna waits 10 seconds, and a call to an AI model easily goes past that. 3. **Drop the repeat**: delivery is at least once, and the same `event_id` can arrive twice. 4. **Put the event on a queue** and handle it outside the request, one at a time, to keep the conversation’s order. 5. **Mark as read** (`POST /v1/messages/{id}/read`) and **show “typing”** (`POST /v1/messages/{id}/typing`). 6. **Think**: call your model with the received text. 7. **Reply** with `POST /v1/messages`, with an `Idempotency-Key` that comes from the received message: `resp-`. 8. **If the 24-hour window is closed** (`409 window_closed`), fall back to an approved template. ## Before you run it - A connected number and a registered webhook endpoint, as in [Quickstart](https://lunahia.com.br/en/docs/quickstart). The `secret` the registration returns is the `LUNA_WEBHOOK_SECRET`. - An API key with the `agent` profile (`profile: "agent"` in `POST /v1/api-keys`, or the “Agente de atendimento” (service agent) profile in the console). It grants `messages:write`, `messages:read`, `numbers:read` and `templates:read`: what the loop uses, and no configuration. - A public HTTPS address for the server. In development, an HTTPS tunnel to your machine works (see [Receive events](https://lunahia.com.br/en/docs/receive-events#gerir)). | Variable | What it is | | --- | --- | | `LUNA_API_KEY` | The API key (`hlsn_...`). | | `LUNA_WEBHOOK_SECRET` | The endpoint’s secret (`whsec_...`). | | `LUNA_NUMBER_ID` | The origin number: the `metaPhoneNumberId` or the `id` from `GET /v1/numbers`. | | `LUNA_TEMPLATE` | Optional. The name of an approved template, for step 8. | | `LUNA_API_URL` | Optional. Only to point at another base, such as a local stack. | | `PORT` | Optional. The server’s port (3000 by default). | ## The code Save as `agente.py` or `agente.mjs`. It is a single file, with no `pip install` or `npm install`. `answer` is the function you swap for your model; here it returns a fixed text. ```js import crypto from 'node:crypto'; import http from 'node:http'; const API = process.env.LUNA_API_URL ?? 'https://api.lunahia.com.br'; // LUNA_API_URL is optional: it exists to point at a local stack const KEY = process.env.LUNA_API_KEY; const SECRET = process.env.LUNA_WEBHOOK_SECRET; const NUMBER = process.env.LUNA_NUMBER_ID; const TEMPLATE = process.env.LUNA_TEMPLATE; // optional: the name of an approved template, for when the window is closed const TOLERANCE_SECONDS = 300; // rawBody: the exact bytes received (a Buffer), never re-serialized JSON. export function verifyLunaSignature(rawBody, header, secret, nowMs = Date.now()) { if (typeof header !== 'string' || !secret) return false; // 1. The header carries the instant t and the signature v1. const m = /^t=(\d{1,15}),/.exec(header); if (!m) return false; const t = Number(m[1]); // 2. Refuse what is too old (a recorded delivery replayed later). if (Math.abs(Math.floor(nowMs / 1000) - t) > TOLERANCE_SECONDS) return false; // 3. Redo the calculation with your secret and compare it with v1. const expected = crypto .createHmac('sha256', secret) .update(`${t}.`) .update(rawBody) .digest(); // During a secret rotation the header carries two v1 values: check them all. let ok = false; for (const [, hex] of header.matchAll(/v1=([0-9a-fA-F]{64})/g)) { if (crypto.timingSafeEqual(Buffer.from(hex, 'hex'), expected)) ok = true; } return ok; } const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // Calls the API. Returns the status and the JSON body. async function luna(method, path, body, idempotencyKey, tries = 3) { const headers = { Authorization: 'Bearer ' + KEY }; if (body !== undefined) headers['Content-Type'] = 'application/json'; if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey; for (let attempt = 1; ; attempt++) { const res = await fetch(API + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(15000), }); if ((res.status === 429 || res.status === 503) && attempt < tries) { // On 429/503 wait what the API says and try again, with the SAME Idempotency-Key await sleep(Number(res.headers.get('retry-after') ?? 2 ** attempt) * 1000); continue; } const text = await res.text(); return { status: res.status, body: text ? JSON.parse(text) : null }; } } // Replace this function with your agent (the LLM call goes here). function answer(text) { return text ? 'Recebi: ' + text + '. Já te ajudo.' : 'Recebi a sua mensagem.'; } async function handle(event) { if (event.event_type !== 'message.received') return; const msg = event.message; const destination = msg.wa_id ? { to: msg.wa_id } : { recipient: msg.user_id }; // wa_id is null when the contact wrote without a phone number: then answer to the user_id await luna('POST', '/v1/messages/' + msg.id + '/read'); // mark as read (the double blue check) await luna('POST', '/v1/messages/' + msg.id + '/typing'); // show "typing..." (it also marks the message as read, and goes away when you reply) const reply = answer(msg.text); // only text is handled here let sent = await luna( 'POST', '/v1/messages', { from: NUMBER, ...destination, text: { body: reply } }, 'resp-' + msg.id, // the key comes from the received message: the same event twice never produces two replies ); console.log('reply', sent.status, sent.body); if (sent.status === 409 && sent.body?.error === 'window_closed' && TEMPLATE) { // the 24-hour window is closed: only a template goes out sent = await luna( 'POST', '/v1/messages', { from: NUMBER, ...destination, type: 'template', template: { name: TEMPLATE, language: { code: 'pt_BR' } }, }, 'resp-' + msg.id + '-template', ); console.log('template', sent.status, sent.body); } } const seen = new Set(); // in production: a database or Redis, with an expiry let queue = Promise.resolve(); // ONE worker keeps the order of the events. For many conversations at once, one worker per wa_id. http .createServer((req, res) => { const chunks = []; req.on('data', (chunk) => chunks.push(chunk)); req.on('end', () => { const raw = Buffer.concat(chunks); if (!verifyLunaSignature(raw, req.headers['x-luna-signature'], SECRET)) { res.writeHead(401).end(); return; } res.writeHead(200).end(); // answer 200 first, work after const event = JSON.parse(raw.toString('utf8')); if (seen.has(event.event_id)) return; seen.add(event.event_id); // the work goes to a queue: the request only verifies and answers queue = queue.then(() => handle(event)).catch((err) => console.error('handler failed', err)); // a failure in one event must not stop the worker }); }) .listen(Number(process.env.PORT ?? 3000)); ``` ```python import hashlib import hmac import json import os import queue import re import threading import time import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer API = os.environ.get("LUNA_API_URL", "https://api.lunahia.com.br") # LUNA_API_URL is optional: it exists to point at a local stack KEY = os.environ["LUNA_API_KEY"] SECRET = os.environ["LUNA_WEBHOOK_SECRET"] NUMBER = os.environ["LUNA_NUMBER_ID"] TEMPLATE = os.environ.get("LUNA_TEMPLATE") # optional: the name of an approved template, for when the window is closed TOLERANCE_SECONDS = 300 def verify_luna_signature(raw_body, header, secret, now=None): # raw_body: the exact bytes received, never re-serialized JSON. if not header or not secret: return False # 1. The header carries the instant t and the signature v1. m = re.match(r"^t=(\d{1,15}),", header) if not m: return False t = int(m.group(1)) # 2. Refuse what is too old (a recorded delivery replayed later). now = time.time() if now is None else now if abs(int(now) - t) > TOLERANCE_SECONDS: return False # 3. Redo the calculation with your secret and compare it with v1. expected = hmac.new( secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256 ).hexdigest() # During a secret rotation the header carries two v1 values: check them all. ok = False for sig in re.findall(r"v1=([0-9a-fA-F]{64})", header): if hmac.compare_digest(sig.lower(), expected): ok = True return ok def luna(method, path, body=None, idempotency_key=None, tries=3): # Calls the API. Returns the status and the JSON body. headers = {"Authorization": f"Bearer {KEY}"} data = None if body is not None: data = json.dumps(body).encode() headers["Content-Type"] = "application/json" if idempotency_key: headers["Idempotency-Key"] = idempotency_key for attempt in range(1, tries + 1): req = urllib.request.Request(API + path, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=15) as res: raw = res.read() return res.status, (json.loads(raw) if raw else None) except urllib.error.HTTPError as err: raw = err.read() payload = json.loads(raw) if raw else None if err.code in (429, 503) and attempt < tries: # On 429/503 wait what the API says and try again, with the SAME Idempotency-Key time.sleep(float(err.headers.get("Retry-After") or 2**attempt)) continue return err.code, payload def answer(text): # Replace this function with your agent (the LLM call goes here). return f"Recebi: {text}. Já te ajudo." if text else "Recebi a sua mensagem." def handle(event): if event["event_type"] != "message.received": return msg = event["message"] destination = {"to": msg["wa_id"]} if msg["wa_id"] else {"recipient": msg["user_id"]} # wa_id is null when the contact wrote without a phone number: then answer to the user_id luna("POST", f"/v1/messages/{msg['id']}/read") # mark as read (the double blue check) luna("POST", f"/v1/messages/{msg['id']}/typing") # show "typing..." (it also marks the message as read, and goes away when you reply) reply = answer(msg.get("text")) # only text is handled here status, body = luna( "POST", "/v1/messages", {"from": NUMBER, **destination, "text": {"body": reply}}, idempotency_key=f"resp-{msg['id']}", # the key comes from the received message: the same event twice never produces two replies ) print("reply", status, body) if status == 409 and body and body.get("error") == "window_closed" and TEMPLATE: # the 24-hour window is closed: only a template goes out status, body = luna( "POST", "/v1/messages", { "from": NUMBER, **destination, "type": "template", "template": {"name": TEMPLATE, "language": {"code": "pt_BR"}}, }, idempotency_key=f"resp-{msg['id']}-template", ) print("template", status, body) events = queue.Queue() # the work goes to a queue: the request only verifies and answers seen = set() # in production: a database or Redis, with an expiry seen_lock = threading.Lock() def worker(): # ONE worker keeps the order of the events. For many conversations at once, one worker per wa_id. while True: event = events.get() try: handle(event) except Exception as err: # a failure in one event must not stop the worker print("handler failed", repr(err)) class Handler(BaseHTTPRequestHandler): def do_POST(self): raw = self.rfile.read(int(self.headers.get("Content-Length", 0))) if not verify_luna_signature(raw, self.headers.get("X-Luna-Signature"), SECRET): self.send_response(401) self.send_header("Content-Length", "0") self.end_headers() return self.send_response(200) # answer 200 first, work after self.send_header("Content-Length", "0") self.end_headers() event = json.loads(raw) with seen_lock: repeated = event["event_id"] in seen seen.add(event["event_id"]) if not repeated: events.put(event) def log_message(self, *args): pass threading.Thread(target=worker, daemon=True).start() ThreadingHTTPServer(("", int(os.environ.get("PORT", "3000"))), Handler).serve_forever() ``` ```bash export LUNA_API_KEY="hlsn_..." export LUNA_WEBHOOK_SECRET="whsec_..." export LUNA_NUMBER_ID="123456789012345" python3 agente.py # ou: node agente.mjs ``` Write from your phone to the connected number: the agent prints `reply 202` and the reply reaches your phone. If nothing arrives, follow “If nothing arrived” in [Quickstart](https://lunahia.com.br/en/docs/quickstart#receber). ## Why each step is the way it is ### Answer `200` first Luna counts as delivered only a `2xx` answer within 10 seconds. If the server called the model before answering, a slow reply would turn into a failure and Luna would resend the event, and the agent would reply twice. That is why the request only verifies, answers and puts the event on the queue; the worker does the thinking. The delivery guarantees are in [Receive events](https://lunahia.com.br/en/docs/receive-events#garantias). ### Drop the repeated `event_id` The `event_id` is stable: the same delivery, repeated, carries the same value. The example’s in-memory set disappears when the process restarts; in production keep the processed ones in a database or Redis, with an expiry. Note: the replay you ask for with `POST /v1/messages/{id}/replay` also carries the **same** `event_id` as the original, so it falls into this drop. To recover a message the agent lost, take its `event_id` out of the seen list before asking for the replay. ### One worker keeps the order Luna delivers a conversation’s events in order. If several workers took events of the same conversation, the reply to the second message could go out before the reply to the first. The example uses a single worker, which is enough for a few conversations at once; for many, keep one worker (or one queue) per `wa_id`, and several conversations move in parallel without getting mixed up. ### Read and “typing” Both routes take the **received** message’s id at Luna (the event’s `message.id`), not the `wamid`. Calling `/typing` also marks the message as read; the example calls both to make the step explicit. The indicator goes away on its own when you reply. There is a shortcut: `typingMs` in `POST /v1/messages` turns the indicator on and waits that long before sending, with no separate call. Both are in [Send messages](https://lunahia.com.br/en/docs/send-messages#lida-e-digitando). ## The agent’s idempotency key For an agent, the key is **not** a new UUID on each attempt: it is a **deterministic** key, which comes from the message it is answering, such as `resp-`. The reason: webhook delivery is at least once, and your handling can run twice for the same event (a restart in the middle, a replay, a retry after a `429`). With the same key, both attempts become **one** reply: the second returns the original message, with the same `id`, and nothing is sent again. A new UUID on each attempt protects from nothing. - One reply per received message: `resp-`. A second reply to the same message (the template fallback, for example) takes another suffix: `resp--template`. The same key with a **different body** answers `409 idempotency_key_reused`. - The key is 1 to 255 visible characters, no space. The full format is in [Send messages](https://lunahia.com.br/en/docs/send-messages#idempotencia). ## When the window has closed Right after the contact writes, the [24-hour window](https://lunahia.com.br/en/docs/glossary#janela) is open, and the reply goes out. `409 window_closed` shows up when the agent answers an old event (a delayed queue, a replay from yesterday) or when it is the one starting the conversation. It carries `fechadaEm` (when the window closed, or `null` if there never was one) and `acaoRecomendada`. Free-form messages are not accepted again with time: only when the contact writes again. What goes out is an approved [template](https://lunahia.com.br/en/docs/glossary#template), which the code above sends if `LUNA_TEMPLATE` is set. How to create one and wait for approval, and how to test before having one, is in [Templates](https://lunahia.com.br/en/docs/templates#testar). > No phone number? A contact who writes with only the [BSUID](https://lunahia.com.br/en/docs/glossary#bsuid) arrives with a null `wa_id`. The code replies with `recipient` equal to the event’s `user_id`, not with `to`. See [Users without a phone number](https://lunahia.com.br/en/docs/users-without-phone). ## Received media When the customer sends an image, audio, document or video, the event carries `message.media` (with the `mime_type` and the `url`) and `message.type`. The `url` is a Luna link that downloads the file **without an API key**: make a `GET` on it and follow the redirect. If Luna is still downloading the file from Meta, the answer is `409 media_not_ready` with `Retry-After`: wait and try again. Treat the link as sensitive data and do not log it. `GET /v1/messages/{id}/media` (`messages:read` scope), with a key, remains valid. Details in [Send messages](https://lunahia.com.br/en/docs/send-messages#midia). ```js import { writeFile } from 'node:fs/promises'; const EXTENSIONS = { 'image/jpeg': '.jpg', 'image/png': '.png', 'audio/ogg': '.ogg', 'application/pdf': '.pdf' }; // Downloads the file from the media.url of a message.received notice. async function downloadFromLink(link, name, attempts = 6) { for (let i = 0; i < attempts; i++) { const res = await fetch(link); // no Authorization header: the token inside the link is the credential. Never log the link. if (res.status === 409) { // 409 media_not_ready: Luna is still downloading from Meta, wait what Retry-After says and try again const seconds = Math.min(Number(res.headers.get('retry-after') ?? 5), 30); await new Promise((resolve) => setTimeout(resolve, seconds * 1000)); continue; } if (res.status === 404) return null; // 404: the link expired (30 days) or never existed. GET /v1/messages/{id}/media still works, with a key. if (!res.ok) throw new Error('media link answered ' + res.status); const type = (res.headers.get('content-type') ?? '').split(';')[0]; const file = name + (EXTENSIONS[type] ?? ''); await writeFile(file, Buffer.from(await res.arrayBuffer())); return file; } return null; } console.log(await downloadFromLink(process.env.LUNA_MEDIA_URL, 'arquivo')); ``` ```python import os import time import urllib.error import urllib.request EXTENSIONS = {"image/jpeg": ".jpg", "image/png": ".png", "audio/ogg": ".ogg", "application/pdf": ".pdf"} def download_from_link(link, name, attempts=6): # Downloads the file from the media.url of a message.received notice. for _ in range(attempts): try: # no Authorization header: the token inside the link is the credential. Never log the link. with urllib.request.urlopen(link, timeout=60) as file: data = file.read() extension = EXTENSIONS.get(file.headers.get_content_type(), "") except urllib.error.HTTPError as err: if err.code == 409: # 409 media_not_ready: Luna is still downloading from Meta, wait what Retry-After says and try again time.sleep(min(int(err.headers.get("Retry-After", "5")), 30)) continue if err.code == 404: return None # 404: the link expired (30 days) or never existed. GET /v1/messages/{id}/media still works, with a key. raise with open(name + extension, "wb") as out: out.write(data) return name + extension return None print(download_from_link(os.environ["LUNA_MEDIA_URL"], "arquivo")) ``` ## Before going to production - **After the `200`, a failure is yours.** If your handling fails, Luna does not retry: it already got the `200`. In production, write the event to a database before answering (a quick `INSERT`) and handle from there, so a restart does not lose the message. - **The pace.** Replies in bursts need no waiting on your side: Luna queues them. See [Limits and pacing](https://lunahia.com.br/en/docs/limits-and-pacing). - **Test without a real number.** The test key simulates sending and the states, without touching Meta: [Test mode](https://lunahia.com.br/en/docs/test-mode). - **The errors** the loop can see and what to do about each: [Errors](https://lunahia.com.br/en/docs/errors). - **n8n instead of code?** The path with the standard nodes is in [SDK and n8n](https://lunahia.com.br/en/docs/sdk-and-n8n). --- # Users without a phone number (BSUID) Fonte: https://lunahia.com.br/en/docs/users-without-phone Someone who adopted a WhatsApp username can write to your customer without their phone number showing. Meta identifies that user by a BSUID. Luna receives, keeps and delivers the BSUID, and your system needs to treat the phone number as optional. ## What the BSUID is The BSUID is the user identifier that does not depend on the phone number. It has the country code (two letters), a dot and up to 128 letters and digits: `US.13491208655302741918`. The parent BSUID, which Meta sends in some portfolios, has `ENT` after the country: `US.ENT.11815799212886844830`. **Keep the whole value, as it came**: Luna and Meta do not normalize it, and an altered value no longer finds the user. The phone number still exists. Meta sends it in the webhook when there was a message or a call in both directions in the last 30 days, or when the user is in the portfolio’s contact book. Outside that, only the BSUID arrives. **There is no API that converts a phone number into a BSUID**, or the other way round: Luna has no way to find one from the other. ## What changes in events `message.received`, `message.status` and `message.echo` gain three fields, always present and null when they do not apply: `user_id` (the BSUID), `parent_user_id` and `username`. And `wa_id` **can be null**: when the user writes without a phone number, the correspondent is `user_id`. The values arrive as Meta sent them. Message from someone who does not show a phone number ```json { "version": "2026-11-10", "event_id": "e2f81dd079e4419dac363779655be694a25cc502b7646be51cdac4b0cfc276fb", "event_type": "message.received", "occurred_at": "2026-11-03T14:02:11.482Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "c8a1e5d2-6f3b-4a7c-9e0d-1b2c3d4e5f60", "wamid": "wamid.EXAMPLE_NO_PHONE", "wa_id": null, "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": "mariasouza", "type": "text", "text": "Oi! Queria saber o status do meu pedido.", "profile_name": "Maria Souza", "media": null, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` > **This is a contract change**, which is why the event version went up to `2026-11-03` (and went up again to `2026-11-04` with the complete incoming content). `wa_id` is no longer always a text: whoever read it without checking for null needs to handle the case. Before it, Luna did not receive the message from someone writing without a phone number. A new event type (`contact.identity_changed`, below) does not raise the version. On the status of a message you sent by BSUID, `wa_id` can also be null and `user_id` identifies the recipient. The event stays in the same ordering group as the conversation: the order inside the conversation is still guaranteed. Status (with phone number and BSUID) ```json { "version": "2026-11-10", "event_id": "464e089a80690f1792db6249678ddeced5ad5be0d46d95e2daa263779f7d92e5", "event_type": "message.status", "occurred_at": "2026-10-06T14:02:14.090Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "status": "sent", "error_code": null, "error": null, "pricing": { "billable": false, "pricing_model": "PMP", "type": "free_customer_service", "category": "service" }, "callback_data": "atendimento-8841" } } ``` ## What the contact key is in your system Use the BSUID (`user_id`) as the contact key when it comes, and the phone number as an attribute. When a message carries both, Luna links phone number and BSUID in the **same conversation**: the conversation you already had by phone number keeps the same `id`, and gains the `userId`. No history is rewritten. The most recent phone number the user themselves used wins. If a conversation already has another phone number and a message arrives from the same BSUID with a new one, Luna uses the new one. Two conversations are never merged: if the new phone number already belongs to another conversation of the number, it is not moved, and both conversations stay, each one findable by one of the identities. A conversation without a phone number in GET /v1/conversations ```json { "id": "0f2c8e6a-1d3b-4a5c-9e7f-2b4d6a8c0e12", "waId": null, "userId": "BR.13491208655302741918", "parentUserId": null, "username": "mariasouza", "numberId": "7a1c9d3e-5f2b-4c8a-9d6e-1b3f5a7c9e11", "windowOpen": true } ``` `GET /v1/conversations` and `GET /v1/messages` return `userId`, `parentUserId` and `username`, and `waId` can now be `null`. Both gain the `userId` filter, which is an exact match and returns an empty list when nothing matches. `GET /v1/conversations?waId=` still finds the conversation by phone number. ## How to answer someone without a phone number `POST /v1/messages` accepts `recipient`, the recipient’s BSUID, in place of `to`. Send **one of the two**: both together, or neither, answer 400. To answer, use the `user_id` of the received event. Sending by BSUID ```json { "from": "123456789012345", "recipient": "BR.13491208655302741918", "text": { "body": "Oi, Maria! Seu pedido saiu para entrega." } } ``` - **The 24-hour window works the same way.** A BSUID-only conversation opens the window when the user writes, and free text outside it answers 409 `window_closed`. A template goes through outside the window, as for any recipient. - **An authentication template does not go to a BSUID.** One-tap, zero-tap and copy-code authentication templates need the phone number. Luna refuses with 400, before Meta, when it knows the template, it is an authentication one and the destination is `recipient`. If Luna does not know the template (created directly in Meta's panel), Meta refuses with error `131062`. Send that template to the phone number, in `to`. - **Error `131062`**: Meta refused the BSUID recipient for this send. Luna returns it as undeliverable, with the action: send to the phone number, in `to`. Repeating by BSUID does not help. - **Replying by quoting** requires the same conversation: quote a message from the conversation of the `recipient` you are using. > If your records have the phone number of a contact who wrote with a BSUID only, **do not** use it in `to` to answer: Luna does not know they are the same person, would open another conversation by phone number, with the window closed, and would refuse free text. Use `recipient` with the `user_id` you received. ## When the contact changes phone number or BSUID Meta announces the change with a system message (`user_changed_number` or `user_changed_user_id`). Luna links the new identity to the same conversation, does not open the service window (it is not the user writing) and delivers the `contact.identity_changed` event. It carries `previous_user_id` and `user_id`: use both to update the contact in your records. The fields Meta omits arrive null. BSUID change ```json { "version": "2026-11-10", "event_id": "f73a65b1f155f86f94e0886ad29bac662a822fabf796b626cdf865c7060f0db9", "event_type": "contact.identity_changed", "occurred_at": "2026-11-03T15:20:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "contact": { "wamid": "wamid.EXAMPLE_IDENTITY_CHANGE", "change_type": "user_changed_user_id", "wa_id": null, "user_id": "BR.98765432109876543210", "previous_user_id": "BR.13491208655302741918", "parent_user_id": null, "previous_parent_user_id": null } } ``` ## What Luna does not do - It does not convert a phone number into a BSUID or a BSUID into a phone number: Meta does not offer that lookup. - It does not merge two conversations that, in your records, are the same person. That is a decision for your system, which has both identifiers. - It does not guarantee strict event order at the moment a BSUID-only conversation gains a phone number: the ordering key changes once, at that moment, and in-flight events from before and after can arrive in any order among themselves. Order inside the conversation holds before and after that change. The events are in [Receive events](https://lunahia.com.br/en/docs/receive-events), sending is in [Send messages](https://lunahia.com.br/en/docs/send-messages) and the errors are in [Errors](https://lunahia.com.br/en/docs/errors). Every field of `GET /v1/conversations`, `GET /v1/messages` and `POST /v1/messages` is in the [API reference](https://lunahia.com.br/en/docs/reference). --- # What the number does at Meta Fonte: https://lunahia.com.br/en/docs/number-on-meta Each connected number has, at Meta, a profile the contact sees, a list of who was blocked and codes that open a conversation. Luna lets you handle the three through the API, with your customer’s own token, without them having to open Meta’s dashboard. The [API reference](https://lunahia.com.br/en/docs/reference) carries every route and field. This guide explains what the reference cannot fit in a few lines: what Meta refuses, what does not work in coexistence and what is still to be confirmed. ## What holds for every route - The `id` in the URL is the number’s: Luna’s UUID (the `id` from `GET /v1/numbers`) or Meta’s id (`metaPhoneNumberId`). Another customer’s number, or one that does not exist, answers the same `404`. - Each call spends **one** unit of Meta’s management limit for the number’s business account: 200 per hour, the same bucket as connecting and templates. When it runs out, the answer is `429` with `Retry-After`. It is a technical Meta limit, the same for everyone. - A number disconnected from Luna answers `409` (`number_disconnected`). A suspended account refuses what creates or changes; deleting, unblocking and reading stay open. - When Meta refuses the request (field too long, outside the 24-hour window, expired authorization), the answer is `422` with `error: "meta_rejected"`. The `meta` field carries what happened, what to do and its original error. A Meta failure (server or network error) does not become `422`. - None of these routes accepts an end customer’s key: use your account key. ## Business profile `GET /v1/numbers/{id}/profile` reads, and `PATCH` changes, what the contact sees on WhatsApp: `about` (the short text), `address`, `description`, `email`, `websites`, `vertical` (the line of business, in Meta’s vocabulary, with no closed list here) and the picture. The read also returns `profilePictureUrl`, which is Meta’s and can expire: download the file if you need to keep it. ```bash curl -X PATCH "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/profile" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "about": "Atendimento de segunda a sexta", "websites": [ "https://example.com" ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/profile', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "about": "Atendimento de segunda a sexta", "websites": [ "https://example.com" ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/profile", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "about": "Atendimento de segunda a sexta", "websites": [ "https://example.com", ], }, timeout=10, ) print(res.status_code, res.json()) ``` The `PATCH` changes only the fields you send. `websites` takes up to two and the whole list replaces the one that exists. To change the picture, send `profilePictureHandle`, the handle of a file uploaded through Meta’s resumable upload: the same handle `POST /v1/template-assets` returns works, **which is still to be confirmed in Meta’s documentation**. The field size limits (139 characters on the about text, 256 on the address, 512 on the description, 128 on the email) are also still to be confirmed: Luna only saves the call Meta would refuse, and Meta is the judge. ## Display name The display name is the name the contact sees at the top of the conversation, and Meta reviews it. It is not in `profile`: it is in `GET /v1/numbers/{id}` and in every item of `GET /v1/numbers`. `displayName` is the name in use. `displayNameStatus` is the state of the review, in lowercase: `approved`, `pending_review`, `declined`, `expired` or `none`; new values can appear, so do not treat the list as closed. `pendingDisplayName` is the requested name that is not yet the name in use (under review, declined, or approved and waiting for the new registration). All three are null until Luna reads the number for the first time, which happens within about an hour. **Meta does not report the reason for a refusal in that query**, and Luna does not return one: the business sees the reason in the WhatsApp Manager, in Meta’s manager. To request the change, send `displayName` in `PATCH /v1/numbers/{id}/profile`, alone or together with other profile fields. The answer is `202`: Meta accepted the request and it is under review, with `displayNameStatus: "pending_review"` and `pendingDisplayName` carrying the requested name. Meta accepts up to 10 name changes every 30 days and refuses a request outside its rules, which comes back as `422` with the original error. When the review ends, the `number.display_name_reviewed` event announces it. **An approved name only takes effect after the number is registered again** (`POST /{PHONE_NUMBER_ID}/register` at Meta), within 14 days of the approval; after that, you must ask again. Luna does not yet offer this new registration through a route: if the approved name does not show up in `displayName`, contact support. > **A number in coexistence has no profile through the API.** Meta lists the business profile among what stops working when the number stays in the phone app. Luna refuses first, with `409` and `error: "not_available_in_coexistence"`, without spending the management call. Whoever needs to change the profile does it in the business’s WhatsApp Business app on the phone. ## Block users `POST /v1/numbers/{id}/blocked-users` blocks, `GET` lists and `DELETE /v1/numbers/{id}/blocked-users/{user}` unblocks. Each user is a **phone number** (digits only, as in `to`) or a **BSUID** (as the `message.received` event carries it in `user_id`). Up to 50 per call. The **parent BSUID** (`XX.ENT.…`) does not block: Luna refuses with `400` and says the position, without repeating the value. That rule comes from the product plan and is still to be confirmed in Meta’s documentation. ```bash curl -X POST "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/blocked-users" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "users": [ "5511900000000" ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/blocked-users', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "users": [ "5511900000000" ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/blocked-users", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "users": [ "5511900000000", ], }, timeout=10, ) print(res.status_code, res.json()) ``` `200` response ```json { "done": [{ "input": "5511900000000", "waId": "5511900000000", "userId": null, "reasons": [] }], "failed": [] } ``` The response separates what Meta accepted (`done`) from what it refused (`failed`, with `reasons`, its text). **Meta only lets you block people who wrote to the number in the last 24 hours**, and Luna does not check that beforehand: Meta is the one that knows the window, and the reason comes back per user. The list (`GET`) uses `limit` and `cursor`, and `nextCursor` is Meta’s. ## QR code and short link `POST /v1/numbers/{id}/qr-codes` creates a code that opens a conversation with the number, with `prefilledMessage` (up to 140 characters, to be confirmed in Meta’s documentation) already written. It returns the `code`, the short `link` (wa.me) and, if you sent `imageFormat` (`PNG` or `SVG`), the `imageUrl`. `GET` lists the ones that exist and `DELETE /v1/numbers/{id}/qr-codes/{code}` deletes: whoever still has the QR printed stops opening the conversation. ```bash curl -X POST "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/qr-codes" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "prefilledMessage": "Oi, quero um orçamento", "imageFormat": "PNG" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/qr-codes', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "prefilledMessage": "Oi, quero um orçamento", "imageFormat": "PNG" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/numbers/YOUR_NUMBER_ID/qr-codes", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "prefilledMessage": "Oi, quero um orçamento", "imageFormat": "PNG", }, timeout=10, ) print(res.status_code, res.json()) ``` `201` response ```json { "code": "4O4YGZEG3RIVE1", "prefilledMessage": "Oi, quero um orçamento", "link": "https://wa.me/message/4O4YGZEG3RIVE1", "imageUrl": "https://example.com/qr.png" } ``` Luna keeps nothing: the code, the link and the image live at Meta. The `imageUrl` is Meta’s and can expire, so download the file right away if you are going to print it. No route returns how many times the code was read. ## When the contact asks to stop receiving marketing Meta tells you through the `user_preferences` field that the user changed a preference, today the one about marketing messages. Luna delivers the notice as the `contact.preferences_changed` event, with the contact (`wa_id`, `user_id`, `username`, `profile_name`) and `preference` (`category`, `value`, `detail`, as Meta sent them). **Luna does not block any send because of it**: your system keeps the request and stops sending marketing to whoever asked. See the event in [Receive events](https://lunahia.com.br/en/docs/receive-events). The event ```json { "version": "2026-11-10", "event_id": "4236ccfb21e7cec359d1e1b5b5f3f8e65cb3e8a8db0fc86e4d95da037796e97c", "event_type": "contact.preferences_changed", "occurred_at": "2026-11-04T16:45:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "contact": { "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "profile_name": "Maria Souza" }, "preference": { "category": "marketing_messages", "value": "stop", "detail": "User requested to stop marketing messages" } } ``` > **The notice only exists if the `user_preferences` field is subscribed on the Meta app.** That subscription is made in Meta’s dashboard, not through this API. The exact shape of the body Meta sends on the field is still to be confirmed in its documentation, and Luna reads it tolerantly. --- # Test mode Fonte: https://lunahia.com.br/en/docs/test-mode To build and test your integration without sending a real message, create a test key. With it, sending a message does not go to Meta, does not use a number of yours and does not count against the plan capacity: Luna returns the same `202` and delivers to your webhook the events Meta would send, simulated, signed and marked `test: true`. The [API reference](https://lunahia.com.br/en/docs/reference) carries every route and field. This guide explains what it cannot fit in a few lines: what the test key reaches, what comes out and when, and what test mode does not simulate. ## Create the test key `POST /v1/api-keys` with `mode: "test"`. The response carries the secret once, as with any key. The `mode` field also shows in the key list (`live` or `test`) and **does not change afterwards**: to leave test mode, use another key. ```bash curl -X POST "https://api.lunahia.com.br/v1/api-keys" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "label": "teste da integração", "profile": "agent", "mode": "test" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/api-keys', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "label": "teste da integração", "profile": "agent", "mode": "test" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/api-keys", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "label": "teste da integração", "profile": "agent", "mode": "test", }, timeout=10, ) print(res.status_code, res.json()) ``` - The test key belongs to the whole account: `externalId` together with `mode: "test"` answers `400`. - It **only uses two routes**: `POST /v1/messages` and `POST /v1/test-mode/inbound-messages`. On any other, the answer is `403` with `error: "test_key_not_allowed"`, before the body is validated. That is what guarantees it never reads or changes a number, account or template, and never reaches Meta. - Scopes work as on any key: sending asks for `messages:write`. The `agent` profile already has it. - The test key is not a number and **does not count against the plan capacity**. ## Send and receive the states Send as usual, with the test key. The body is validated by the same contract as a real send (an invalid body answers `400`), and `from` is free text: Luna does not look the number up, so use the `phone_number_id` your code will use in production. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "1000000000000001", "to": "5511900000000", "type": "text", "text": { "body": "Olá! Esta mensagem é de teste." } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "1000000000000001", "to": "5511900000000", "type": "text", "text": { "body": "Olá! Esta mensagem é de teste." } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "1000000000000001", "to": "5511900000000", "type": "text", "text": { "body": "Olá! Esta mensagem é de teste.", }, }, timeout=10, ) print(res.status_code, res.json()) ``` `202` response, the same as a real send ```json { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "status": "queued" } ``` After the `202`, Luna delivers three `message.status` events to your webhook endpoints, in order: `sent` (about 0.3 second later), `delivered` (about 1 second) and `read` (about 2 seconds). The times are approximate. The event `id` is the one the `202` returned. The `sent` event ```json { "version": "2026-11-10", "event_id": "bda40971d61ae76b36ab297565598f9427fd64ef16af8a62d201c8f596eb1006", "event_type": "message.status", "occurred_at": "2026-11-03T15:00:00.300Z", "phone_number_id": "1000000000000001", "test": true, "number": { "id": "03af3f4b-3a6f-4867-880f-eb5e847a6a8f", "phone_number_id": "1000000000000001", "external_id": null }, "message": { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "wamid": "wamid.TESTE_ae60f28875654315a4403663e9c231e1", "wa_id": "5511900000000", "user_id": null, "parent_user_id": null, "username": null, "status": "sent", "error_code": null, "error": null, "pricing": null } } ``` - **`test: true` on the envelope.** It is what separates the simulated event from a real one. If your code acts on the event, check that field. - It goes out **signed** with your endpoint’s secret, with the same headers and the same signature as a real delivery. Whoever verifies the signature for real verifies this event’s. See [Receive events](https://lunahia.com.br/en/docs/receive-events). - The `wamid` starts with `wamid.TESTE_`, so it is never mistaken for a Meta one. The `number.id` is a made-up identifier, stable for the same `phone_number_id`, and `number.external_id` is null. - `pricing` is null: the message did not go to Meta, so nobody classified it. **Who receives:** active endpoints, with no customer or number filter, that accept the event type. A paused endpoint, or one restricted to customers or numbers, does not receive the simulated event. Delivery is **one attempt only**: there is no resend, the event does not go to the rejected queue and a failure does not pause the endpoint. With no endpoint at all, the `202` goes out the same and nothing arrives. ## Simulate a send failure Three numbers in `to` make the test send end in `failed`, so you can see your code handle the refusal without spending a real number. For them **a single** `message.status` goes out, with `status: "failed"`, `error_code` and `error` (`code`, `title` and `message`) in the format of the error Meta reports. No `sent`, `delivered` or `read` goes out. - `5511900009901`: `failed` with error `131026` (message undeliverable: the number has no WhatsApp, or has not accepted the terms). - `5511900009902`: `failed` with error `131047` (the 24-hour window is closed: only a template works). - `5511900009903`: `failed` with error `131049` (Meta did not deliver it to keep the ecosystem healthy, the per-person marketing limit). Only the test key behaves this way. With the production key these numbers are nothing special: the send follows the usual path. ## Simulate a received message `POST /v1/test-mode/inbound-messages` delivers **one** example `message.received` to your endpoints, in about half a second, so you can exercise the support flow without waiting for a contact to write. The body is optional: `text` (the text), `waId` (the phone of whoever "wrote", digits only) and `phoneNumberId` (what shows in the event). When absent, an example text, `5511900000000` and `123456789012345` apply. ```bash curl -X POST "https://api.lunahia.com.br/v1/test-mode/inbound-messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "text": "Quero a segunda via do boleto" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/test-mode/inbound-messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "text": "Quero a segunda via do boleto" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/test-mode/inbound-messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "text": "Quero a segunda via do boleto", }, timeout=10, ) print(res.status_code, res.json()) ``` `202` response ```json { "id": "3f6a1c52-9d4e-4b87-a1f0-5e2c7b9d8a14", "wamid": "wamid.TESTE_3f6a1c529d4e4b87a1f05e2c7b9d8a14", "endpoints": 1 } ``` `endpoints` says how many of your endpoints will receive the event. Zero means nothing will arrive: register an endpoint. This route also accepts the regular key, and then does the same as `POST /v1/webhooks/endpoints/{id}/test` with `eventType: "message.received"`, only for all endpoints at once. To exercise the other event types, use that endpoint test route, which accepts any type. ## What test mode does not do - **It stores nothing.** The message does not show in `GET /v1/messages`, and the test key cannot even read that route. The `id` exists only in the events. - **It does not check the 24-hour window, the approved template, its variables, the recipient phone (+55) or the number.** That is why a send that production would refuse with `409`, `400` or `422` passes in test mode. Test those paths with a real number. - **It only simulates the three failures of the magic numbers.** Outside them the states are `sent`, `delivered` and `read`. For any other `failed`, use `POST /v1/webhooks/endpoints/{id}/test` with `eventType: "message.status"` or build the event from the examples in [Receive events](https://lunahia.com.br/en/docs/receive-events). - **It is not idempotent.** The `Idempotency-Key` header is ignored: each send produces a new `id` and three new events. - **The states come from a timer in Luna’s process.** If the process restarts between one state and the next, the missing ones do not go out. Repeat the send. - There is a technical ceiling on simulated deliveries scheduled at the same time, the same for everyone. Past it, the answer is `429` with `Retry-After`. Wait the indicated time. - A suspended account refuses the test send the way it refuses a real one (`403`, see [Plan and numbers](https://lunahia.com.br/en/docs/plan-and-numbers)). ## Go to production Swap the test key for a regular one. The rest of the code is the same, because sending and the events have the same shape. While both environments coexist, drop or separate what comes with `test: true`. To use test mode in n8n or with the SDK, see [SDK and n8n](https://lunahia.com.br/en/docs/sdk-and-n8n). --- # SDK and n8n Fonte: https://lunahia.com.br/en/docs/sdk-and-n8n The Luna API is plain HTTP with an OpenAPI specification, and you can call it from any language and any tool. In n8n, the path that works today uses only the standard nodes: a Webhook to receive, a Code to check the signature and an HTTP Request to send. The Node/TypeScript SDK and the dedicated n8n node are in preparation. The [API reference](https://lunahia.com.br/en/docs/reference) is the contract. The tools have no business rules: the [24-hour window](https://lunahia.com.br/en/docs/glossary#janela), the plan capacity and the approved template are checked by the API, which answers with the reason. ## n8n today: the standard nodes A workflow of four pieces, all built into n8n: the **Webhook** receives Luna’s event (with the raw body), the **Code** checks the signature, the **Respond to Webhook** returns `200` or `401`, and the **HTTP Request** sends the reply through the API. You need an API key with `messages:write` and the origin number (`metaPhoneNumberId`, from `GET /v1/numbers`). ### 1. The Webhook node - **HTTP Method**: `POST`. **Path**: `luna` (or whatever you prefer). - **Respond**: “Using ‘Respond to Webhook’ Node”. It is what lets you answer `401` to a signature that does not match. - In **Options**, turn on **Raw Body**. This is the step that usually gets missed: the signature is calculated over the **exact bytes** of the body, and without that option n8n hands over the JSON already parsed and the calculation does not match. With it, the body arrives as binary data in the `data` property. - Activate the workflow and copy the **Production URL**. Register it as a Luna endpoint (`POST /v1/webhooks/endpoints`, as in [Quickstart](https://lunahia.com.br/en/docs/quickstart#webhook)) and keep the response’s `secret`: it appears only once. n8n’s test URL does not work, because it only lives while you listen in the editor. ### 2. The Code node: check the signature Mode **Run Once for All Items**, JavaScript language. The code does the check that [Receive events](https://lunahia.com.br/en/docs/receive-events#assinatura) explains in words, and returns `valid` (true or false) and, if it holds, the `event` already parsed. Swap `SECRET` for the secret from the previous step. ```js const crypto = require('crypto'); const SECRET = 'whsec_PASTE_YOUR_SECRET_HERE'; // paste your endpoint secret here (whsec_...). In production, keep it in a credential or a variable. const TOLERANCE_SECONDS = 300; const header = $input.first().json.headers['x-luna-signature'] ?? ''; // the signature header (the Webhook node lowercases header names) const raw = await this.helpers.getBinaryDataBuffer(0, 'data'); // the exact bytes that arrived: the Webhook node needs the Raw Body option on const m = /^t=(\d{1,15}),/.exec(header); if (!m) return [{ json: { valid: false } }]; const t = Number(m[1]); // refuse what is too old (a captured delivery replayed later) if (Math.abs(Math.floor(Date.now() / 1000) - t) > TOLERANCE_SECONDS) { return [{ json: { valid: false } }]; } // redo the calculation with your secret and compare it with each v1 const expected = crypto.createHmac('sha256', SECRET).update(t + '.').update(raw).digest(); let valid = false; // during a secret rotation the header carries two v1 values: check them all for (const [, hex] of header.matchAll(/v1=([0-9a-fA-F]{64})/g)) { if (crypto.timingSafeEqual(Buffer.from(hex, 'hex'), expected)) valid = true; } // the next node reads valid and, if it is true, the event return [{ json: { valid, event: valid ? JSON.parse(raw.toString('utf8')) : null } }]; ``` > The Code node only uses the Node modules the n8n administrator has allowed. If `require('crypto')` is refused, set `NODE_FUNCTION_ALLOW_BUILTIN=crypto` in n8n’s environment (on an n8n you host yourself) and restart. ### 3. The HTTP Request node: send the reply After an “IF” node that lets through only what has `valid` true, and another that filters `event.event_type` equal to `message.received`, the HTTP Request calls the API: | Field | Value | | --- | --- | | Method | `POST` | | URL | `https://api.lunahia.com.br/v1/messages` | | `Authorization` header | `Bearer hlsn_...` (your key; in n8n, prefer a “Header Auth” credential) | | `Idempotency-Key` header | `resp-` followed by the received message’s `id`: with it, repeating the run does not send two replies | | Body (JSON) | `from` (your number), `to` (the event’s `wa_id`) and `text.body` | ### A ready-made workflow to import The JSON below is the whole workflow: Webhook, Code, IF, the two answers, the received-message filter and the HTTP Request. Copy it, and in n8n paste it on the canvas (Ctrl+V or Cmd+V) or use **Import from File**. Then swap the three `PASTE_...` values: the secret in the Code node, and the API key and the number in the HTTP Request. ```json { "name": "Luna: reply to a received message", "nodes": [ { "parameters": { "httpMethod": "POST", "path": "luna", "responseMode": "responseNode", "options": { "rawBody": true } }, "id": "5b0c1c1e-2f3a-4b5c-8d6e-7f8091a2b3c1", "name": "Luna webhook", "type": "n8n-nodes-base.webhook", "typeVersion": 2, "position": [ 0, 300 ], "webhookId": "9d8c7b6a-5e4f-4a3b-9c2d-1e0f9a8b7c6d" }, { "parameters": { "jsCode": "const crypto = require('crypto');\n\nconst SECRET = 'whsec_PASTE_YOUR_SECRET_HERE'; // paste your endpoint secret here (whsec_...). In production, keep it in a credential or a variable.\nconst TOLERANCE_SECONDS = 300;\n\nconst header = $input.first().json.headers['x-luna-signature'] ?? ''; // the signature header (the Webhook node lowercases header names)\nconst raw = await this.helpers.getBinaryDataBuffer(0, 'data'); // the exact bytes that arrived: the Webhook node needs the Raw Body option on\n\nconst m = /^t=(\\d{1,15}),/.exec(header);\nif (!m) return [{ json: { valid: false } }];\nconst t = Number(m[1]);\n\n// refuse what is too old (a captured delivery replayed later)\nif (Math.abs(Math.floor(Date.now() / 1000) - t) > TOLERANCE_SECONDS) {\n return [{ json: { valid: false } }];\n}\n\n// redo the calculation with your secret and compare it with each v1\nconst expected = crypto.createHmac('sha256', SECRET).update(t + '.').update(raw).digest();\nlet valid = false;\n// during a secret rotation the header carries two v1 values: check them all\nfor (const [, hex] of header.matchAll(/v1=([0-9a-fA-F]{64})/g)) {\n if (crypto.timingSafeEqual(Buffer.from(hex, 'hex'), expected)) valid = true;\n}\n\n// the next node reads valid and, if it is true, the event\nreturn [{ json: { valid, event: valid ? JSON.parse(raw.toString('utf8')) : null } }];" }, "id": "6c1d2d2f-3a4b-4c5d-9e7f-8a9102b3c4d2", "name": "Verify the signature", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 240, 300 ] }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 2 }, "conditions": [ { "id": "a1b2c3d4-0001-4000-8000-000000000001", "leftValue": "={{ $json.valid }}", "rightValue": "", "operator": { "type": "boolean", "operation": "true", "singleValue": true } } ], "combinator": "and" }, "options": {} }, "id": "7d2e3e30-4b5c-4d6e-8f80-9b0213c4d5e3", "name": "Valid signature?", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 480, 300 ] }, { "parameters": { "respondWith": "noData", "options": { "responseCode": 200 } }, "id": "8e3f4f41-5c6d-4e7f-9091-ac1324d5e6f4", "name": "Answer 200", "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1.1, "position": [ 720, 200 ] }, { "parameters": { "respondWith": "noData", "options": { "responseCode": 401 } }, "id": "9f405052-6d7e-4f80-a1a2-bd2435e6f705", "name": "Answer 401", "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1.1, "position": [ 720, 420 ] }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 2 }, "conditions": [ { "id": "a1b2c3d4-0002-4000-8000-000000000002", "leftValue": "={{ $('Verify the signature').item.json.event.event_type === 'message.received' }}", "rightValue": "", "operator": { "type": "boolean", "operation": "true", "singleValue": true } } ], "combinator": "and" }, "options": {} }, "id": "a0516163-7e8f-4091-b2b3-ce3546f70816", "name": "Is it a received message?", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 960, 200 ] }, { "parameters": { "method": "POST", "url": "https://api.lunahia.com.br/v1/messages", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Authorization", "value": "Bearer hlsn_PASTE_YOUR_KEY_HERE" }, { "name": "Idempotency-Key", "value": "=resp-{{ $('Verify the signature').item.json.event.message.id }}" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ JSON.stringify({ from: 'PASTE_YOUR_NUMBER_ID_HERE', to: $('Verify the signature').item.json.event.message.wa_id, text: { body: 'Got: ' + $('Verify the signature').item.json.event.message.text } }) }}", "options": {} }, "id": "b1627274-8f90-4102-83c4-df4657081927", "name": "Send the reply", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 1200, 100 ] } ], "connections": { "Luna webhook": { "main": [ [ { "node": "Verify the signature", "type": "main", "index": 0 } ] ] }, "Verify the signature": { "main": [ [ { "node": "Valid signature?", "type": "main", "index": 0 } ] ] }, "Valid signature?": { "main": [ [ { "node": "Answer 200", "type": "main", "index": 0 } ], [ { "node": "Answer 401", "type": "main", "index": 0 } ] ] }, "Answer 200": { "main": [ [ { "node": "Is it a received message?", "type": "main", "index": 0 } ] ] }, "Is it a received message?": { "main": [ [ { "node": "Send the reply", "type": "main", "index": 0 } ] ] } }, "pinData": {}, "settings": { "executionOrder": "v1" } } ``` > **What was checked, and what was not.** The Code node’s code is run in the documentation tests against Luna’s real signature. The JSON workflow was written from the documentation of n8n’s standard nodes, and Helsen has not yet imported it into a real n8n: if your version names an option differently, what changes is the screen, not the logic. To check end to end, send the test event (`POST /v1/webhooks/endpoints/{id}/test`, see [Receive events](https://lunahia.com.br/en/docs/receive-events#gerir)): if the Code node answers `valid` true, the calculation matches. To build and test the workflow without sending a real message, use a test key in the HTTP Request: the send does not go to Meta, and Luna delivers the `sent`, `delivered` and `read` states to your webhook with `test: true`. See [Test mode](https://lunahia.com.br/en/docs/test-mode). An AI agent that replies with a model in the middle of the workflow follows the loop in [AI agent](https://lunahia.com.br/en/docs/ai-agent). ## Coming: the SDK and the dedicated node > **Luna’s Node/TypeScript SDK and n8n node are not published yet** (neither on npm nor in the n8n node directory), and there is no date. They live in the Luna repository, in `packages/sdk` and `packages/n8n-nodes-luna`. Today’s n8n is the workflow above, and today’s Node is `fetch` (see [AI agent](https://lunahia.com.br/en/docs/ai-agent)). ## Node/TypeScript SDK The SDK is the typed client generated from the specification, with three additions: the production URL as default (`criarLuna`), error handling (`exigir` returns the body of a good response and throws `LunaErro` on a refusal, with `status`, `codigo` and `docsUrl`) and webhook signature verification. Every path and verb comes from the specification, so a route the API does not serve is a compile error. Create the client and send ```js import { criarLuna, exigir } from '@helsen/sdk'; const luna = criarLuna({ apiKey: process.env.LUNA_API_KEY }); const envio = exigir( await luna.POST('/v1/messages', { body: { from: '1000000000000001', to: '5511900000000', type: 'text', text: { body: 'Olá!' } }, }), ); console.log(envio.id, envio.status); ``` ### Check the webhook signature `lerEvento` checks the signature (`x-luna-signature`) over the **exact bytes** of the body and only then reads the JSON, returning the event typed by `event_type`. With a signature that does not match, it throws `AssinaturaInvalida`, and the body is not read. `verificarAssinatura` only returns `true` or `false`. During secret rotation, pass a list with the new and the old one. It is the same code Luna uses to sign, so the result agrees with the reference verifier in [Receive events](https://lunahia.com.br/en/docs/receive-events). A webhook server with the SDK ```js import express from 'express'; import { lerEvento, AssinaturaInvalida, CABECALHO_DA_ASSINATURA } from '@helsen/sdk'; const app = express(); // O corpo precisa chegar como bytes, sem passar por express.json() antes. app.post('/luna', express.raw({ type: 'application/json' }), (req, res) => { try { const evento = lerEvento(req.body, req.headers[CABECALHO_DA_ASSINATURA], process.env.LUNA_WEBHOOK_SECRET); if (evento.event_type === 'message.received') console.log(evento.message.text); res.sendStatus(200); } catch (erro) { if (erro instanceof AssinaturaInvalida) return res.sendStatus(401); throw erro; } }); ``` An event with `test: true` is a test event. See [Test mode](https://lunahia.com.br/en/docs/test-mode). ## n8n node The package brings one credential and two nodes. The **Luna API credential** holds the key (`hlsn_...`) and the API URL, and its test button reads `GET /v1/numbers`, so the key needs the `numbers:read` scope. The **Luna** node sends text, sends a template and lists the numbers. The **Luna Trigger** starts the workflow when Luna delivers an event. ### Send a message 1. Create the credential with your API key. 2. In the Luna node, choose Message and Send Text, or Send Template. Fill in the origin number (the `metaPhoneNumberId` that List Numbers returns), the recipient phone (digits only) and the content. 3. The output is the API’s `202`, with the message `id`. If the API refuses (for example `409`, text outside the 24-hour window), the node fails with its response; with "Continue on fail" on, the error becomes an item. ### Receive events in n8n 1. Activate the workflow and copy the production URL of the Luna Trigger webhook. 2. Register that URL as a Luna endpoint (`POST /v1/webhooks/endpoints`). The response carries the secret once. 3. Paste the secret in the node’s "Signing Secret" field. The node checks the signature over the exact bytes of the body and answers `401`, without running the workflow, when it does not match. It **does not register the endpoint by itself**. You can filter by event type (comma separated, empty means all) and drop events with `test: true`. > **The n8n node was never loaded in a real n8n.** It was written and tested with a stand-in for the n8n context. The behavior of the raw body and of the `401` response in the trigger is still to be confirmed in a real n8n, before any publishing. ## Build the workflow without sending a real message Use a test key in the n8n credential, or in the SDK. Sending does not go to Meta, and Luna delivers the `sent`, `delivered` and `read` states to your webhook, with `test: true`. The n8n credential test button reads `GET /v1/numbers` and a test key does not pass it, but the send operations work. The [Test mode](https://lunahia.com.br/en/docs/test-mode) guide explains it all. --- # Use the documentation in your editor (MCP) Fonte: https://lunahia.com.br/en/docs/mcp The Luna documentation has a public MCP server. Connected to your editor or assistant, the AI searches the guides and the reference on its own, and reads each route’s exact contract before writing the integration code. The address is `https://lunahia.com.br/mcp`. The server is read-only, asks for no key and stores nothing about you. It reads from the same content that generates this documentation, each page’s `.md` file and `llms-full.txt`: when a guide or the [API reference](https://lunahia.com.br/en/docs/reference) changes, the MCP changes with it, with nothing for you to update. It does not call the Luna API and does not send messages; for that use the [API key](https://lunahia.com.br/en/docs/account-and-keys) and the reference. ## The four tools | Tool | What it does | | --- | --- | | `list_pages` | Lists the pages (guides and reference) with the identifier (`slug`), the title and a one-line summary. | | `read_page` | Returns a page’s Markdown, identical to its `.md` file. Long pages come in pieces; the answer says which `offset` to ask for to continue. | | `search_docs` | Searches the guides, routes, webhook events and error codes, and returns the best sections with `slug`, anchor, link and an excerpt. | | `get_endpoint` | Returns a route’s OpenAPI operation (`method` and `path`), with the schemas already resolved: the exact contract to generate the client code. Big routes accept `part` (`request` or `responses`) to bring only half. | All of them accept `lang`: `pt` (default) or `en`. Each answer has at most 24,000 characters; beyond that the text is cut with a notice, and `read_page` and `get_endpoint` accept `offset` to ask for the rest. ## Connect your client In all of them, the name `luna-docs` is just a label; change it if you like. There is no authentication header to set up. ### Claude Code One line in the terminal: ```bash claude mcp add --transport http luna-docs https://lunahia.com.br/mcp ``` By default the setup applies only to you, in the current project. With `--scope user` it applies to all your projects, and with `--scope project` the command writes the `.mcp.json` below at the repository root, for the whole team to use. Check it with `claude mcp list` or, inside Claude Code, with `/mcp`. .mcp.json ```json { "mcpServers": { "luna-docs": { "type": "http", "url": "https://lunahia.com.br/mcp" } } } ``` ### Cursor Create `.cursor/mcp.json` in the project, or `~/.cursor/mcp.json` to apply to all of them: .cursor/mcp.json ```json { "mcpServers": { "luna-docs": { "url": "https://lunahia.com.br/mcp" } } } ``` ### VS Code Create `.vscode/mcp.json`. Note that VS Code uses the `servers` key, not `mcpServers`. You can also use the **MCP: Add Server** command from the command palette, choose **HTTP** and paste the address. .vscode/mcp.json ```json { "servers": { "luna-docs": { "type": "http", "url": "https://lunahia.com.br/mcp" } } } ``` ### Claude (remote connector) On claude.ai, go to **Customize > Connectors**, click **Add** and **Add custom connector**, give it a name (for example `Luna docs`) and paste `https://lunahia.com.br/mcp` as the address. Under authentication, choose **No sign in**. Team and Enterprise plans: the organization administrator adds it, in **Organization settings > Connectors**. Then, in each chat, turn the connector on with the **+** button. ### ChatGPT ChatGPT accepts a remote MCP server through **developer mode**, in the apps and connectors settings: create an MCP app, paste `https://lunahia.com.br/mcp` as the address and choose **no authentication**. Then turn it on in the chat. These menus change place and name between versions and plans, and Helsen could not check the steps against OpenAI’s documentation, so follow what your ChatGPT shows. > Other clients that speak MCP over HTTP work the same way: the address is all they need. Claude and ChatGPT connect from their cloud, so they only see the published server, never a `localhost`. ## What to ask the AI - “Using the Luna documentation, write the Node code that sends an approved template.” - “What is the exact contract of `POST /v1/messages`? Generate the TypeScript types.” - “How do I check a Luna webhook signature? Show an example in Python.” - “What does the `window_closed` error mean and what do I do?” ## Technical details - **Streamable HTTP** transport, with no session: each call is a `POST` with one JSON-RPC message, and the answer is a JSON. `GET` and `DELETE` answer `405`. - Protocol versions: 2025-03-26, 2025-06-18, 2025-11-25 (with `initialize`) and 2026-07-28 (no handshake, with `server/discover`). - Open CORS, for browser clients, and no credentials: there is no cookie or key to protect. To test with no client at all, call a tool directly: ```bash curl -X POST https://lunahia.com.br/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_docs","arguments":{"query":"enviar template"}}}' ``` --- # Templates Fonte: https://lunahia.com.br/en/docs/templates A template is a message pre-approved by Meta. It is what lets you start a conversation outside the 24-hour window. Inside the window, free-form text is enough. ## When you need a template - The contact never wrote to your number, or their last message is more than 24 hours old (the [24-hour window](https://lunahia.com.br/en/docs/glossary#janela) closed): only a template goes out. Free-form text is refused with `409`. - Sending a template **does not reopen the window**. It is the way to start the conversation, and free-form messages are only accepted again once the contact replies. - To know whether the window is open before trying, read `GET /v1/conversations`. See [Send messages](https://lunahia.com.br/en/docs/send-messages#janela). ## Testing without an approved template A new template is born `PENDING` and only sends once `APPROVED`: Meta decides, and the `template.status` event announces when the state changes. Meanwhile, you can build and test your code in two ways: - **With a test key** ([Test mode](https://lunahia.com.br/en/docs/test-mode)). `POST /v1/messages` with `type: "template"` and the test key returns the `202` and delivers simulated states to your webhook, **without checking** whether the template exists, whether it is approved or its variables. It serves to test your code (the body, the webhook, the handling of the states), not the template itself. - **With the real key**, a template that Luna knows and that is not approved yet answers `409` with `error: "template_not_approved"` and the `templateStatus` (`PENDING`, `REJECTED`, `PAUSED`...), sending nothing. That also shows, without spending a send, the exact point where your code needs to wait. A template created directly in Meta’s dashboard, which Luna does not know, goes through, and Meta decides. Creating and editing templates uses a budget of account management operations, and going past it answers `429` with `error: "management_busy"`. The numbers are in [Limits and pacing](https://lunahia.com.br/en/docs/limits-and-pacing). ## Create a template `POST /v1/templates` creates the template in the customer’s WhatsApp Business account and submits it to Meta for approval. `templates:write` scope. The `wabaId` is the account’s identifier at Meta, and comes from `GET /v1/business-accounts` (`numbers:read` scope): **How long approval takes.** Meta says reviewing a template can take up to 24 hours ([Meta documentation](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/overview)). The status starts at `PENDING` and changes by itself: do not poll, wait for the `template.status` event (`APPROVED`, `REJECTED`, `PAUSED`, `DISABLED`). Plan creating a new customer’s templates before the first send outside the service window. ```bash curl -X GET "https://api.lunahia.com.br/v1/business-accounts" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/business-accounts', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/business-accounts", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ```bash curl -X POST "https://api.lunahia.com.br/v1/templates" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "wabaId": "YOUR_WABA_ID", "name": "confirmacao_de_pedido", "language": "pt_BR", "category": "UTILITY", "bodyText": "Olá {{nome}}, recebemos o seu pedido e já estamos preparando.", "examples": { "nome": "Ana" }, "footer": "Obrigado por comprar com a gente.", "buttons": [ { "type": "QUICK_REPLY", "text": "Falar com atendente" } ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/templates', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "wabaId": "YOUR_WABA_ID", "name": "confirmacao_de_pedido", "language": "pt_BR", "category": "UTILITY", "bodyText": "Olá {{nome}}, recebemos o seu pedido e já estamos preparando.", "examples": { "nome": "Ana" }, "footer": "Obrigado por comprar com a gente.", "buttons": [ { "type": "QUICK_REPLY", "text": "Falar com atendente" } ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/templates", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "wabaId": "YOUR_WABA_ID", "name": "confirmacao_de_pedido", "language": "pt_BR", "category": "UTILITY", "bodyText": "Olá {{nome}}, recebemos o seu pedido e já estamos preparando.", "examples": { "nome": "Ana", }, "footer": "Obrigado por comprar com a gente.", "buttons": [ { "type": "QUICK_REPLY", "text": "Falar com atendente", }, ], }, timeout=10, ) print(res.status_code, res.json()) ``` `201` response ```json { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "metaTemplateId": "1259544702043801", "name": "confirmacao_de_pedido", "language": "pt_BR", "category": "UTILITY", "status": "PENDING", "createdAt": "2026-10-06T14:00:00.000Z", "updatedAt": "2026-10-06T14:00:00.000Z" } ``` | Field | Rule | | --- | --- | | `name` | Lowercase letters, digits and underscore: `^[a-z0-9_]{1,512}$`. It does not change afterwards. | | `language` | In Meta’s spelling, with an underscore and not a hyphen: `pt_BR`, `pt_PT`, `en_US`, `es_MX`, `fr`. It does not change afterwards. | | `category` | `MARKETING` or `UTILITY`. Absent means `UTILITY`. For verification codes there is a separate route (see below). | | `bodyText` | Up to 1024 characters. Accepts variables in the form `{{variable_name}}`, in lowercase and underscore. The body cannot start or end with a variable, and punctuation at the edge does not count: a body ending in `{{nome}}.` is refused. Write text before the first variable and after the last. | | `examples` | An object `{ "primeiro_nome": "Maria" }`, never a list: one sample value per body variable, required when there is a variable. Meta refuses a parameter with no example, and the refusal costs one unit of the account’s management budget. | | `header`, `footer` | Text of up to 60 characters. The footer does not accept a variable. For an image, video or document header, use `headerMedia`. | | `buttons` | Up to 10 in total, adding up the `QUICK_REPLY`, `URL`, `PHONE_NUMBER` and `COPY_CODE` types. If quick replies sit next to other buttons, the two sets must be grouped. | - The category returned in the response is the one **Meta assigned**, and may not be the one you asked for, because it reclassifies at creation. Luna stores what Meta answered and updates it when Meta announces a category change (the `template.category` event, see Category and quality change after approval): `GET /v1/templates` shows the current one. A change Meta did not announce does not reach Luna; when in doubt, check Meta’s panel. - Each language is a **separate** template for Meta. Ten templates in nine languages are ninety templates, and the ceiling is 250 per WhatsApp Business account. The ceiling is Meta’s and is the same for every customer. - Above three buttons, only two appear in the delivered message. Meta accepts the template with more and delivers two, so decide the arrangement before designing the flow. ## Follow the status `GET /v1/templates/{id}` returns the template’s current status at Meta. `templates:read` scope: ```bash curl -X GET "https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` - The `status` is free text, not a closed set, on purpose: Meta adds new values without notice. The common ones are `APPROVED`, `PENDING`, `REJECTED`, `PAUSED` and `DISABLED`. - **Luna sends the `template.status` event to your endpoint when a template’s status changes**: approved, rejected, paused or disabled. The event carries the template’s Luna `id`, the `name`, the `language`, the `waba_id` (the business account, the `wabaId` of the template reads), the `category`, the new `status` and, on a rejection or a pause, the `reason` Meta gave. Wait for the event instead of polling. See [Receive events](https://lunahia.com.br/en/docs/receive-events#eventos). - Polling remains the fallback. If your endpoint was down, or you missed an event, `GET /v1/templates/{id}` returns the current status, and `GET /v1/templates` the last one Luna observed for each template. `GET /v1/templates` lists the customer’s templates, newest first. The `status` in the list is the **last one Luna observed**, not a live read at Meta. Use `?status=` to filter. The comparison is literal and case-sensitive. ```bash curl -X GET "https://api.lunahia.com.br/v1/templates?status=APPROVED" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/templates?status=APPROVED', { method: 'GET', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.get( "https://api.lunahia.com.br/v1/templates?status=APPROVED", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code, res.json()) ``` ## Category and quality change after approval The template category (`UTILITY`, `MARKETING`, `AUTHENTICATION`) sets the price Meta charges the business for sending. Meta can change the category **after approval**, when the content points to another one: a `UTILITY` template that becomes `MARKETING` stays `APPROVED`, and its price goes up. The account owner pays, directly to Meta; Luna neither charges nor intermediates that amount. Businesses usually find out from Meta’s invoice. With Luna you find out earlier, by event. - **`template.category`** arrives in two forms: the advance notice, with `correct_category` (the category Meta will change to) and `scheduled_for` (when), and the change made, with `previous_category` and `new_category`. When the change is made, the template’s `category` field, in `GET /v1/templates`, shows the new category. - **`template.quality`** announces that the template’s quality score changed (`previous_quality_score` and `new_quality_score`: `GREEN`, `YELLOW`, `RED`). A low score comes before Meta pauses the template, which arrives as `template.status` with `PAUSED`. - **What to do.** On the advance notice, review the content if the intent was utility and tell the account owner the price is about to change. Meta allows asking for a category review in WhatsApp Manager, within a period it defines. On low quality, review the content or the audience before the pause. > The full format of both events, with examples, is in [Receive events](https://lunahia.com.br/en/docs/receive-events). ## Approved is not cleared An `APPROVED` template is not necessarily cleared to go out. Meta applies a pace of its own to the first sends of a newly approved template. It calls this template pacing, and defines it as a process that gives WhatsApp users time to react to the message: if the first deliveries are poorly received, the template is paused before reaching many people. > **Meta publishes no deadline and no mechanics, and Luna does not make any up.** No field in this API says when the pace ends, and no state says it is under way, because that information is not issued by whoever controls it. Looking for one here is looking for something that cannot exist. - **Ramp up the first send** instead of scheduling it for a date. - Start with a small volume and grow as deliveries confirm. - Watch the template’s status: it goes to `PAUSED` if the reaction is negative. You can filter the list with `?status=PAUSED`. ## Media header For an image, video or document header, there are two steps. First upload the example file at `POST /v1/template-assets`, as `multipart/form-data`, in the `file` field (`templates:write` scope): ```bash curl -X POST "https://api.lunahia.com.br/v1/template-assets" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -F "file=@./exemplo.png;type=image/png" ``` ```js import { readFile } from 'node:fs/promises'; const form = new FormData(); form.append( 'file', new Blob([await readFile('./exemplo.png')], { type: 'image/png' }), 'exemplo.png', ); const res = await fetch('https://api.lunahia.com.br/v1/template-assets', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, body: form, }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/template-assets", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, files={"file": ("exemplo.png", open("exemplo.png", "rb"), "image/png")}, timeout=10, ) print(res.status_code, res.json()) ``` `200` response ```json { "handle": "4:EXAMPLE_HANDLE_NOT_REAL:ARb0Xk:e:1790451084:0" } ``` Then use the `handle` in `headerMedia`, with the `format` `IMAGE`, `VIDEO` or `DOCUMENT`: ```bash curl -X POST "https://api.lunahia.com.br/v1/templates" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "wabaId": "YOUR_WABA_ID", "name": "pedido_a_caminho", "language": "pt_BR", "category": "UTILITY", "bodyText": "Olá {{nome}}, o seu pedido saiu para entrega.", "examples": { "nome": "Ana" }, "headerMedia": { "format": "IMAGE", "handle": "YOUR_HANDLE_FROM_TEMPLATE_ASSETS" } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/templates', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "wabaId": "YOUR_WABA_ID", "name": "pedido_a_caminho", "language": "pt_BR", "category": "UTILITY", "bodyText": "Olá {{nome}}, o seu pedido saiu para entrega.", "examples": { "nome": "Ana" }, "headerMedia": { "format": "IMAGE", "handle": "YOUR_HANDLE_FROM_TEMPLATE_ASSETS" } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/templates", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "wabaId": "YOUR_WABA_ID", "name": "pedido_a_caminho", "language": "pt_BR", "category": "UTILITY", "bodyText": "Olá {{nome}}, o seu pedido saiu para entrega.", "examples": { "nome": "Ana", }, "headerMedia": { "format": "IMAGE", "handle": "YOUR_HANDLE_FROM_TEMPLATE_ASSETS", }, }, timeout=10, ) print(res.status_code, res.json()) ``` - **The `handle` is not the media identifier** that `POST /v1/numbers/{id}/media` returns. They are two Meta endpoints with different purposes, and a media identifier in place of the `handle` makes the creation get refused. The media identifier is a long decimal number, and the `handle` is not numeric. - The types accepted in the upload are `application/pdf`, `image/jpeg`, `image/jpg`, `image/png` and `video/mp4`. For a document Meta accepts only PDF. Neither GIF nor location is accepted. - The file’s content is checked against the declared type before any call to Meta. A file declared as `image/png` whose bytes are something else is refused with `400`. Above the ceiling, `413`. - Meta does not publish how long the `handle` stays valid, and Luna does not store the value. Use it in the template creation right after, and upload again if it stops working. - `header` (text) and `headerMedia` are mutually exclusive: Meta accepts only one header per template. > **The `headerMedia` file is the example Meta reviews, not the delivered content.** Each message you send with the template supplies its own media, in the send’s header component. Whoever creates the template thinking the example image is the one sent ends up sending a message with no header. ## Send the template With the template `APPROVED`, send it through `POST /v1/messages` with `type: "template"`. The `language.code` must match the approved language, and the `components` fill in the variables. For a named variable, use `parameter_name`: ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "confirmacao_de_pedido", "language": { "code": "pt_BR" }, "components": [ { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana" } ] } ] } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID(), }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "confirmacao_de_pedido", "language": { "code": "pt_BR" }, "components": [ { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana" } ] } ] } }), }); console.log(res.status, await res.json()); ``` ```python import os import uuid import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", "Idempotency-Key": str(uuid.uuid4()), }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "confirmacao_de_pedido", "language": { "code": "pt_BR", }, "components": [ { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana", }, ], }, ], }, }, timeout=10, ) print(res.status_code, res.json()) ``` With a media header, the media goes in the `header` component **of each send**. `parameters` accepts the values in the form the Cloud API defines, and here the image goes by `link`: ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "pedido_a_caminho", "language": { "code": "pt_BR" }, "components": [ { "type": "header", "parameters": [ { "type": "image", "image": { "link": "https://example.com/pedido.jpg" } } ] }, { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana" } ] } ] } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "pedido_a_caminho", "language": { "code": "pt_BR" }, "components": [ { "type": "header", "parameters": [ { "type": "image", "image": { "link": "https://example.com/pedido.jpg" } } ] }, { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana" } ] } ] } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "pedido_a_caminho", "language": { "code": "pt_BR", }, "components": [ { "type": "header", "parameters": [ { "type": "image", "image": { "link": "https://example.com/pedido.jpg", }, }, ], }, { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana", }, ], }, ], }, }, timeout=10, ) print(res.status_code, res.json()) ``` For a template Luna knows (created by it, or seen through the `template.status` event), the refusal comes in the send response, not later by webhook: `409 template_not_approved` when the state is not `APPROVED` (the body carries `templateStatus`), and `400` with `campos` when a body or header variable is missing, when one the template does not have comes in, or when the code of an authentication template goes over 15 characters. The variable check applies to a template whose content Luna has (`bodyText` other than `null`). A template created directly in Meta’s panel is not in that catalog and goes through: Meta decides, and its refusal arrives through the `message.status` event. The `handle` used at creation does not become the delivered content, and there is nothing to reuse from it in the send. To choose between `link` and a media identifier, the recommendation in [Send messages](https://lunahia.com.br/en/docs/send-messages#midia) applies. ## Edit and remove `PATCH /v1/templates/{id}` changes the components of an existing template. The update is **partial**: whatever you do not send stays as it is. That is why the verb is `PATCH`, not `PUT`. ```bash curl -X PATCH "https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "bodyText": "Olá {{nome}}, recebemos o seu pedido e já estamos separando os itens.", "examples": { "nome": "Ana" } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "bodyText": "Olá {{nome}}, recebemos o seu pedido e já estamos separando os itens.", "examples": { "nome": "Ana" } }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "bodyText": "Olá {{nome}}, recebemos o seu pedido e já estamos separando os itens.", "examples": { "nome": "Ana", }, }, timeout=10, ) print(res.status_code, res.json()) ``` To build the creation form without copying any limit, read `GET /v1/templates/rules` (scope `templates:read`): the `categories` (each with `value`, `label` and `summary`), the suggested `languages`, the `namePattern` and a `nameExample`, the lengths `bodyMaxLength`, `headerMaxLength` and `footerMaxLength`, and the `buttonLimits` (`total` and `byType`). The languages are suggestions: any code Meta publishes is valid. It is the same number `POST /v1/templates` enforces. To fill in an edit form, read the current content at `GET /v1/templates/{id}` or `GET /v1/templates`: `bodyText`, `header`, `headerMedia` (the format only), `footer`, `buttons` (in the same shape you sent them) and `variables`, the list of the body’s variables in the order they appear, each with its `example`. The read also returns `rejectedReason`, the reason Meta gave while the template is `REJECTED`, `qualityScore`, the last quality rating it announced, `previousCategory`, the category the template had before Meta changed it, and `allowedActions`, what the account can do now (`edit` and `delete`, and nothing while the account is suspended). The content is null (`bodyText: null`) on a template created before Luna stored it or directly in Meta’s panel. - Name, language and business account **cannot** be changed. For a different name, create another template. - If you send any component, send `bodyText` as well: Meta refuses a template with no body. - The edit submits the template for approval again, and the status changes. Check the status afterwards. `DELETE /v1/templates/{id}` answers `204`. ```bash curl -X DELETE "https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID', { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, }, }); console.log(res.status); ``` ```python import os import requests res = requests.delete( "https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, timeout=10, ) print(res.status_code) ``` > **Meta removes a template by NAME, and that deletes every language version of that name.** If you keep the same template in three languages, this call deletes all three at once on Meta’s side. Luna removes from your listing only what you asked for, and the other language versions keep showing up here and no longer exist there. Removal is final, and creating another with the same name restarts approval from zero. Removing twice is safe: the second call returns `404`. ## Copy to other customers Meta creates templates per business account, so whoever operates many customers used to repeat the creation account by account. `POST /v1/templates/{id}/copy` (scope `templates:write`) runs the loop: it takes `targets`, 1 to 50 destinations, each `{ "wabaId": "..." }` (the account, by its Meta id) or `{ "externalId": "..." }` (a customer of yours, and the copy goes to each WhatsApp Business account of their numbers). Luna builds the body from the content it stored of the source template and creates the copy through the same path as `POST /v1/templates`, with the same rules; the copy starts under review at Meta, like any new template, with the same name and language. ```bash curl -X POST "https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID/copy" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "targets": [ { "wabaId": "102290129340398" }, { "externalId": "cliente-43" } ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID/copy', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "targets": [ { "wabaId": "102290129340398" }, { "externalId": "cliente-43" } ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/templates/YOUR_TEMPLATE_ID/copy", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "targets": [ { "wabaId": "102290129340398", }, { "externalId": "cliente-43", }, ], }, timeout=10, ) print(res.status_code, res.json()) ``` The response is always `200` with `results`, **one result per destination** (per account, when an `externalId` has more than one). Each result carries `target` (the requested destination), `wabaId`, `status` and, depending on the case, `template` (the created template, in the same shape as `POST /v1/templates`) or `error` (the same error body the route would give alone). `status` is `201` when the copy was created, or the status of that destination’s error: `404` for an account that is not yours or a customer that does not exist, `422` when Meta refused (a template with that name already exists, for example). **A destination that fails does not bring the others down**, which is why the response status does not count what happened to each: read `results[].status`. Each destination spends one unit of that account’s management limit. - A template created directly in Meta’s panel, or before Luna stored the content, answers `409` with `template_content_unknown`: without the content there is nothing to copy. Create it again with `POST /v1/templates` and copy the new one. - With a media header, send `headerMediaHandle`: Luna stores only the header’s format, not the sample file. Without it, `400` with `campos`. - An authentication template uses the authentication path and asks for `authentication` (`codeExpirationMinutes`, and if you want `addSecurityRecommendation`, `buttonText` and `messageSendTtlSeconds`): Luna does not store these parameters. ## Authentication template A verification code has a creation route of its own, `POST /v1/templates/authentication` (`templates:write` scope), and is not one more category in `POST /v1/templates`. The content is not yours: the body is fixed by Meta, with the text "{{1}} is your verification code." translated into the template’s language. That is why the route takes no body, examples, header, footer or buttons. ```bash curl -X POST "https://api.lunahia.com.br/v1/templates/authentication" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "wabaId": "YOUR_WABA_ID", "name": "codigo_de_verificacao", "language": "pt_BR", "addSecurityRecommendation": true, "codeExpirationMinutes": 10 }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/templates/authentication', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "wabaId": "YOUR_WABA_ID", "name": "codigo_de_verificacao", "language": "pt_BR", "addSecurityRecommendation": true, "codeExpirationMinutes": 10 }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/templates/authentication", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "wabaId": "YOUR_WABA_ID", "name": "codigo_de_verificacao", "language": "pt_BR", "addSecurityRecommendation": True, "codeExpirationMinutes": 10, }, timeout=10, ) print(res.status_code, res.json()) ``` - You choose the `name`, the `language`, whether the security notice shows (`addSecurityRecommendation`), in how many minutes the code expires (`codeExpirationMinutes`, required) and, if you like, the `buttonText` and the `messageSendTtlSeconds`. - Omitting `buttonText` is recommended: without it Meta uses the language’s default label, already translated. - On sending, the one-time code goes **twice** in the message body: once in the body component and once in the button component. That is the format, not redundancy to optimize. The password accepts at most 15 characters. Sending the code is an ordinary template send, with two components: the code in the body and the same code in the button. The body below follows the example on Meta’s copy-code page, and Luna passes it on untouched. The `index` goes as text (`"0"`), which is how Luna reads it, and the `sub_type` is `url`, the value Meta shows in that example even for the copy-code button. ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "codigo_de_verificacao", "language": { "code": "pt_BR" }, "components": [ { "type": "body", "parameters": [ { "type": "text", "text": "482913" } ] }, { "type": "button", "sub_type": "url", "index": "0", "parameters": [ { "type": "text", "text": "482913" } ] } ] } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID(), }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "codigo_de_verificacao", "language": { "code": "pt_BR" }, "components": [ { "type": "body", "parameters": [ { "type": "text", "text": "482913" } ] }, { "type": "button", "sub_type": "url", "index": "0", "parameters": [ { "type": "text", "text": "482913" } ] } ] } }), }); console.log(res.status, await res.json()); ``` ```python import os import uuid import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", "Idempotency-Key": str(uuid.uuid4()), }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "type": "template", "template": { "name": "codigo_de_verificacao", "language": { "code": "pt_BR", }, "components": [ { "type": "body", "parameters": [ { "type": "text", "text": "482913", }, ], }, { "type": "button", "sub_type": "url", "index": "0", "parameters": [ { "type": "text", "text": "482913", }, ], }, ], }, }, timeout=10, ) print(res.status_code, res.json()) ``` - The code has at most 15 characters. Above that Luna answers `400` with `campos` before queueing, and the value does not come back in the error. - Send it to the phone (`to`). An authentication template does not go to someone who wrote without a visible phone (`recipient`): Meta requires the phone for it. - Luna only creates the copy-code template. The one-tap and zero-tap ones depend on an Android app of yours and are left out for now. > **What is still unchecked:** Helsen has not yet run this send against Meta with an approved template. If Meta refuses the button’s shape, the refusal arrives as `message.status` with `failed` and the error code, and Meta’s copy-code page is what holds. Generating, storing, expiring and checking the code is up to your system: Luna delivers the message. > Each route’s full contract is in the [API reference](https://lunahia.com.br/en/docs/reference), in the Templates section. ## Route details for this guide The [API reference](https://lunahia.com.br/en/docs/reference) says how to call each route, in a few lines. What explains the reason for each decision, the edge cases and the warnings is here, in the order of the reference. ### GET /v1/templates The status you get here is the last one Luna observed, not a live read at Meta. For the current state of one template, use the read by identifier. Use ?wabaId= to see only the templates of one business account, or ?phoneNumberId= (Luna's UUID or Meta's id) to see those of the account a number belongs to: with one account per customer of yours, that is how you separate templates by customer. A template belongs to the account, not to the number. Use ?status= to filter by state, for example ?status=PAUSED. The comparison is literal and case sensitive, and the field takes any text: Meta adds new states without notice, and a closed list would stop you from filtering by the new one the day it shows up. The category returned is the one Meta assigned AT CREATION, and it may not be the one that was requested, because Meta reclassifies. Luna does not keep it up to date after that: if Meta reclassifies a template that was already approved, the value you read here is still the one from creation. For the current category, check Meta's own panel. Approved does not mean cleared for bulk sending. Meta applies its own pacing over the first sends. ### POST /v1/templates Templates are what let you start a conversation outside the 24 hour window. Inside the window, free text is enough. The category in the response is the one Meta assigned, and it may not be the one you asked for, because Meta reclassifies on creation. What Luna stores is what Meta answered, never what was requested. And it is the category assigned AT CREATION: Luna does not keep it up to date after that. For the current category of an older template, check Meta's own panel. Each language is a SEPARATE template for Meta. Ten templates in nine languages are ninety templates, and the ceiling is 250 per WhatsApp Business Account. The ceiling is Meta's and it is the same for every customer: it exists for their platform capacity, and it does not vary. Approved does not mean cleared for bulk sending. Meta applies its own pacing over the first sends. Media header: use headerMedia with format IMAGE, VIDEO or DOCUMENT and the handle returned by POST /v1/template-assets. That handle is not the media identifier that POST /v1/numbers/{id}/media returns: they are two Meta endpoints with different purposes, and a media identifier in place of the handle makes the creation fail. For documents Meta accepts PDF only. Neither GIF nor location is accepted, and that is a decision rather than an oversight. The headerMedia file is the EXAMPLE Meta reviews, and not the content that gets delivered. Every message you send with this template supplies its own media, in the header component of the send. Anyone who creates the template believing the example image is the image sent will end up sending messages with no header. The two headers are exclusive: header is the text one, headerMedia is the media one, and Meta accepts one per template. ### GET /v1/templates/{id} The state is free text and not a closed set, on purpose: Meta adds new values without notice, and a closed set would turn that into a Luna error. ### PATCH /v1/templates/{id} The update is PARTIAL: whatever you leave out stays as it is. That is why the verb is PATCH and not PUT, since PUT would promise to replace the whole template, and that is not what happens. Name, language and business account CANNOT be changed: Meta does not accept changing them after the template is created. For a different name, create another template. If you send any component, send bodyText as well: Meta refuses a template with no body. Editing submits the template for approval again, and the state changes. Wait for the template.status event on your webhook endpoint, or read the state afterwards. ### DELETE /v1/templates/{id} WARNING: Meta deletes templates by NAME, and that removes ALL language versions of that name, not only the one you are deleting. If you keep the same template in three languages, this call deletes all three at Meta. Luna removes from your listing only the one you asked for: the other language versions keep showing up here and no longer exist there. The consequence is Meta's, it is destructive, and it does not change. Deletion is permanent. A deleted template does not come back, and creating another one with the same name starts approval from scratch. Deleting twice is safe: the second call returns 404, the same 404 as an identifier that never existed. ### POST /v1/templates/authentication This is a separate creation path, and not one more category on POST /v1/templates. The reason is that the content is not yours: the body is fixed by Meta and cannot be customised, with the text "{{1}} is your verification code." translated into the template language, and the text property is not accepted. That is why this route takes no body, no examples, no header, no footer and no buttons. What you choose is the name, the language, whether the security recommendation shows up, in how many minutes the code expires and, if you want it, the button label. The security recommendation and the expiry notice are also Meta's texts, generated in the template language. The button label, when omitted, comes in the template language already translated, and omitting it is the recommended choice. The category in the response is the one Meta assigned, as on any creation, and Luna stores what Meta answered. Each language is a SEPARATE template for Meta, and the ceiling of 250 per WhatsApp Business Account applies here too. The ceiling is Meta's and it is the same for every customer: it exists for their platform capacity, and it does not vary. Three things about SENDING that are worth knowing before you integrate. First: the one time password goes TWICE in the message you send, once in the body component and once in the button component. That is the format, and not redundancy to be optimised away. Second: the password takes at most 15 characters. Third, and this one is a gap we would rather declare than fill with a guess: the exact shape of the button component on send is not published here yet, because Meta's documentation has two pages that disagree about it and nobody in this house has run a send to decide. It will be published once that run exists. ### POST /v1/template-assets This handle is NOT the media identifier that POST /v1/numbers/{id}/media returns. They are two Meta endpoints with different purposes: that one is for sending a message, this one is for the example Meta reviews when approving the template. A media identifier in place of the handle makes the creation fail. In practice you can spot the mix up from a distance: the media identifier is a long decimal number, and the handle is not numeric. The file here is the EXAMPLE, and not the content that gets delivered. It exists so Meta can see what the template looks like. Every message you send afterwards supplies its own media. Anyone who creates the template believing this image is the one that reaches the recipient will end up sending messages with no header. The accepted types are application/pdf, image/jpeg, image/jpg, image/png and video/mp4. The list is narrower than the one for message media upload because it is the list of the endpoint this route calls, and for documents it accepts PDF only. Neither GIF nor location is accepted, and that is a decision rather than an oversight: the requirement names image, video and document. The file content is checked against the declared type before any call to Meta. A file declared as image/png whose bytes are something else is refused with 400 here, so none of your calls are spent. A file above the ceiling is refused with 413 before any call to Meta. The ceiling is the same for every customer: it exists for infrastructure capacity, and it does not vary. How long the handle lasts: Meta does not publish an expiry, and Luna does not store the value. Get the handle and use it to create the template right after. If it stops working, upload the file again. --- # Errors Fonte: https://lunahia.com.br/en/docs/errors Every API error returns a JSON body with `error` and `message`. The `error` is a stable code, meant for your code to decide what to do. The `message` is text for a person to read, in Portuguese. ## The error shape `400` ```json { "error": "invalid_request", "message": "Requisição inválida.", "campos": [{ "campo": "text.body", "motivo": "Não pode ficar vazio." }] } ``` - Decide by the `error` and the status, never by the text of `message`. - Every error carries `docsUrl`, the address of the site guide that explains that `error` (the ones with no guide of their own point to this page). Use it for the "Learn more" link on your screen instead of building the address. - Some errors add fields that say what to do: `campos`, `fechadaEm`, `acaoRecomendada`, `estado`, `faltando`, `tentativasRestantes`, `janelaVira`, `reenfileiradoEm` and `credentialStatus`. They are in the table below. - No error echoes back the value you sent. On a `400`, what comes out is the path of the refused field and the reason, in one short sentence, never its content. - `404` also stands for a resource that exists and is not yours. The API does not confirm the existence of another customer’s resource, not even by status. ## The main codes | Status | `error` | What it means, and what to do | | --- | --- | --- | | 400 | `invalid_request` | The body or query does not match the contract. The `campos` field lists each refused field in `campo` and the reason in `motivo` (in Portuguese), for example "Curto demais: no mínimo 3 caracteres.", "Valor não aceito. Valores aceitos: text, image." or, on a field with a fixed format such as the phone number, the expected format ("Só dígitos, com o código do país e sem o sinal de mais"). The `motivo` is text to read: decide by `campo`. A query parameter the route does not know is also refused, on every `GET` route, so a misspelled filter does not silently return the whole list. Fix it and send again. Repeating the same request repeats the refusal. | | 401 | `unauthorized` | The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. Check the `Authorization: Bearer hlsn_...` header and whether the key was revoked. | | 403 | `forbidden` | The key lacks the route’s scope. The `requiredScope` field says which scope is missing (for example `numbers:read`), and the `message` quotes it. Create a key with that scope, and give each key only what it needs. The answer talks about the verb, never about the resource. | | 403 | `test_key_not_allowed` | The key is a test key and the route is not part of test mode. The test key only uses `POST /v1/messages` and `POST /v1/test-mode/inbound-messages`. For this operation, use a production key. See [Test mode](https://lunahia.com.br/en/docs/test-mode). | | 403 | `connection_not_released` | The account cannot open a number connection yet. The `faltando` field lists the condition (`email_confirmado`). Confirm the account’s e-mail. | | 403 | `trial_expired` | The free trial ended. Sending and the other writes are paused, while reading and receiving continue. See [Plan and numbers](https://lunahia.com.br/en/docs/plan-and-numbers#fim-do-teste). | | 403 | `account_blocked` | Helsen blocked the account. The effect is the same as an ended trial. Write to sales to learn the reason. | | 404 | `not_found` | The resource does not exist, or is not yours. The two answers are identical, byte for byte. Check the identifier, and whether it is Luna’s or Meta’s for this route. When the missing resource is pointed to by the body (the `from` of `POST /v1/messages`, for example), `campos` says which field it was, and the `message` says where to find the right id (`GET /v1/numbers`). | | 409 | `number_capacity_reached` | The account already has as many active numbers as the plan’s capacity. Disconnect a number with `DELETE /v1/numbers/{id}` or increase the capacity with sales. See [Plan and numbers](https://lunahia.com.br/en/docs/plan-and-numbers#capacidade-atingida). | | 409 | `window_closed` | The [24-hour window](https://lunahia.com.br/en/docs/glossary#janela) is closed. `fechadaEm` says when it closed, and `acaoRecomendada` says the path: send a template, and free-form messages come back once the contact replies. If the contact wrote a moment ago, check that `to` is the phone of the event (`wa_id`). The `detalheTecnico` carries the rest, for whoever already checked that: Luna finds a Brazilian mobile with and without the ninth digit, and no other difference, and whoever wrote with only the BSUID takes `recipient`. There is no `Retry-After`, and repeating does not help. See [Send messages](https://lunahia.com.br/en/docs/send-messages#janela). | | 409 | `template_not_approved` | The template exists in your account, but Meta has not approved it yet, or rejected or paused it. `templateStatus` carries the state. Wait for the `template.status` event (or read `GET /v1/templates/{id}`), or fix the template. A template created directly in Meta’s panel does not go through this check. | | 409 | `template_content_unknown` | Luna does not know the content of the template you asked to copy: it was created directly in Meta’s panel, or before Luna stored the content. Create the template again with `POST /v1/templates` and copy the new one. See [Templates](https://lunahia.com.br/en/docs/templates#copiar). | | 409 | `link_not_open` | You asked to generate again the `url` of a link that is not open: `status` says whether it was used, expired or revoked. Only an open link can be reissued. Create a new link with `POST /v1/onboarding/links`. See [Connect a number](https://lunahia.com.br/en/docs/connect-a-number). | | 409 | `message_not_cancelable` | You asked to cancel a message that is no longer in the queue: `status` gives the current state (`sent`, `failed`, `canceled`, or `accepted` when the send was already reserved and is going out). Only a message in `accepted` and not yet reserved can be canceled. Check the result with `GET /v1/messages/{id}`. See [Send messages](https://lunahia.com.br/en/docs/send-messages). | | 409 | `idempotency_key_reused` | The `Idempotency-Key` was already used with a different body, and nothing was sent. To repeat the original message, resend the same body with the same key. For a new message, use a new key. | | 409 | `media_not_ready` | The media has not been fetched yet. `estado` says where it stands: `pendente` and `falhou` come back on their own, `expirado` is final. Try again later. On the notice link (`GET /v1/media/{token}`), `pendente` carries `Retry-After`: wait that long. | | 409 | `no_webhook_endpoint` | You asked to replay a webhook and have no active endpoint. Register one at `POST /v1/webhooks/endpoints`, or resume a paused one with `PATCH /v1/webhooks/endpoints/{id}`, and ask again. | | 409 | `webhook_endpoint_limit` | The customer already has the maximum number of webhook endpoints (`limit`, today 25), the same for everyone. Remove one with `DELETE /v1/webhooks/endpoints/{id}` to free the slot. See [Receive events](https://lunahia.com.br/en/docs/receive-events#gerir). | | 409 | `already_requeued` | This item in the rejected queue was already requeued. `reenfileiradoEm` says when. Nothing to do. | | 409 | `pin_not_applicable` | The number is not waiting for the PIN. `state` says where it stands. See [Connect a number](https://lunahia.com.br/en/docs/connect-a-number#outro-provedor). | | 409 | `not_available_in_coexistence` | The number is in coexistence and Meta does not accept this operation through the API in that case (today, the business profile). Make the change in the business’s WhatsApp Business app on the phone. See [What the number does at Meta](https://lunahia.com.br/en/docs/number-on-meta#perfil). | | 422 | `meta_rejected` | Meta refused a number management operation (profile, block or QR code). The `meta` field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. See [What the number does at Meta](https://lunahia.com.br/en/docs/number-on-meta). | | 409 | `register_budget_reserved` | The registration attempts Meta grants the number in 72 hours are near the end. `tentativasRestantes` and `janelaVira` say how many are left and when the window turns over. Confirm the PIN with the end business before trying again. | | 409 | `reconnect_not_applicable` | This number’s authorization does not allow reconnection. `credentialStatus` says the state. | | 413 | `file_too_large` | The file goes over the upload ceiling, which is the same for every customer. The refusal happens before any call to Meta. Send a smaller file. | | 429 | `rate_limited` | You went over the key’s request limit. Wait the `Retry-After` time. See the [next section](#limite). | | 429 | `queue_full` | This number’s send queue is full. Wait the `Retry-After` time and try again. | | 429 | `number_rate_limited` | This number is at its limit of calls per second. Wait the `Retry-After` time. | | 429 | `management_busy` | The connection’s management operations (creating and editing templates, for example) hit the momentary limit. Wait the `Retry-After` time. | | 500 | `internal` | Unexpected failure on Luna’s side. The body carries no detail, and the detail stays in the internal log. Try again, and if it persists, ask for help with the time and the message identifier. | | 503 | `unavailable` | The platform cannot serve right now. Try again with a growing wait. This same body also shows up, on purpose, when you try to connect an account or number that already belongs to another customer: the API does not confirm the existence of another’s resource. So, when connecting, a `503` that repeats the same after three spaced attempts is not unavailability: stop retrying and ask the number’s owner to disconnect it from where it is connected, or contact support. In a real outage the wait passes and the same request works again. | The four `429` codes come from different places, and the response carries `Retry-After`, in seconds. If it is missing, wait with a growing backoff, as the code below does. Luna’s `429` is **never** Meta’s pacing limit handed back to you: that limit is resolved by queue, which is why sending answers `202`. ## The request limit Each API key can make **600 requests per minute**. The limit is technical and identical for every customer. No limit on this platform varies with price. A request without a key is counted by its source address. All the limits together, with what each one does when you go past it, are in [Limits and pacing](https://lunahia.com.br/en/docs/limits-and-pacing). | Header | What it carries | | --- | --- | | `X-RateLimit-Limit` | The window’s ceiling. | | `X-RateLimit-Remaining` | How many requests still fit in the window. | | `X-RateLimit-Reset` | In how many seconds the window starts over. | | `Retry-After` | On `429` responses: how many seconds to wait before trying again. | - The three `X-RateLimit-*` headers accompany successful responses. Read `X-RateLimit-Remaining` and slow down before it reaches zero. - On a `429`, wait the `Retry-After`. Retrying right away is only refused again. - Account sign-up has a ceiling of its own: 5 per hour per source address. ### Retrying safely Retry only `429` and `503`, and wait the `Retry-After`. For `POST /v1/messages`, always send the `Idempotency-Key`, and **the same one** on every attempt: without it, a retry after a timeout can send the message twice. Do not retry `400`, `401`, `403`, `404` or `409`: the answer does not change. ```js const BASE = 'https://api.lunahia.com.br'; async function lunaFetch(path, options = {}, attempts = 5) { for (let attempt = 1; ; attempt++) { const res = await fetch(`${BASE}${path}`, { ...options, headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', ...options.headers, }, }); const retryable = res.status === 429 || res.status === 503; if (!retryable || attempt === attempts) return res; // Retry-After is in seconds. Without it, back off 2, 4, 8... seconds. const wait = Number(res.headers.get('retry-after')) || 2 ** attempt; await new Promise((resolve) => setTimeout(resolve, wait * 1000)); } } // One Idempotency-Key for all attempts, so a retry never sends twice. const res = await lunaFetch('/v1/messages', { method: 'POST', headers: { 'Idempotency-Key': crypto.randomUUID() }, body: JSON.stringify({ from: 'YOUR_PHONE_NUMBER_ID', to: '5511999990000', text: { body: 'Olá!' }, }), }); const body = await res.json(); if (!res.ok) { console.error(res.status, body.error, body.message); } else { console.log(res.status, body); } ``` ```python import os import time import uuid import requests BASE = "https://api.lunahia.com.br" def luna_request(method, path, attempts=5, **kwargs): headers = { "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", **kwargs.pop("headers", {}), } for attempt in range(1, attempts + 1): res = requests.request( method, BASE + path, headers=headers, timeout=10, **kwargs ) if res.status_code not in (429, 503) or attempt == attempts: return res # Retry-After is in seconds. Without it, back off 2, 4, 8... seconds. time.sleep(int(res.headers.get("Retry-After", 2**attempt))) # One Idempotency-Key for all attempts, so a retry never sends twice. res = luna_request( "POST", "/v1/messages", headers={"Idempotency-Key": str(uuid.uuid4())}, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511999990000", "text": {"body": "Olá!"}, }, ) body = res.json() if not res.ok: print(res.status_code, body["error"], body["message"]) else: print(res.status_code, body) ``` ## When the message is accepted and then fails The send’s `202` means Luna accepted the message, not that it was delivered. The failure can come later, from Meta, and you see it two ways: in the webhook, with a `message.status` of `status: "failed"`, the `error_code` and the `error` object, and in `GET /v1/messages/{id}`, in the `erros` field. This also holds when Meta refuses the send in its own response (revoked token, number without WhatsApp, wrong template parameter, window closed on Meta’s side, payment method): Luna marks the message as failed right away, does not retry, and the same event reaches your endpoint, with a null `wamid`, because Meta never accepted the message. Correlate by `id`. A passing failure at Meta, such as a timeout, is not a failure: Luna retries on its own and no `failed` is emitted. ```json { "codigo": 131026, "categoria": "nao_entregavel", "mensagem": "O destinatário não pode receber esta mensagem: o número não tem WhatsApp, ou não existe.", "acaoRecomendada": "Confira o número do destinatário e reenvie para o número correto. Repetir o envio para o mesmo número não muda o resultado.", "original": { "error": { "message": "Message undeliverable", "type": "OAuthException", "code": 131026, "fbtrace_id": "EXAMPLE_TRACE_ID" } } } ``` | `erros` field | What it is | | --- | --- | | `codigo` | Meta’s error code, intact. Null when Meta did not answer: a timeout, for example, has no code. | | `categoria` | The error’s nature, in Luna’s vocabulary. The values are `parametro_invalido`, `reauth_required`, `recurso_inacessivel`, `orcamento_management`, `throughput_excedido`, `estado_de_produto`, `janela_de_atendimento`, `midia_indisponivel`, `nao_entregavel`, `template_invalido`, `ritmo_por_destinatario`, `terminal`, `transporte`, `contrato` and `desconhecido`. | | `mensagem` | What happened, in Portuguese. It is Helsen’s text, not a translation of Meta’s message. | | `acaoRecomendada` | What to do, in one actionable sentence. | | `original` | Meta’s error body, with no rewriting and no filtering. It is what Meta’s support recognizes. | - `desconhecido` (unknown) is literal and deliberate: Meta adds codes without notice, and a code not yet mapped arrives under that category rather than being hidden. Read the `codigo` and the `original`. - `erros` gathers what Meta refused at send time and what it reported afterwards, through a status event. You do not need to know which of the two each item came from: the `acaoRecomendada` is the one that fixes it. - **Take care when passing `original` on.** It can contain the end consumer’s phone number and parts of the conversation. Treat it with the same care as the rest of the message content before sending it to third parties. - When asking Meta for help, the `fbtrace_id` inside `original` is what moves a ticket forward. > The API reference carries each route’s contract and body examples, in the [API reference](https://lunahia.com.br/en/docs/reference). --- # Limits and pacing Fonte: https://lunahia.com.br/en/docs/limits-and-pacing The rule for every Luna limit fits in one sentence: it exists for infrastructure capacity and is the same for every customer. None varies with price. This page gathers the ones that matter to whoever sends a lot, an AI agent for example, with what each one does when you go past it. The live list, with each limit’s value and reason, is at `GET /v1/limits` (`numbers:read` scope). Each route’s contract is in the [API reference](https://lunahia.com.br/en/docs/reference). ## The limits, in one table | Limit | Value | What happens when you go past it | | --- | --- | --- | | Requests per key | 600 per minute | `429` with `error: "rate_limited"` and `Retry-After`. Wait the indicated time. See [Errors](https://lunahia.com.br/en/docs/errors#limite). | | Burst of each conversation (the same origin number and the same recipient) | 30 messages at once, then one every 7 seconds | Nothing fails: the message waits in the queue and goes out in order. The `202` comes back the same, and this limit never becomes a `429`. | | Sends per number | 55 per second (20 per second on a number in coexistence) | What goes past the pace waits in the queue and goes out in order. The live value is at `GET /v1/limits`. | | Send queue per number | 5,000 pending messages | `429` with `error: "queue_full"` and `Retry-After`, the time the queue takes to drain. Nothing was accepted: repeat later, with the same `Idempotency-Key`. | | `/read` and `/typing` | They share the number’s per-second pace | `429` with `error: "number_rate_limited"` and `Retry-After`. They are synchronous and lose their value with time: if you go past it, wait and try, or leave it to the reply. | | New conversations per day (Meta’s) | The tier in `limiteDiarioDeConversas` | Meta refuses the send and the reason arrives in `message.status` with `failed`. See the section below. | | Business account management operations (creating and editing templates, for example) | 150 per hour on an account with no registered number, and 3,750 per hour with a number | `429` with `error: "management_busy"` and `Retry-After`. The ceiling is shared with the number connection, so a loop that creates many templates can delay a connection. | | Text of a message | 4096 characters | `400` with `campos`. See [Send messages](https://lunahia.com.br/en/docs/send-messages#basico). | | `typingMs` | 1 to 25000 milliseconds | `400` with `campos`. See [Send messages](https://lunahia.com.br/en/docs/send-messages#lida-e-digitando). | | File uploaded to Luna | 100 MB | `413` with `error: "file_too_large"`, before any call to Meta. | | Webhook endpoints per account | 25 | `409` with `error: "webhook_endpoint_limit"`. Removing one frees the slot. | | Time your endpoint has to answer | 10 seconds | The delivery counts as a failure and is retried. See [Receive events](https://lunahia.com.br/en/docs/receive-events#entrega). | > Why is the burst 30 and one every 7 seconds, and not Meta’s numbers? Luna runs with margin over what Meta publishes, because Meta’s count is not visible from outside. You do not need to adjust to it: Luna accepts, queues and delivers at the right pace. ## What waits and what fails There are two families of limit, and the difference decides your code. The **pace** ones (the burst of each conversation and sends per number) never fail: the message is accepted with `202` and Luna delivers it when the pace allows, in order. The **refusal** ones (requests per key, full queue, `/read` and `/typing`) answer `429` with `Retry-After`, and nothing was accepted. - On a `429`, wait the `Retry-After` and repeat **with the same `Idempotency-Key`**: if the first attempt got through, the repeat returns the original message instead of sending twice. - An agent that replies in bursts needs no `sleep` between messages: the wait happens in Luna’s queue. - The burst holds **within each conversation**: a slow conversation does not delay the other ones of the same number. - The state of a message that waits is `queued`, and `sent` arrives when it goes out. See [Send messages](https://lunahia.com.br/en/docs/send-messages#estados). - The ready-made retry code, in Node and Python, is in [Errors](https://lunahia.com.br/en/docs/errors#limite). ## The daily conversation limit This is a limit **from Meta**, and Luna only shows it. `GET /v1/numbers` returns, on each number, `limiteDiarioDeConversas`: the name of the tier Meta placed the business portfolio in (`TIER_250`, `TIER_2K`, `TIER_10K`, `TIER_100K` or `TIER_UNLIMITED`; Meta may add others). It counts unique people the business **starts** a conversation with outside the service window, in a 24-hour period, and not messages, and it is the same for all numbers in the portfolio. Talking to someone who wrote first, inside the [24-hour window](https://lunahia.com.br/en/docs/glossary#janela), does not count. - The field says the ceiling Meta granted, and **never** how much you have used. There is no route that returns consumption. - **The initial limit.** A new business portfolio starts at `TIER_250`: 250 unique people you start a conversation with per 24-hour period ([Meta documentation](https://developers.facebook.com/documentation/business-messaging/whatsapp/messaging-limits)). People who **wrote first** inside the service window do not count. To go up, Meta asks for the business to be verified (or the partner that connected it), or for 2,000 delivered messages outside the window, to unique people and with good-quality templates, within 30 days; after that the rise is automatic (10 thousand, 100 thousand, unlimited) with high quality and use of half the current limit in 7 days. For a new customer, plan the first mass send below 250 people a day. - When Meta changes the tier, the `account.limit_changed` event announces it. See [Account health](https://lunahia.com.br/en/docs/account-health). - Went past the ceiling: Meta refuses the send and the reason arrives in `message.status` (`failed`), in the `error` field. See [Errors](https://lunahia.com.br/en/docs/errors#envio). - Do not confuse it with `throughputLevel`, which is **speed** (messages per second) and not the number of conversations. ## What no limit is No limit on this page is a quota per plan. Luna’s plan defines one thing only: how many numbers the account keeps active ([Plan and numbers](https://lunahia.com.br/en/docs/plan-and-numbers)). The request ceiling, the pace and the queue are the same for everyone, and exist for capacity. --- # Account health Fonte: https://lunahia.com.br/en/docs/account-health When Meta restricts, deactivates or disconnects your customer’s account, sending stops working and their agent goes quiet. Luna passes these notices on as events and keeps the last state, so your system acts at once instead of finding out from the end customer. ## One account notice, one event per number Meta notifies the **business account** (the WABA), not a number. Luna’s envelope is per number, so each notice is sent **once for every connected number of the account**, all with the same `waba_id` inside the `waba` object. To handle the notice only once, group by `waba_id`. An account with no connected number produces no event; its state stays in `GET /v1/business-accounts`. | Event | When it is sent | What your system does | | --- | --- | --- | | `account.restricted` | Meta restricted the account. | Read the type and the deadline, tell the customer, adjust what the restriction blocks. | | `account.violation` | Meta recorded a policy violation. | Handle the cause before it becomes a restriction. | | `account.disabled` | Meta deactivated the account. | Stop trying to send and ask Meta for a review. | | `account.reinstated` | Meta reinstated the account. | Resume sending. | | `number.disconnected` | The number is no longer connected to Luna. | Open a new connect link. | | `account.limit_changed` | Meta changed the account limit. | Adjust the sending pace to the new ceiling. | | `number.quality_changed` | The number’s quality changed. | Reduce what causes complaints. | | `account.alert` | Meta sent an alert about the account (`account_alerts`). | Read the `alert_type` and the description, and tell the customer. | | `number.credential_expiring` | The authorization the customer gave Luna expires within 14 days. | Open a reconnection link for the number and send it to the customer. | | `account.update` | Another account notice Luna does not translate. | Read the raw `event` and decide, or ignore it. | ## Where to read the state, without a webhook Meta offers no lookup for this state. Luna keeps the last notice it received and returns it in two places. In `GET /v1/business-accounts`, each account carries `status`, with `restricted`, `restrictions`, `disabled`, `violationType` and `reportedAt`. In `GET /v1/numbers` and `GET /v1/numbers/{id}`, each number carries `waba`, with `id`, `restricted` and `disabled`, ready for a screen to show without calculating anything. Both places also carry the validity of the customer’s authorization (`credentialExpiresAt` and `credentialNeverExpires`) and the payment method at Meta (`paymentMethodOnMeta` and `currency`), described in the sections below. A restricted account, in GET /v1/business-accounts ```json { "id": "ed404df1-b420-4ed6-8743-ba1609892e0a", "wabaId": "102290129340398", "numbers": ["+55 11 90000-0000"], "status": { "restricted": true, "restrictions": [ { "restrictionType": "RESTRICTED_ADD_PHONE_NUMBER_ACTION", "expiration": "2026-11-13T12:00:00Z", "remediation": null } ], "disabled": false, "violationType": null, "reportedAt": "2026-10-13T12:00:00.000Z" }, "createdAt": "2026-08-07T11:27:41.208Z" } ``` > `restricted` only holds while the restriction deadline has not passed, because Meta does not announce the end of a timed restriction. If the deadline cannot be read as a date, the restriction counts as active until a new notice, and `restrictions` returns the value as Meta sent it so you can check. ## Restricted account: `account.restricted` **What it means.** Meta imposed a restriction on the account. What it blocks depends on the type, in `restrictions[].restriction_type` (for example, adding numbers or starting conversations). `expiration` carries the deadline as Meta reported it and `remediation` carries its guidance, when there is any. ```json { "version": "2026-11-10", "event_id": "d3b1b97cb8b69ac0bf9db087b5200febbea3dcbcc8d0a4108913592b51fdaf29", "event_type": "account.restricted", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "restrictions": [ { "restriction_type": "RESTRICTED_ADD_PHONE_NUMBER_ACTION", "expiration": "2026-11-13T12:00:00Z", "remediation": null } ] } } ``` - **Cause.** It usually comes from complaints, contacts blocking the number, or use outside Meta’s policy. A restriction for abusing utility templates, for example, follows a ladder of Meta warnings before it gets here. - **Fix.** Read the type and the deadline, and tell your customer. The account owner handles the cause, in Meta’s WhatsApp Manager, by the route Meta itself indicates in the notice. While it lasts, do not insist on what the restriction blocks. - **How to know it ended.** Meta does not announce the end of a timed restriction. Check `expiration`, or read `status.restricted` in `GET /v1/business-accounts`, which stops holding when the deadline passes. ## Policy violation: `account.violation` **What it means.** Meta recorded a policy violation on the account, with the type in `violation_type`. It is a warning: the account can be restricted or deactivated if the violation is not handled. ```json { "version": "2026-11-10", "event_id": "a2fa828795bf24fd8e7460738c1a1e11a1bcd278fc09a0d238f92ba8c5994441", "event_type": "account.violation", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "violation_type": "ALCOHOL_VIOLATION" } } ``` - **Cause.** Content or behavior that Meta’s policy does not allow, indicated by the type. - **Fix.** Find which content or flow caused the violation, fix it and tell the account owner. A violation does not expire on its own: `status.violationType` keeps the last type announced. ## Deactivated and reinstated account: `account.disabled` and `account.reinstated` **What it means.** `account.disabled` says Meta deactivated the account: sends stop being accepted. `account.reinstated` says it came back. Meta also announces a **scheduled** deactivation, and that notice arrives as `account.update` with `event` equal to `DISABLED_UPDATE`, because the account is not deactivated yet. Deactivated ```json { "version": "2026-11-10", "event_id": "b0308dcc1ab6324eaea0474f1bcdec28146d3a6eb62668a1425fb3a7d6aad778", "event_type": "account.disabled", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "ban_date": "2026-10-13" } } ``` Reinstated ```json { "version": "2026-11-10", "event_id": "135a9c7b3f192a7cab5ea55f68e0a8113e8d8e80acaa0ae8dad7f20aaf61f2db", "event_type": "account.reinstated", "occurred_at": "2026-10-14T09:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "ban_date": null } } ``` - **Cause.** A serious or repeated violation of Meta’s policy, or a restriction that was not resolved. - **Fix.** The account owner asks Meta for a review. Luna does not reinstate accounts and cannot ask for it on their behalf. While it is deactivated, stop sending: every attempt only fails. - **How to know it is back.** By `account.reinstated`, or by `status.disabled` equal to `false` in `GET /v1/business-accounts`. ## Disconnected number: `number.disconnected` **What it means.** The number is no longer connected to Luna. It is the pair of `number.connected`. The `reason` field says which Meta notice caused the disconnection: `PARTNER_APP_UNINSTALLED` (the customer removed the app), `PARTNER_REMOVED` (Luna was removed as the account’s partner) or `ACCOUNT_OFFBOARDED` (the account’s link to Luna was ended). `disconnection_reason` and `initiated_by` carry what Meta reported, when it reports. ```json { "version": "2026-11-10", "event_id": "0dfe4e31d4e40e4a5da6d3f42f0d44b660f67ce551b2a43966e5fb0390fcd741", "event_type": "number.disconnected", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "reason": "PARTNER_APP_UNINSTALLED", "disconnection_reason": null, "initiated_by": null } } ``` - **Cause.** Almost always, the customer removed the app in their own Business Manager. - **What state the number ends up in.** It depends on the cause, and the event name is not the state name. When the customer removes the app (`PARTNER_APP_UNINSTALLED`), their authorization stops being valid: the number gets `connection.status: "action_required"`, `canSend: false` and the reason `credential_invalid` in `connection.reasons`, and reconnection is through the link (`POST /v1/onboarding/links` with `numberId`). When **you** disconnect with `DELETE /v1/numbers/{id}` (`reason: "requested_by_tenant"`), the number gets `connection.status: "disconnected"`, `canSend: false` and empty `reasons`. For `PARTNER_REMOVED` and `ACCOUNT_OFFBOARDED` the event is delivered, but today only the uninstall changes the number’s state by itself: check `connection` before concluding it stopped. So decide by the event’s `reason`, or read `connection` in `GET /v1/numbers/{id}`, and do not always expect `disconnected`. - **Fix.** Sends from this number no longer work. To come back, your customer has to connect again: open a new connect link (see [Connect a number](https://lunahia.com.br/en/docs/connect-a-number)) and ask them to finish it. The message history stays in `GET /v1/messages`. ## Account limit: `account.limit_changed` **What it means.** Meta changed the account limit. `daily_conversation_limit` is Meta’s messaging limit, in its tier names: `TIER_250`, `TIER_2K`, `TIER_10K`, `TIER_100K` or `TIER_UNLIMITED` (250, 2,000, 10,000 and 100,000 people per 24-hour period, or no ceiling). It counts unique people the business writes to outside the customer service window, not messages, and it belongs to the **business portfolio**, shared by all its numbers. And `max_phone_numbers_per_waba` is the account’s number ceiling. One of the two is `null` when the notice changed only the other. It is the ceiling Meta granted, never how much was used. The limit belongs to the business portfolio, so it holds for all numbers of the account. ```json { "version": "2026-11-10", "event_id": "a3bddf693de91539edaebb432d0d4f936b40822085cafa5c7864ae149756dbff", "event_type": "account.limit_changed", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "daily_conversation_limit": "TIER_2K", "max_phone_numbers_per_waba": null } } ``` - **Cause.** Meta raises the limit when quality is good and volume calls for it, and lowers it when quality drops. - **Fix.** Adjust the sending pace to the new ceiling. Each number’s current value is in `limiteDiarioDeConversas`, in `GET /v1/numbers`. ## Number quality: `number.quality_changed` **What it means.** The number’s quality rating changed, from `previous_quality_rating` to `quality_rating` (`GREEN`, `YELLOW`, `RED`). Meta has no webhook for this: Luna checks each number’s quality periodically, and the event is sent when the check sees the change. It arrives with a delay of up to about an hour. ```json { "version": "2026-11-10", "event_id": "cc81de4eb28ad6a80e39c6cca13eb4b6db12f223f3c1346552cbc24795bcdbbe", "event_type": "number.quality_changed", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "previous_quality_rating": "GREEN", "quality_rating": "YELLOW" } } ``` - **Cause.** Contacts block or report the number, or complain about the messages. - **Fix.** Reduce what causes complaints: messages the contact did not ask for, high frequency, unexpected content. Low quality leads to a lower limit and, later, to a restriction. The history is in `GET /v1/numbers/{id}/health`. ## Authorization about to expire: `number.credential_expiring` **What it means.** The authorization your customer gave Luna to operate the number expires within 14 days (`credential_expires_at`). That authorization can have an expiry (the current connection setup issues it with a 60-day validity); when it expires, Meta refuses Luna’s calls on that account and the number stops sending and receiving. This is the one notice in the family that comes **before** the problem. Luna reads the validity at connection time and checks it every hour, and the notice is sent **once per expiry and per number of the account**: renewing the authorization changes the expiry and allows a new notice. An authorization issued without an expiry never produces the event. ```json { "version": "2026-11-10", "event_id": "33b03111fe7f1f225626ece55b50955389e78742a6b99059f05be056ce2b2260", "event_type": "number.credential_expiring", "occurred_at": "2026-11-21T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "credential_expires_at": "2026-12-05T12:00:00.000Z" } } ``` - **Cause.** The authorization’s own expiry. Nothing went wrong on your customer’s side. - **Fix.** Create a reconnection link with `POST /v1/onboarding/links` passing `numberId`, and send it to your customer. The page opens that number’s renewal directly, does not count a new number and keeps your `externalId`. The same applies if `credentialStatus` is already `reauth_required`. Whether renewal is allowed is the API’s call: the `podeReconectar` field of `GET /v1/numbers/{id}` becomes `true` 14 days before the expiry. - **Where to read it without a webhook.** `credentialExpiresAt` (the date) and `credentialNeverExpires` (`true` when Meta reported it does not expire, null until Luna has read it) in `GET /v1/business-accounts` and in each number’s `waba` object. ## Meta alert: `account.alert` **What it means.** Meta sent an alert about the account (the `account_alerts` field), for example a denied limit increase (`INCREASED_CAPABILITIES_ELIGIBILITY_DEFERRED`, `INCREASED_CAPABILITIES_ELIGIBILITY_FAILED` or `INCREASED_CAPABILITIES_ELIGIBILITY_NEED_MORE_INFO`) or a lost profile picture (`PROFILE_PICTURE_LOST`). The fields arrive as Meta sent them, untranslated and with no closed list of values: `entity_type`, `entity_id`, `alert_severity`, `alert_status`, `alert_type` and `alert_description`. What Luna does not name yet goes in `details`. Like the other account notices, one event goes out per connected number, all with the same `waba_id`. ```json { "version": "2026-11-10", "event_id": "fb613a0660724669d9251d4185488ec26409b34345c592b908ce9747b8430f99", "event_type": "account.alert", "occurred_at": "2026-10-19T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "entity_type": "WABA", "entity_id": "102290129340398", "alert_severity": "INFORMATIONAL", "alert_status": "ACTIVE", "alert_type": "INCREASED_CAPABILITIES_ELIGIBILITY_DEFERRED", "alert_description": "Messaging limit increase deferred.", "details": {} } } ``` - **Cause.** It depends on the `alert_type`. The text in `alert_description` is Meta’s. - **Fix.** Show the alert to the account owner and let them handle it in Meta’s WhatsApp Manager. Treat new `alert_type` values as information, not as an error: Meta adds types without notice. ## Other notices: `account.update` Every Meta account notice that has no type of its own arrives as `account.update`, with Meta’s raw `event` field and the rest in `details`: `ACCOUNT_DELETED`, `ACCOUNT_RECONNECTED`, `VOLUME_BASED_PRICING_TIER_UPDATE`, the scheduled deactivation and whatever Meta adds. Luna does not invent a meaning for them. If your system does not use them, ignore them. ```json { "version": "2026-11-10", "event_id": "f663ad9f077e865db5d29245db96fe579e9aaa487bdf2f9d91a6e535af3d7949", "event_type": "account.update", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "event": "ACCOUNT_DELETED", "details": {} } } ``` ## What Luna does not do - It does not lift a restriction, reinstate an account or ask Meta for a review. That belongs to the account owner. - It does not look the state up at Meta: Meta offers no such lookup. The state Luna returns is the one from the last notice it received. - It does not block your sending because of a restriction. Meta is what refuses, and the refusal arrives as an error on the message. - It charges nothing for these notices. A missing payment method at Meta has its own guide: [Payment at Meta](https://lunahia.com.br/en/docs/payment-at-meta). The events have their full format in [Receive events](https://lunahia.com.br/en/docs/receive-events), and the fields are in the [API reference](https://lunahia.com.br/en/docs/reference). Template **category** and **quality** changes are in [Templates](https://lunahia.com.br/en/docs/templates). ## Route details for this guide The [API reference](https://lunahia.com.br/en/docs/reference) says how to call each route, in a few lines. What explains the reason for each decision, the edge cases and the warnings is here, in the order of the reference. ### GET /v1/numbers/{id}/health limiteDiarioDeConversas is Meta's MESSAGING LIMIT, set for the business portfolio and not for each number: it counts unique people the business writes to outside the customer service window, in the tiers TIER_250, TIER_2K, TIER_10K, TIER_100K and TIER_UNLIMITED. throughputLevel is SPEED, how many messages per second Meta processes. Each transition carries the value in force at that point, and that is how you find out when the limit went up or down. Neither one counts what has already been used. And there is a ceiling that goes up and a ceiling that does not. throughputLevel describes a progression Meta raises on its own as the number builds quality. A number connected through coexistence, which keeps working in the business phone app, has a FIXED ceiling and never enters that progression. What separates the two cases is tetoDeVazaoPorSegundo, right beside it: with a value, it gives the fixed ceiling in messages per second; null, the progression applies to this number. The value comes from what the platform observed in the traffic, and not from the label Meta returned. sincronizacaoDoHistorico tracks the import of the phone previous conversations on a number connected through coexistence, and there are FOUR situations, not three. Null means there is no import for this number. em_curso means it is running, and sincronizacaoPrazo tells you until when: past that instant without finishing, Meta disconnects the end business. concluida means it finished, and the older conversations already show up in GET /v1/messages. recusada means the business owner declined to share on the phone, so it will not finish and asking again changes nothing. Do not read the percentage on its own. sincronizacaoProgresso is a label Meta assigns, and one hundred per cent does NOT mean success: a refusal arrives carrying whatever progress had already been recorded. What tells you the outcome is sincronizacaoDoHistorico, and nothing else. And absence is not zero progress: null means there is no import, zero means one started and has not moved yet. The transitions list carries one entry per CHANGE, not one per check. A number whose rating has never changed since it was connected returns an empty list, and that means it has been stable: do not read an empty list as missing data. What separates the two cases is checkedAt. With a timestamp, the platform asked Meta and found no change. Null, the check has not happened for this number yet. Transitions come newest first. --- # Payment at Meta Fonte: https://lunahia.com.br/en/docs/payment-at-meta Meta charges WhatsApp usage to the business that owns the number, on its payment method. When that method is missing or has a problem, Meta refuses sends with error 131042. Luna marks the number, announces it by event and says what to do. Whoever fixes it is the account owner, at Meta. ## What happens when it is missing Meta refuses the send with error `131042`. The number stays connected and registered, and Luna does not switch it off. None of this is a platform failure: something is missing on the side of the business that owns the account. | What | With the number waiting | | --- | --- | | Free-form message or template | Meta refuses with `131042`. The message becomes `failed`, and the error arrives in `message.status` and in `GET /v1/messages/{id}`. | | Refused message | Luna does not retry it and does not resend it on its own. Your system resends it, once the payment is fixed. | | What Meta sends to the number | Luna delivers it as usual. The wait does not switch off the number or the event subscription on Luna’s side. | | The number’s state | `state` stays `REGISTERED`. What changes is `awaitingPaymentSince`, which now carries the date. | | Luna’s subscription | It does not change. Luna charges for the plan’s number capacity, and a waiting number remains configured capacity. | ## Know before the first failure Since October 1, 2026 Meta delivers each number’s service messages up to the free allowance of 1,000 a month, and, if the business’s WhatsApp account **has no payment method**, stops delivering the following ones. Finding that out through error `131042` means finding out with the agent already silent. So Luna reads the business account’s `primary_funding_id` and `currency`: at connection time and then every hour, within Meta’s call limit. A missing `primary_funding_id` is Meta’s own rule for "the account has no payment method". The result is in `GET /v1/business-accounts` and in each number’s `waba` object (`GET /v1/numbers` and `GET /v1/numbers/{id}`): `paymentMethodOnMeta` is `true`, `false`, or `null` while Luna has not read it yet, and `currency` is the currency Meta reported for the account. With `false`, ask the account owner to register the payment method in Meta’s WhatsApp Manager, as in [How to fix it](#solucao). The console shows the "No payment method at Meta" warning from that field. > `true` means a payment method is linked to the account, not that it is in good standing: a credit line above its limit and a payment account with no currency still cause `131042`. Luna does not see the card, does not see a balance and does not intermediate that payment. The payment is between the business and Meta. **The webhook notice, without waiting for the refusal.** When the read finds the account with no payment method, Luna publishes `number.action_required` for each number of the account, with the `payment_method_missing` reason in the `reasons` list; when the payment method shows up, it publishes `number.action_resolved`. The event goes out within a few minutes of the read, once per transition. It is not `number.payment_required`: that one only goes out when Meta **refuses a send** (`131042`, below). If both things happen, `reasons` carries only `payment_required`, the stronger reason, and you do not get two notices for the same fact. **Check now.** Did your customer say they registered the card? `POST /v1/business-accounts/{id}/payment-method/check` reads from Meta right away, without waiting for the next read (the `id` is the one from `GET /v1/business-accounts`; the key needs the `numbers:read` scope). The response carries `paymentMethodOnMeta`, `currency`, `checkedAt` and `reason`: `checked` (read now), `recent` (the last read is under 60 seconds old and was returned without calling Meta), `busy` (the Meta call budget for this account is at its limit; try again in a few minutes) or `failed` (Meta did not answer; the value is the previous one). The limit exists because these reads come out of the same account call budget the connection uses. The console has the "Check now" button on the "Pagamento na Meta" card and on the number detail. The event goes out the usual way, on the next pass of the notices loop. ## How to detect it Meta has no payment field or webhook, and Luna does not look the state up: the only signal is the error in the response to a send. Luna turns that signal into three things you can read. 1. **The number field.** `awaitingPaymentSince` in `GET /v1/numbers` and in `GET /v1/numbers/{id}` carries the instant of the first refusal, or `null` when there is no wait. 2. **The `number.payment_required` event.** It is sent once, when the number enters the wait, and not for every refused message. See [Receive events](https://lunahia.com.br/en/docs/receive-events). 3. **The error on the message.** Each refused message arrives in `message.status` with `status: "failed"` and `error_code: 131042`, and `GET /v1/messages/{id}` returns the error with the explanation and the `acaoRecomendada`. See [Errors](https://lunahia.com.br/en/docs/errors#envio). The event for entering the wait ```json { "version": "2026-11-10", "event_id": "50a49cee4b216c529e3f7cdd0be525f8902ff6aff66439e004dfe34a0c979fcf", "event_type": "number.payment_required", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "awaiting_payment_since": "2026-10-13T12:00:00.000Z" } } ``` The field on the number ```json { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "metaPhoneNumberId": "123456789012345", "state": "REGISTERED", "ready": true, "awaitingPaymentSince": "2026-10-13T12:00:00.000Z" } ``` The error on the message ```json { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "status": "failed", "erros": [ { "codigo": 131042, "categoria": "estado_de_produto", "mensagem": "Há um problema com o método de pagamento da conta comercial do negócio final na Meta. O número segue configurado; o que falta é do lado do negócio final.", "acaoRecomendada": "O negócio dono da conta de WhatsApp precisa cadastrar ou regularizar o método de pagamento no WhatsApp Manager da Meta (Billing Hub). A Luna não intermedeia esse pagamento e não consulta a situação dele: a Meta não oferece essa consulta. Depois que ele regularizar, envie de novo: a mensagem recusada não é reenviada sozinha, e o número volta ao normal quando um envio for aceito.", "original": { "error": { "code": 131042, "type": "OAuthException", "fbtrace_id": "AbCdEfGhIjK" } } } ] } ``` > `ready` does not take payment into account: it says the number is registered and the subscription is confirmed. A number with `ready: true` can be waiting for payment, and `awaitingPaymentSince` is what says so. ## Causes Meta’s `131042` error covers more than one situation, and Meta does not say which one is your customer’s. The causes it lists: - There is no payment method linked to the business’s WhatsApp account. - The payment account exists, but it is not linked to the WhatsApp account. - The account’s credit line is inactive or above its limit. - The WhatsApp account was deleted or suspended. - The payment account’s time zone or currency is not set. - A request to pay on behalf of another company is pending or was denied. ## How to fix it Whoever fixes it is the business that owns the WhatsApp account, and nobody else: the payment is between it and Meta. Ask your customer to open Meta’s WhatsApp Manager, go to the Billing Hub of their WhatsApp account, and register or fix the payment method, checking the causes above. A text you can send them: Suggested message to the end customer ```text O envio de mensagens do seu WhatsApp foi pausado pela Meta porque a conta não tem um método de pagamento válido. Entre no WhatsApp Manager da Meta, abra o Billing Hub da sua conta de WhatsApp e cadastre ou regularize o cartão ou a forma de pagamento. Avise a gente quando terminar. ``` Once they have fixed it, send again. Messages refused during the wait are not resent on their own: resend the ones that still matter. ## How to know it is back Meta does not announce when payment is fixed, and there is no lookup. The only signal is a send that is accepted again. When that happens, `awaitingPaymentSince` goes back to `null` and Luna publishes `number.payment_resolved`, once. The event for being back to normal ```json { "version": "2026-11-10", "event_id": "6a956161dd17bb975533e63286e811ae62b77b3350107945952b2e53f0a9d1e2", "event_type": "number.payment_resolved", "occurred_at": "2026-10-13T15:30:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841" } } ``` > **Do not count it as fixed before a send goes through.** While `awaitingPaymentSince` has a date, the number is still waiting, even if your customer says they already registered. To test, send a message: if Meta accepts it, the event is sent. If it refuses again, the number stays in the wait and nothing new is published. ## What Luna does not do - It does not charge that payment, does not advance it and does not intermediate it. Luna is a Tech Provider and has no credit line: that line is a requirement for Meta Solution Partners, which is not the case here. - It does not look the payment state up: Meta offers no such lookup. - It does not mark the number as fixed on its own. The mark only goes away when a send is accepted. - It does not resend the refused messages. - It has no credit, top-up or payment route. What Meta charges is in [Meta costs](https://lunahia.com.br/en/docs/meta-costs). The fields and events mentioned are in the [API reference](https://lunahia.com.br/en/docs/reference). --- # Meta costs Fonte: https://lunahia.com.br/en/docs/meta-costs Luna charges only for the number capacity of the plan. WhatsApp usage is charged by Meta, directly to the business that owns the number. This guide summarizes the Meta charging rules in force and what they change for whoever integrates. ## Who charges for what Luna charges only for the capacity of connected numbers in the plan. It never charges by the message sent or received, and no API limit varies with the plan. The technical limits the API applies (requests per minute, webhook endpoints, connection link validity, file size, sends per second) come from `GET /v1/limits`, each with `key`, `label`, `value`, `unit` and `reason`. They are the same for every customer and exist for capacity or because Meta imposes them. It asks for `numbers:read`. Meta charges for WhatsApp usage directly to the business that owns the number, on the payment method registered in that business’s WhatsApp account at Meta. That is why each business needs its own Meta account, with its own payment method. Luna does not intermediate, advance or pass on that payment. ## What Meta charges since October 1, 2026 The rules below were read on Meta’s pricing page on October 7, 2026. The amounts are not here: they vary by message category and by the recipient’s country, and Meta updates them on the first day of each quarter. [Meta’s rate card](https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing) is the reference. Whoever needs to show these rules inside their own product reads `GET /v1/meta-pricing`: the `rules` list (each rule with `key`, `title` and `text`), the day Luna read them in `readAt`, and the addresses of the rate card (`sourceUrl`) and of the AI Providers policy (`aiProvidersUrl`). It carries no monetary values. It asks for `numbers:read`. - **Replies inside the 24-hour window**, which Meta calls service messages: each number has 1,000 free service messages a month, and the balance does not roll over. From the 1,001st on, Meta charges each delivered message. The month turns at midnight, in the messaging account’s time zone. - **A utility template inside an open window** is no longer free. Meta now charges it even with the 24-hour window open. - **A marketing template** is always charged, inside or outside the window. - **A conversation started from a click-to-WhatsApp ad**: replying inside the service window opens a free period of up to 7 days, for marketing, utility, authentication and service. - **Authentication and utility** have volume tiers: the rate of the next tier is lower. Meta does the counting, across the whole business portfolio, and it restarts every month. > **Without a payment method, replies stop.** If the business’s WhatsApp account has no payment method at Meta, Meta delivers service messages while the month’s free allowance lasts, and after that stops delivering them. Ask the business to register a payment method in Meta’s Billing Hub before that happens. For whoever integrates, the practical consequence is to plan the first send and high-volume replies with the payment method already registered. The 24-hour window still decides whether a free-form message can go out: see [Send messages](https://lunahia.com.br/en/docs/send-messages). ## General-purpose AI assistants Meta calls general-purpose AI assistants AI Providers, and treats them under a policy of its own. The service-message rule above does not apply to them. Read [Meta’s policy for AI Providers](https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ai-providers) before deciding whether your product falls under it. When Meta classifies a sent message under that charge, its `pricing.category` arrives as `general_purpose_ai`, in `GET /v1/messages/{id}`, in `GET /v1/messages` and in the `message.status` event, and the console shows the label "General-purpose AI". It is the AI Provider charge, which Meta makes to the business that owns the account, per service message, and it applies to Brazil. Luna only displays the classification: it does not add it up, does not convert it into an amount and charges nothing on it. A business’s support agent, answering about the business’s own service, pays as an ordinary service message; the `general_purpose_ai` category shows up when the main product is a general-purpose assistant. ## How to check what Meta charged Luna returns the cost classification Meta applied to each sent message, with Meta’s names, and does not return a price. The `pricing` object comes in `GET /v1/messages/{id}` and in the `message.status` event, with `billable`, `pricing_model`, `type` and `category`. Meta reports it only on `sent` and on one of `delivered` and `read`: until it does, the field is null. Meta is going to discontinue `billable`, so read `type` and `category` together. The values are Meta’s and can gain new ones: do not treat them as a closed list. What Luna returns is what helps predict the category. The template’s category comes in the `category` field of `GET /v1/templates`. The state of each contact’s service window comes in `GET /v1/conversations`, in the `windowOpen`, `windowExpiresAt` and `windowSource` fields. Both are in the [API reference](https://lunahia.com.br/en/docs/reference). To see the usage Meta measures for a number in the period, use `GET /v1/usage?numberId=`. Luna reads Meta’s `pricing_analytics` with the business’s token and passes the points through as Meta reports them: pricing category and type, the tier, the country, the volume and the approximate cost, in the currency of the business’s account at Meta. Each point comes from a single number and carries `numberId`, `phoneNumberId` and `currency`, the currency of its account; the response has no total, and `notice` carries the warning that the value is an approximation and that Meta charges the business directly. Each read spends one unit of Meta’s management limit, so the read of each number is kept for five minutes (`readAt` says when the read is from). None of this goes into the Luna subscription. To pass usage on to one of your customers, send `externalId` instead of `numberId` (exactly one of the two; both, or neither, answer `400` with `campos`): `GET /v1/usage?externalId=cliente-42&start=2026-11-01&end=2026-12-01&granularity=MONTHLY`. Luna reads each number of that customer and returns the points of all of them in `data`, each with its own `numberId` and `currency`. A customer with accounts in different currencies gets points in different currencies, and Luna **never adds currencies**: group by `numberId` and `currency` on your side. `numbers` lists the numbers covered, including the ones that had no point and the ones left out (`read: false`, with `reason`: `number_disconnected` or `phone_not_read_yet`). `granularity` is `DAILY` (the default), `MONTHLY` or `HALF_HOUR`, and Meta limits the period of each. With `format=csv` the response comes as `text/csv`, one line per point, for your finance team’s spreadsheet; the approximation notice goes in the `X-Luna-Notice` header. It is still display only: none of this goes into the Luna subscription. The `pricing` is for you to display, it is not the invoice. To see what Meta actually charged, check the Billing Hub of the business’s WhatsApp account, and the invoice Meta issues to it. That is where the amount shows up. Luna does not compute money amounts, does not add them up and does not charge on them. --- # Coming from Z-API or the Evolution API Fonte: https://lunahia.com.br/en/docs/migrate-from-unofficial-api Z-API and the Evolution API connect a number the way a handset does; Luna talks only to Meta’s official WhatsApp Cloud API. This guide translates what you did there into what you do here: how to authenticate, send, receive, and what each state and event becomes. It ends with the list of what does not exist on the official API, so you do not look for what is not here. The [API reference](https://lunahia.com.br/en/docs/reference) carries each route’s contract. Before the tables, read [the model difference](https://lunahia.com.br/en/migrate-from-evolution-api): the 24-hour window, the `202` with no `wamid` and the absence of a QR code are what breaks a migration halfway. The Z-API and Evolution columns describe, in our own words, what each one’s public documentation shows. ## What changes before you touch the code - **An instance becomes a number.** Instead of creating an instance and reading a QR code, you send your customer a connect link (`POST /v1/onboarding/links`) and the number’s owner signs in with their own Meta account. The number stays in your customer’s account, and that is what avoids a session ban. See [Connect a number](https://lunahia.com.br/en/docs/connect-a-number). - **Free-form text only within 24 hours.** Once the contact stops writing for 24 hours, the path is an approved template. Luna refuses text outside the window with `409 window_closed` before spending the call. See [the window](https://lunahia.com.br/en/docs/send-messages#janela). - **Sending answers `202`.** The response carries Luna’s `id` and `status: "queued"`. The `wamid` and the delivery state arrive later, in the `message.status` event. The states are in [The message states](https://lunahia.com.br/en/docs/send-messages#estados). - **Brazilian mobiles only.** `to` is the phone with country and area code, digits only, starting with `55`. Any other format answers `400` with `campos: [{campo: "to"}]`, except for someone who already wrote to your number. The ninth digit is not a problem: Luna finds the conversation with and without it, and the text goes to the `wa_id` Meta used. Someone who never wrote gets the phone as you wrote it. - **The queue has a pace.** For the same contact, 30 messages go out at once and then one every 7 seconds. You do not configure this, and the limit never comes back as a `429`. There is no way to cancel a message already in the queue, or to estimate when it goes out. - **A template is not silently refused later.** A template Luna knows that is not `APPROVED` answers `409 template_not_approved`, and a missing or extra variable answers `400` with `campos`. A number that cannot send right now (`connection.canSend: false` in `GET /v1/numbers`) still accepts the request with `202` and the failure arrives in `message.status`: read `canSend` before sending. ## Authenticate and send | What you did | Z-API | Evolution API | Luna | | --- | --- | --- | --- | | Authenticate | The instance identifier and a token, plus an account security token. | A key for the deployment. | `Authorization: Bearer hlsn_...` with scopes. One key per customer, with `externalId`. | | Create a customer’s instance | Create an instance through the partner. | Create an instance. | A connect link per customer: `POST /v1/onboarding/links`. | | Send text | A call with the phone and the message; it returns two identifiers at once. | A per-instance call with the number and the text. | `POST /v1/messages` with `from`, `to` and `text.body`. It returns `id` and `status: "queued"`; the `wamid` comes later. | | Pause between messages | A per-message delay, from 1 to 15 seconds. | A per-message delay. | Automatic queue: a burst of 30, then one every 7 seconds per contact. | | Show “typing” | A typing delay on the send. | A presence call. | `POST /v1/messages/{id}/typing`, with the `id` of the **received** message. It also marks it as read and goes away in about 25 seconds. | | Send media | The URL or the file in base64 in the send itself. | The file in the send itself. | `POST /v1/numbers/{id}/media` and then `image.id`, or `image.link` with a public URL. Two steps, because Meta works with a media identifier. | | Buttons and list | Action buttons and an option list. | Send buttons and send list. | `interactive.type`: `button`, `list` or `cta_url`. The answer comes back in `message.interactive.id`, in the `message.received` event. | | Reaction | Send a reaction. | Send a reaction. | `type: "reaction"`, with `reaction.message_id` (the `wamid`) and `reaction.emoji`. | | Reply with a quote | Reply to a message. | A quote field on the send. | `context.message_id`, with Luna’s `id` or the `wamid`. | | Mark as read | Read messages. | Mark message as read. | `POST /v1/messages/{id}/read`, one message at a time. | | Delete the instance | Delete the instance. | Delete the instance. | `DELETE /v1/numbers/{id}`. It frees the slot on Luna and does not take the number down at Meta. | The phone goes as the customer wrote it, with or without the ninth digit. The minimum body of a text send: ```json { "from": "YOUR_PHONE_NUMBER_ID", "to": "5531990009991", "text": { "body": "Olá! Sua consulta está confirmada." } } ``` Fields that belong to the type go inside the type’s object, not at the top of the body: `image.caption`, `location.latitude`. An unknown field answers `400` naming it. Always send the `Idempotency-Key`: see [Idempotency](https://lunahia.com.br/en/docs/send-messages#idempotencia). ## Events and states On Luna there is one webhook endpoint for the whole account, or one per customer with `externalIds`. Every event carries the `number` object, with the `external_id` of the customer who owns the number, so a single endpoint serves all your customers. Delivery is signed and may repeat: deduplicate by `event_id`. See [Receive events](https://lunahia.com.br/en/docs/receive-events). ### Webhook per number (like the “instance”) There each instance had its own webhook URL. Here the number is the instance and the endpoint accepts `phoneNumberIds`: it receives only the events of those numbers (Luna’s UUID, the `id` from `GET /v1/numbers`, or the `metaPhoneNumberId`). ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/webhooks/numero-1", "phoneNumberIds": [ "YOUR_PHONE_NUMBER_ID" ] }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "url": "https://example.com/webhooks/numero-1", "phoneNumberIds": [ "YOUR_PHONE_NUMBER_ID" ] }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.post( "https://api.lunahia.com.br/v1/webhooks/endpoints", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "url": "https://example.com/webhooks/numero-1", "phoneNumberIds": [ "YOUR_PHONE_NUMBER_ID", ], }, timeout=10, ) print(res.status_code, res.json()) ``` To change the URL of just that number, use `PATCH /v1/webhooks/endpoints/{id}` with the new `url`. For numbers that are still to be connected, register the endpoint with `externalIds` (the `externalId` you give the customer): it receives from every number with that `externalId`, including the ones connected later. Details in the “Webhook per number” section of [Receive events](https://lunahia.com.br/en/docs/receive-events). ```bash curl -X PATCH "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/webhooks/numero-1-novo" }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "url": "https://example.com/webhooks/numero-1-novo" }), }); console.log(res.status, await res.json()); ``` ```python import os import requests res = requests.patch( "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ENDPOINT_ID", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", }, json={ "url": "https://example.com/webhooks/numero-1-novo", }, timeout=10, ) print(res.status_code, res.json()) ``` | What you listened to | Z-API | Evolution API | Luna | | --- | --- | --- | --- | | Message received | The “on receive” webhook. | `MESSAGES_UPSERT` | `message.received` | | A message the owner sent from the phone | “On receive”, including the ones sent by me. | `SEND_MESSAGE` | `message.echo`, only on a number in coexistence. | | Message state | A status webhook, with the send, receipt, read and played states. | `MESSAGES_UPDATE` | `message.status`: `sent`, `delivered`, `read`, `played` and `failed`. Meta does not send `delivered` when delivery and reading coincide. | | Connected | The “on connect” webhook. | `QRCODE_UPDATED` and `CONNECTION_UPDATE`. | `onboarding.link.completed` when the customer finishes the link, and `number.connected` when the number is ready. | | Disconnected | The “on disconnect” webhook. | `CONNECTION_UPDATE` | `number.disconnected`, `number.action_required` and `number.credential_expiring`. The state is in `connection` of `GET /v1/numbers/{id}`. | | Template approval | - | - | `template.status` | > **`number.disconnected` does not always mean `disconnected`.** When the customer removes the app, the number goes to `connection.status: "action_required"` with the reason `credential_invalid`, and reconnects through the link. Only `DELETE /v1/numbers/{id}` leaves `disconnected`. See [Disconnected number](https://lunahia.com.br/en/docs/account-health#desconectado). There is no incoming-call event, and no setting to reject calls. If your agent depends on one of them, handle it on your side. Automatic reading exists: turn on `autoRead` on the number, with `PATCH /v1/numbers/{id}`, and Luna marks every message the number receives as read, with no typing indicator. To mark only the ones you process, leave `autoRead` off and use `POST /v1/messages/{id}/read`. ## What does not exist on the official API These are not Luna gaps: they are features of whoever connects a number as a handset. Each row says what to do instead. | What existed there | Here | | --- | --- | | QR code and pairing code | There is no QR code. The connection is through the connect link, and the number’s owner signs in with their own Meta account. That is what prevents a ban. | | Check whether a number has WhatsApp before sending | The official API does not answer that. Send normally: if the number has no WhatsApp, a `message.status` with `failed` and code 131026 arrives, and repeating the send does not change the result. | | Address book, photo and status of whoever writes, chat list | A business number has no address book or chat list. Keep the contacts in your own database from `message.received` (`wa_id` and `profile_name`). | | Old messages from the handset | Luna only has what went through it after the connection. On a number in coexistence, Meta imports the history within a deadline: see [Connect a number](https://lunahia.com.br/en/docs/connect-a-number#coexistencia). | | Status and stories | The official API neither posts nor answers status. | | Polls, events and pinning a message | Use buttons or a list, which the contact answers and which comes back in `message.received`, in `message.interactive`. | | Edit, delete and forward a sent message | Meta’s messages API does not offer these operations to the business. Correct it by sending another message; `context.message_id` quotes the original. | | Business app labels and notes | A label belongs to the phone app and does not exist on the API. Mark the conversation in your own system, by `conversationId` or by `wa_id`. | | Contact presence: online, “typing”, last seen | Meta does not deliver the contact’s presence. Your agent’s “typing” goes out through `POST /v1/messages/{id}/typing`. | | Account privacy and blocking a contact | Blocking exists, in `POST /v1/numbers/{id}/blocked-users`. The rest of the privacy settings belong to the app. | | Broadcast lists, channels, communities | The official API has none. To reach many people, use a template, and respect the quality limit and the contact’s marketing preference (`contact.preferences_changed`). | | Groups | Ordinary WhatsApp groups do not exist on the official API. Meta has a groups API of its own, with limits and requirements, which Luna does not expose yet. | | Per-instance proxy, dedicated IP, unbanning | There is no session to protect: the number is registered at Meta, and the risk is quality, not IP. See `GET /v1/numbers/{id}/health` and [Account health](https://lunahia.com.br/en/docs/account-health). | | Free-form text at any time | Outside 24 hours, only a template. It is Meta’s rule, and Luna applies it before spending the call (`409 window_closed`). | | MP3 audio as a voice message | Meta requires OGG with OPUS and Luna does not convert. Convert before: `ffmpeg -i entrada.mp3 -c:a libopus -b:a 32k -ar 48000 -ac 1 saida.ogg`. | ## Where to start 1. Create the account and a key per customer: [Account and keys](https://lunahia.com.br/en/docs/account-and-keys). 2. Replace instance creation with the connect link: [SaaS with N customers](https://lunahia.com.br/en/docs/saas-with-n-customers). 3. Register the webhook and swap your event handling using the table above: [Receive events](https://lunahia.com.br/en/docs/receive-events). 4. Test sending without going to Meta, with the test key: [Test mode](https://lunahia.com.br/en/docs/test-mode). > Helsen charges for your plan’s active-number capacity, and for nothing beyond that. WhatsApp platform usage is charged by Meta, to your end customer, on their payment method. Z-API and the Evolution API are third-party projects, unaffiliated with Helsen; this guide describes each platform’s model for those migrating and is not a commercial comparison. --- # Coming from Twilio Fonte: https://lunahia.com.br/en/docs/migrate-from-twilio Twilio and Luna both deliver messages through Meta’s WhatsApp Cloud API, but with different contracts: here sending is asynchronous, the 24-hour window is enforced by the API, and there is a single webhook, signed another way. This guide maps what you use, so you can swap the code without relearning the product. The [API reference](https://lunahia.com.br/en/docs/reference) carries each route’s contract. The Twilio column describes, in our own words, what its public documentation shows; if something changed there, its documentation holds. ## What changes before you touch the code - **The number belongs to your customer, in their own Meta account.** There is no subaccount: your product’s customer is the `externalId` of a key, a connect link and an endpoint. See [SaaS with N customers](https://lunahia.com.br/en/docs/saas-with-n-customers). - **Sending answers `202`.** Luna’s `id` comes back at once with `status: "queued"`, and the `wamid` and the delivery state arrive in `message.status`. See [The message states](https://lunahia.com.br/en/docs/send-messages#estados). - **Outside the 24-hour window the refusal is immediate.** Free-form text to someone who did not write in the last 24 hours answers `409 window_closed` in the call itself, with `fechadaEm` and `acaoRecomendada`. You do not find out later, from an error code. Templates and reactions pass. - **An invalid template is also refused at once, when Luna knows it.** `409 template_not_approved` if the state is not `APPROVED`, and `400` with `campos` if a variable is missing, an extra one comes in, or the authentication code goes over 15 characters. A template created directly in Meta’s panel is not in Luna’s catalog and passes: Meta decides. - **Brazilian recipients only.** `to` starts with `55`. Any other format answers `400` with `campos: [{campo: "to"}]`, except for someone who already wrote to your number. ## Mapping what you use | Twilio | Luna | | --- | --- | | Create a message in the messages API | `POST /v1/messages` | | Origin in the `whatsapp:+5531...` format | `from`: the number’s UUID (`GET /v1/numbers`) or the `metaPhoneNumberId`. | | Destination in the `whatsapp:+5511900000001` format | `to: "5511900000001"`: digits only, no `+` and no prefix. | | Text body | `text.body`, up to 4096 characters. | | A content identifier and numbered variables `{"1":"Ana"}` | `type: "template"`, with `template.name`, `template.language.code` and `template.components[].parameters`. The variable is named, with `parameter_name`. | | Content builder and approval request | `POST /v1/templates`: the body neither starts nor ends with a variable, and each variable needs an example. Approval arrives in the `template.status` event. See [Templates](https://lunahia.com.br/en/docs/templates). | | Status callback of each message | One endpoint (`POST /v1/webhooks/endpoints`) receives the `message.status` event for every message. | | States `queued`, `sent`, `delivered`, `read`, `failed`, `undelivered` | `queued` (only in the `202`), `accepted`, `sent`, `delivered`, `read`, `played` and `failed`. There is no `undelivered`: a failure is `failed`. See [The message states](https://lunahia.com.br/en/docs/send-messages#estados). | | The message’s error code | `error_code` in the `message.status` event (Meta’s code, 131xxx) and, in `GET /v1/messages/{id}`, `erros[]` with `codigo`, `categoria`, `mensagem` and `acaoRecomendada`. | | Received message: text, sender, WhatsApp identifier, button payload | `message.received` event: `message.text`, `wa_id`, `message.button.payload` and `message.interactive`. | | Send idempotency key | `Idempotency-Key` header, 1 to 255 visible characters. The same key and body return the same `id`; a different body answers `409 idempotency_key_reused`. See [Idempotency](https://lunahia.com.br/en/docs/send-messages#idempotencia). | | Account SID and token, or an API key | `Authorization: Bearer hlsn_...`, with scopes (`messages:write`, `messages:read`, `templates:read`...). See [Account and keys](https://lunahia.com.br/en/docs/account-and-keys). | | Subaccount per customer | A key with `externalId`, a connect link and an endpoint with `externalIds`. | | List messages by recipient, date and page size | `GET /v1/messages` with `waId` (a Brazilian mobile matches with and without the ninth digit), `since`, `until` and `limit` from 1 to 100. For the next page, send `nextCursor` in `cursor`. An unknown parameter answers `400`. | | See the text and variables of what was sent | `content` of `GET /v1/messages`: in `template`, the `name`, the `language` and the `variables`. | | Sandbox with `join` | A key with `mode: "test"`: the send does not go to Meta and your webhook receives the simulated states. See [Test mode](https://lunahia.com.br/en/docs/test-mode). | ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511900000001", "type": "template", "template": { "name": "lembrete_consulta", "language": { "code": "pt_BR" }, "components": [ { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana" }, { "type": "text", "parameter_name": "medico", "text": "Dra. Lima" } ] } ] } }' ``` ```js const res = await fetch('https://api.lunahia.com.br/v1/messages', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LUNA_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID(), }, body: JSON.stringify({ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511900000001", "type": "template", "template": { "name": "lembrete_consulta", "language": { "code": "pt_BR" }, "components": [ { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana" }, { "type": "text", "parameter_name": "medico", "text": "Dra. Lima" } ] } ] } }), }); console.log(res.status, await res.json()); ``` ```python import os import uuid import requests res = requests.post( "https://api.lunahia.com.br/v1/messages", headers={ "Authorization": f"Bearer {os.environ['LUNA_API_KEY']}", "Idempotency-Key": str(uuid.uuid4()), }, json={ "from": "YOUR_PHONE_NUMBER_ID", "to": "5511900000001", "type": "template", "template": { "name": "lembrete_consulta", "language": { "code": "pt_BR", }, "components": [ { "type": "body", "parameters": [ { "type": "text", "parameter_name": "nome", "text": "Ana", }, { "type": "text", "parameter_name": "medico", "text": "Dra. Lima", }, ], }, ], }, }, timeout=10, ) print(res.status_code, res.json()) ``` ## The webhook signature Twilio signs the URL plus the form parameters. Luna signs the **raw body**: the `X-Luna-Signature` header carries `t=...,v1=...`, and `v1` is the HMAC-SHA256 of the text `t` + `.` + raw body, with the endpoint’s secret (`whsec_...`) as the key. Refuse a delivery whose `t` is more than 300 seconds from your clock. During secret rotation the header carries two `v1` values, and one matching is enough. - Do not re-serialize the JSON before checking: use the exact bytes that arrived. The verification code, in Node and Python, is in [Verify the signature](https://lunahia.com.br/en/docs/receive-events#assinatura). - Answer `2xx` to accept and `401` to an invalid signature. Only `2xx` counts as delivered, and a delivery may repeat: deduplicate by `event_id`. - The TypeScript SDK has `lerEvento`, which checks the signature and returns the typed event. See [SDK and n8n](https://lunahia.com.br/en/docs/sdk-and-n8n). ## Error codes On Twilio, the error code comes in the callback or on the debugger page. On Luna there are two moments: the immediate refusal, which is an HTTP status with a stable `error`, and the failure Meta reports later, in `message.status`. | On Twilio | On Luna | | --- | --- | | 21211, invalid destination | `400` with `campos: [{campo: "to"}]`, at once. | | 63016, outside the reply window | `409 window_closed`, at once and before going to Meta. Send a template. | | Invalid template content or variables | `409 template_not_approved` or `400` with `campos`, at once, when Luna knows the template. | | Number without WhatsApp, payment, account restriction and the other Meta codes | `message.status` with `failed` and `error_code` (131026, 131042...), and the full `erros[]` in `GET /v1/messages/{id}`. The `acaoRecomendada` says what to do. See [Errors](https://lunahia.com.br/en/docs/errors#envio). | ## What does not exist here | On Twilio | On Luna | | --- | --- | | Code verification over WhatsApp, SMS, voice and e-mail | Luna delivers Meta’s authentication template. Generating, storing, expiring and checking the code is up to your system, and the other channels stay with your provider. The send body is in [Authentication template](https://lunahia.com.br/en/docs/templates#autenticacao). | | Automatic fallback to SMS | Luna sends only over WhatsApp. If you need SMS as a backup, listen for `message.status` with `failed` and send the SMS through your SMS provider. | | Knowing whether a number has WhatsApp before sending | The official API does not answer that. Treat code 131026 as “number without WhatsApp” and stop retrying that number. | | Sender pool and messaging service | Each Meta number is independent, and `from` is one number. Choosing the sender is your code’s decision. | | Batch sending, scheduling and send validity | One `POST /v1/messages` per recipient, with `Idempotency-Key`. There is no scheduled send: your job picks the time. The limits are in `GET /v1/limits`. | | Delete or anonymize a message | There is no route to delete a message. To request data deletion, see the privacy policy. | | List of who asked to stop | Meta reports the marketing preference in `contact.preferences_changed`. Keeping the list and honoring it before sending is up to your system. | | Visual flows and conversations with timers | Luna delivers the messaging; the logic is yours. For no-code flows, there is the n8n node in [SDK and n8n](https://lunahia.com.br/en/docs/sdk-and-n8n). | > Helsen charges for your plan’s active-number capacity, and for nothing beyond that. WhatsApp platform usage is charged by Meta, to your end customer, on their payment method. Twilio is an independent company, unaffiliated with Helsen; this guide describes each platform’s model for those migrating and is not a commercial comparison. --- # Coming from another official partner (360dialog, Gupshup) Fonte: https://lunahia.com.br/en/docs/migrate-from-another-partner If you already run customers through another official partner, the model is familiar: the business owns the WhatsApp Business account, the number is on Meta’s Cloud API, and you connect a customer through a Meta flow. What changes are the names of things, the webhook and how Meta gets paid. This guide maps them and says what to do with a number that is already at the other partner. The [API reference](https://lunahia.com.br/en/docs/reference) carries each route’s contract. The other partners’ columns describe, in our own words, what each one’s public documentation shows; if something changed there, their documentation holds. ## What changes and what stays the same - **Stays the same:** your customer keeps owning the WhatsApp Business account (the WABA) and their own payment method at Meta. Luna owns none of that. - **How Meta gets paid changes.** Luna is a Tech Provider and has no line of credit with Meta, so there is no wallet, balance or top-up. Each business pays Meta directly, and Luna only **shows** each number’s usage in `GET /v1/usage`. You pass that value on to your customer however you see fit, outside Luna. - **There is no “client” or “app” object.** Your customer is the `externalId`, a label you put on the key, the connect link and the endpoint, and which comes back in every event. The instance is the number. - **The webhook changes.** One endpoint for the whole account (or one per customer with `externalIds`), signed delivery, order preserved within each conversation and an `event_id` to deduplicate. There are no custom headers on the call: the delivery’s authentication is the signature. See [Receive events](https://lunahia.com.br/en/docs/receive-events). ## Mapping by partner ### If you come from 360dialog | 360dialog | Luna | | --- | --- | | A key header, one key per channel | `Authorization: Bearer hlsn_...`. One key per customer, with `externalId` and `profile: "agent"`. | | Send a message | `POST /v1/messages`: asynchronous `202` and `Idempotency-Key`. | | Register the webhook URL per channel, with headers | `POST /v1/webhooks/endpoints` with `url`, `eventTypes` and `externalIds`. No custom headers; the signature is `X-Luna-Signature`. | | List clients | There is no “client” object: the `externalId` is your customer. | | List channels | `GET /v1/numbers`, with the `externalId`, `state` and `canSend` filters. | | Create a channel’s key | `POST /v1/api-keys` with `externalId`. | | Integration address and a redirect with the client and channels | `POST /v1/onboarding/links` with `redirectUrl`, which receives `status` and `numberId` in the query. The link is valid for 72 hours. See [Connect a number](https://lunahia.com.br/en/docs/connect-a-number). | | Channel created event | `onboarding.link.completed` | | Channel running event | `number.connected` | | Number quality event | `number.quality_changed` | | Health state: available, limited, blocked | `connection.status` and `connection.reasons` in `GET /v1/numbers/{id}`, and `GET /v1/numbers/{id}/health`. See [Account health](https://lunahia.com.br/en/docs/account-health). | | List, create and delete templates | `GET /v1/templates?wabaId=`, `POST /v1/templates` and `DELETE /v1/templates/{id}`. See [Templates](https://lunahia.com.br/en/docs/templates). | | Replicate a template to another customer | There is none. Create the template in each WABA with `POST /v1/templates`. `GET /v1/templates/{id}` returns the content and the `wabaId`, which helps copy by hand. | | Client balance | `GET /v1/usage?numberId=`, for display only. There is no balance or top-up. | | Channel limit | `GET /v1/subscription`: `capacity` and `capacityLeft`. See [Plan and numbers](https://lunahia.com.br/en/docs/plan-and-numbers). | | Channel cancellation request | `DELETE /v1/numbers/{id}`, which triggers `number.disconnected`. It does not deregister the number at Meta. | ### If you come from Gupshup | Gupshup | Luna | | --- | --- | | Create an app per customer | There is no app: the instance is the number. Create a connect link with `POST /v1/onboarding/links`. | | Signed embed link | The connect link: a `url` with a token, valid for 72 hours. | | Callback subscriptions per app | `POST /v1/webhooks/endpoints`. | | Templates per app | `/v1/templates`, per WABA. | | Wallet and balance | It does not exist, by design: each business pays Meta directly. `GET /v1/usage` only shows usage. | | Daily usage per app | `GET /v1/usage`, per number. | | Business profile and display name | `GET` and `PATCH /v1/numbers/{id}/profile`, without the display name. The business sees and requests that name in Meta’s WhatsApp Manager. See [Business profile](https://lunahia.com.br/en/docs/number-on-meta#perfil). | ## What changes in the webhook - **Signature.** Each delivery carries `X-Luna-Signature: t=...,v1=...`, the HMAC-SHA256 of `t` + `.` + raw body. See [Verify the signature](https://lunahia.com.br/en/docs/receive-events#assinatura). - **Order and repeats.** Order holds within a conversation, and a delivery may repeat. Deduplicate by the stable `event_id`. - **Which account and which customer.** Connection and template events carry the `waba_id`, and every event carries the `number` object with your customer’s `external_id`. You do not need to cross lists to know whose event it is. - **Abandoned link.** A customer who closes Meta’s window leaves the link `open`, with `lastFailure` and `reason: "abandoned"`. The `onboarding.link.failed` event arrives later. ## Moving a number that is already at the other partner 1. The business must own the WhatsApp Business account and have the number released at the previous partner. The prerequisites and the two-step verification PIN are in [A number coming from another provider](https://lunahia.com.br/en/docs/connect-a-number#outro-provedor). 2. Send the connect link (`POST /v1/onboarding/links`). If the number goes to `PIN_REQUIRED`, give the PIN in `POST /v1/numbers/{id}/pin`. A wrong PIN spends one of the registration attempts Meta grants. 3. Wait for the `number.connected` event and check `connection.canSend` in `GET /v1/numbers/{id}`. Only then switch the number off at the previous partner, so you are not left without a channel in the gap. 4. Switch your system’s webhook: the events and the signature are different, as in the table above. > **What has not been confirmed in practice:** templates belong to the WABA and not to the partner, but Helsen has not yet tested connecting a WABA that already has approved templates. After connecting, list `GET /v1/templates?wabaId=` and check what Luna knows. A template it does not know is accepted on send and Meta decides. ## Capacity and links Luna’s plan defines how many numbers you keep active. The connect link **does not reserve a slot**: if you send more links than there are slots, the last customers are left with the number "connecting" until a slot is free. Before handing over each link, check the slots, as [Plan and numbers](https://lunahia.com.br/en/docs/plan-and-numbers) explains. > Helsen charges for your plan’s active-number capacity, and for nothing beyond that. WhatsApp platform usage is charged by Meta, to your end customer, on their payment method. 360dialog and Gupshup are independent companies, unaffiliated with Helsen; this guide describes each platform’s model for those migrating and is not a commercial comparison. --- # Glossary Fonte: https://lunahia.com.br/en/docs/glossary The terms the documentation uses all the time, explained in one paragraph each, with the guide where the subject is covered in full. Each route’s contract is in the [API reference](https://lunahia.com.br/en/docs/reference). ## 24-hour window The period in which you can send a free-form message (text, image, buttons) to a contact: 24 hours after the **last message they sent** to your number. The contact opens the window, by writing; sending a template does not open it. With the window closed, only a [template](#template) goes out, and sending free-form text answers `409` with `error: "window_closed"`. More in [Send messages](https://lunahia.com.br/en/docs/send-messages#janela). ## Template A message model that Meta approves before use. It is the only way to start a conversation, or to talk to someone outside the [24-hour window](#janela). Its state (`PENDING`, `APPROVED`, `REJECTED`...) comes from Meta, and only `APPROVED` sends. More in [Templates](https://lunahia.com.br/en/docs/templates). ## Idempotency The property of a call that, repeated, produces the same result as once. On Luna, you send the `Idempotency-Key` header with a value of yours in `POST /v1/messages`: if the call is repeated (after a timeout, for example), Luna returns the original message instead of sending a second one. More in [Send messages](https://lunahia.com.br/en/docs/send-messages#idempotencia) and, for agents, in [AI agent](https://lunahia.com.br/en/docs/ai-agent#idempotencia). ## BSUID The user identifier that Meta gives each person, and which does not depend on the phone. Some people write without showing their phone number, and in that case the event arrives with a null `wa_id` and with the BSUID in `user_id`. To reply, use `recipient` with that value, in place of `to`. More in [Users without a phone number](https://lunahia.com.br/en/docs/users-without-phone). ## Webhook An HTTPS address of yours that Luna calls (a `POST`) every time something happens: a message arrived, a message changed state, a number connected. It is how your system finds out without having to ask all the time. More in [Receive events](https://lunahia.com.br/en/docs/receive-events). ## Signature The stamp Luna puts on every webhook delivery, in the `X-Luna-Signature` header, which proves the event came from it and was not changed. You redo the calculation with your secret and check. More in [Receive events](https://lunahia.com.br/en/docs/receive-events#assinatura). ## wamid The identifier of a message **at Meta**. It arrives after the send, over the webhook. The `id` the `202` returns is a different one: it is the message’s at Luna, and it is the one Luna’s routes ask for. More in [Send messages](https://lunahia.com.br/en/docs/send-messages#basico). ## externalId The label you give one of your customers (1 to 128 characters, free text). It is born on the connect link, goes to the number and comes back in that number’s events, so your system knows which customer each belongs to. Luna never interprets it. More in [SaaS with N customers](https://lunahia.com.br/en/docs/saas-with-n-customers). ## event_id The identifier of a webhook event. It is stable: the same delivery, repeated, carries the same `event_id`, and it is with it that your code drops what it has already handled. As delivery is at least once, repeats happen. More in [Receive events](https://lunahia.com.br/en/docs/receive-events#garantias). ## Raw body The exact bytes your server received in the `POST`, before any reading of the JSON. The signature is calculated over them: if you open the JSON and build it again, the key order or the spaces can change and the check fails. Take the raw body from your library before parsing it. More in [Receive events](https://lunahia.com.br/en/docs/receive-events#assinatura). --- # API reference Fonte: https://lunahia.com.br/en/docs/reference ## Messages Send messages and read what came in and went out. Sending is asynchronous: the answer is 202 and delivery happens at the pace Meta allows. ### List messages `GET /v1/messages` The record of what came in and what went out, newest first. Each message carries the number, the customer label, the conversation and, when it failed, the error summary. Filters: phoneNumberId, externalId, conversationId, waId, userId, wamid, direction, status, since and until. A parameter the route does not know answers 400. format=csv answers text/csv, with the same filters. Authentication: API key. Required scope: `messages:read` Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-get-v1-messages #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `limit` | `integer` | no | Quantas mensagens trazer. Padrão 50, máximo 100. Com format=csv o padrão e o máximo são 1000. Mais que 100 sem format=csv responde 400. | | `format` | `string` | no | json (o padrão) ou csv. O csv vem em text/csv, uma linha por mensagem, com os mesmos filtros e a mesma ordem; a próxima página vem no cabeçalho X-Luna-Next-Cursor (ausente na última) e vai em cursor. Colunas: id, direction, wamid, type, bodyText, status, waId, userId, displayNumber, numberId, externalId, conversationId, errorCode, errorMessage, createdAt. | | `phoneNumberId` | `string` | no | O número: o UUID da Luna (o id de GET /v1/numbers) ou o id da Meta (metaPhoneNumberId). Os dois valem. | | `externalId` | `string` | no | O rótulo que você deu ao seu cliente (externalId): só as mensagens dos números dele. Igualdade exata; um rótulo sem número devolve lista vazia. | | `conversationId` | `string` | no | | | `waId` | `string` | no | O telefone do interlocutor (waId), só com dígitos: só as mensagens da conversa dele. Igualdade exata, e o celular do Brasil vale com e sem o nono dígito; um waId sem conversa devolve lista vazia. | | `userId` | `string` | no | O BSUID do interlocutor (userId), o identificador do usuário que não depende do telefone: só as mensagens da conversa dele. Igualdade exata; um userId sem conversa devolve lista vazia. | | `direction` | `string` | no | inbound: só o que chegou. outbound: só o que você enviou. | | `status` | `string` | no | O status da mensagem, como a Meta o informa e como o campo status o devolve (por exemplo sent, delivered, read, failed). Igualdade exata, e um valor que nenhuma mensagem tem devolve lista vazia. Vale só para mensagem enviada, que é a que tem status. | | `since` | `any` | no | Só as mensagens criadas neste instante ou depois (ISO 8601: 2026-11-03T00:00:00.000Z, 2026-11-03T00:00:00-03:00, ou a data 2026-11-03, que vale meia-noite UTC). | | `until` | `any` | no | Só as mensagens criadas antes deste instante (ISO 8601, nas mesmas formas de since). Junto de since, forma a janela [since, until). | | `wamid` | `string` | no | O identificador da mensagem na Meta, o mesmo que os eventos de webhook trazem em wamid. Devolve só a mensagem com esse wamid, e a lista vem vazia quando ele não é seu ou não existe. | | `cursor` | `string` | no | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "direction": "outbound", "wamid": "wamid.HBgMNTUzMTgwMzYwMjEwFQIAERgSQjczNEE1OEVDMDgyMTJCMjA2AA==", "type": "text", "bodyText": "Olá! Recebemos seu pedido e já estamos preparando.", "content": null, "callbackData": "atendimento-8841", "status": "read", "pricing": { "billable": true, "pricing_model": "PMP", "type": "regular", "category": "utility" }, "waId": "5511900000000", "userId": "BR.13491208655302741918", "parentUserId": null, "username": null, "displayNumber": "+55 11 90000-0000", "numberId": "a3c1f5b2-7d4e-4b8a-9c21-5e6f7a8b9c0d", "externalId": "cliente-8841", "conversationId": "2d9f6a41-0c5b-4e7a-8f13-9b6c4d2e1a07", "errorSummary": null, "createdAt": "2026-08-07T12:24:02.085Z" }, { "id": "b6d84033-a8e8-4db9-aab6-565ce203cc51", "direction": "inbound", "wamid": "wamid.HBgMNTUzMTgwMzYwMjEwFQIAEhgUM0FCMEFBNDUzNzg4NzY5MUQ5MTUA", "type": "text", "bodyText": "oi", "content": null, "callbackData": null, "status": null, "pricing": null, "waId": "5511900000000", "userId": "BR.13491208655302741918", "parentUserId": null, "username": null, "displayNumber": "+55 11 90000-0000", "numberId": "a3c1f5b2-7d4e-4b8a-9c21-5e6f7a8b9c0d", "externalId": "cliente-8841", "conversationId": "2d9f6a41-0c5b-4e7a-8f13-9b6c4d2e1a07", "errorSummary": null, "createdAt": "2026-08-07T11:35:10.000Z" } ], "nextCursor": null } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Send a text message `POST /v1/messages` Accepts the message, returns 202 with its identifier, and delivers it to Meta asynchronously. With a test key, the message does NOT go to Meta: Luna returns the 202 and delivers the simulated states sent, delivered and read to your webhook, with test: true. The optional Idempotency-Key header (1 to 255 visible characters, no space) makes repeating the request return the original message; empty or malformed answers 400. Authentication: API key. Required scope: `messages:write` Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-post-v1-messages #### Request body `application/json` Shape 1: `type = "text"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | no | Sempre text. Pode ser omitido: um corpo sem type é interpretado como texto, para não quebrar quem integrou antes dos demais tipos existirem. · default: "text" · Values: text | | `text` | `object` | yes | | | `text.body` | `string` | yes | O texto da mensagem. Limite de 4096 caracteres, o mesmo da Cloud API. · 1 to 4096 characters | | `text.preview_url` | `boolean` | no | Se a Meta deve buscar a primeira URL do texto para montar uma prévia. Desligado por padrão: ligado, ele dispara uma requisição de saída a partir de conteúdo que o negócio final escreveu, com latência e comportamento que não são da plataforma. | Shape 2: `type = "image"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | yes | Sempre image. · Values: image | | `image` | `object` | yes | | | `image.id` | `string` | no | O identificador de um arquivo já enviado à Meta. Use este OU link, nunca os dois. A Meta retém o arquivo enviado por 30 dias. · 1 to 128 characters | | `image.link` | `string (uri)` | no | A URL pública do arquivo, que a Meta baixa no momento do envio. Use esta OU id, nunca os dois. Ela precisa responder sem autenticação. · up to 2048 characters | | `image.caption` | `string` | no | A legenda que acompanha o arquivo. Limite de 1024 caracteres, o mesmo da Cloud API. · up to 1024 characters | Shape 3: `type = "video"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | yes | Sempre video. · Values: video | | `video` | `object` | yes | | | `video.id` | `string` | no | O identificador de um arquivo já enviado à Meta. Use este OU link, nunca os dois. A Meta retém o arquivo enviado por 30 dias. · 1 to 128 characters | | `video.link` | `string (uri)` | no | A URL pública do arquivo, que a Meta baixa no momento do envio. Use esta OU id, nunca os dois. Ela precisa responder sem autenticação. · up to 2048 characters | | `video.caption` | `string` | no | A legenda que acompanha o arquivo. Limite de 1024 caracteres, o mesmo da Cloud API. · up to 1024 characters | Shape 4: `type = "audio"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | yes | Sempre audio. · Values: audio | | `audio` | `object` | yes | | | `audio.id` | `string` | no | O identificador de um arquivo já enviado à Meta. Use este OU link, nunca os dois. A Meta retém o arquivo enviado por 30 dias. · 1 to 128 characters | | `audio.link` | `string (uri)` | no | A URL pública do arquivo, que a Meta baixa no momento do envio. Use esta OU id, nunca os dois. Ela precisa responder sem autenticação. · up to 2048 characters | | `audio.voice` | `boolean` | no | true para enviar como mensagem de voz (a bolinha de áudio do WhatsApp, com a forma de onda), e não como arquivo de áudio. A Meta exige um arquivo .ogg com codec OPUS, e a Luna não converte áudio: com link, um arquivo de outro tipo reconhecido (por exemplo .mp3) é recusado com 400. Com id, a Luna não vê o tipo do arquivo, e a conferência é da Meta. | Shape 5: `type = "document"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | yes | Sempre document. · Values: document | | `document` | `object` | yes | | | `document.id` | `string` | no | O identificador de um arquivo já enviado à Meta. Use este OU link, nunca os dois. A Meta retém o arquivo enviado por 30 dias. · 1 to 128 characters | | `document.link` | `string (uri)` | no | A URL pública do arquivo, que a Meta baixa no momento do envio. Use esta OU id, nunca os dois. Ela precisa responder sem autenticação. · up to 2048 characters | | `document.caption` | `string` | no | A legenda que acompanha o arquivo. Limite de 1024 caracteres, o mesmo da Cloud API. · up to 1024 characters | | `document.filename` | `string` | no | O nome com que o arquivo aparece para quem recebe. Sem ele, quem recebe vê o nome que a Meta derivar da origem. · 1 to 240 characters | Shape 6: `type = "sticker"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | yes | Sempre sticker. · Values: sticker | | `sticker` | `object` | yes | | | `sticker.id` | `string` | no | O identificador de um arquivo já enviado à Meta. Use este OU link, nunca os dois. A Meta retém o arquivo enviado por 30 dias. · 1 to 128 characters | | `sticker.link` | `string (uri)` | no | A URL pública do arquivo, que a Meta baixa no momento do envio. Use esta OU id, nunca os dois. Ela precisa responder sem autenticação. · up to 2048 characters | Shape 7: `type = "location"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | yes | Sempre location. · Values: location | | `location` | `object` | yes | | | `location.latitude` | `number` | yes | A latitude em graus decimais, entre -90 e 90. · minimum -90 · maximum 90 | | `location.longitude` | `number` | yes | A longitude em graus decimais, entre -180 e 180. · minimum -180 · maximum 180 | | `location.name` | `string` | no | O nome do lugar, exibido acima do endereço. · up to 1000 characters | | `location.address` | `string` | no | O endereço do lugar, exibido abaixo do nome. · up to 1000 characters | Shape 8: `type = "contacts"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | yes | Sempre contacts. · Values: contacts | | `contacts` | `array` | yes | Os cartões de contato a enviar. Ao menos um, no máximo vinte. · 1 to 20 items | | `contacts[].name` | `object` | yes | | | `contacts[].name.formatted_name` | `string` | yes | O nome como ele aparece no cartão. · 1 to 512 characters | | `contacts[].name.first_name` | `string` | no | O primeiro nome. · up to 256 characters | | `contacts[].name.last_name` | `string` | no | O sobrenome. · up to 256 characters | | `contacts[].name.middle_name` | `string` | no | O nome do meio. · up to 256 characters | | `contacts[].name.prefix` | `string` | no | O prefixo, como Dr. ou Sra. · up to 64 characters | | `contacts[].name.suffix` | `string` | no | O sufixo, como Jr. ou Neto. · up to 64 characters | | `contacts[].birthday` | `string` | no | A data de nascimento em AAAA-MM-DD. · /^\d{4}-\d{2}-\d{2}$/ | | `contacts[].org` | `object` | no | Os dados profissionais do contato. | | `contacts[].org.company` | `string` | no | A empresa. · up to 256 characters | | `contacts[].org.department` | `string` | no | O departamento. · up to 256 characters | | `contacts[].org.title` | `string` | no | O cargo. · up to 256 characters | | `contacts[].phones` | `array` | no | Os telefones do contato. · up to 20 items | | `contacts[].phones[].phone` | `string` | no | O telefone, como ele deve aparecer. · up to 64 characters | | `contacts[].phones[].type` | `string` | no | O rótulo do telefone, como CELL ou WORK. · up to 64 characters | | `contacts[].phones[].wa_id` | `string` | no | O identificador do contato no WhatsApp, se conhecido. · up to 64 characters | | `contacts[].emails` | `array` | no | Os e-mails do contato. · up to 20 items | | `contacts[].emails[].email` | `string` | no | O endereço de e-mail. · up to 320 characters | | `contacts[].emails[].type` | `string` | no | O rótulo do e-mail, como HOME ou WORK. · up to 64 characters | | `contacts[].addresses` | `array` | no | Os endereços do contato. · up to 20 items | | `contacts[].addresses[].street` | `string` | no | O logradouro e o número. · up to 512 characters | | `contacts[].addresses[].city` | `string` | no | A cidade. · up to 256 characters | | `contacts[].addresses[].state` | `string` | no | O estado. · up to 256 characters | | `contacts[].addresses[].zip` | `string` | no | O CEP. · up to 64 characters | | `contacts[].addresses[].country` | `string` | no | O país. · up to 256 characters | | `contacts[].addresses[].country_code` | `string` | no | O código do país em duas letras. · up to 8 characters | | `contacts[].addresses[].type` | `string` | no | O rótulo do endereço, como HOME ou WORK. · up to 64 characters | | `contacts[].urls` | `array` | no | As páginas do contato. · up to 20 items | | `contacts[].urls[].url` | `string` | no | O endereço na web. · up to 2048 characters | | `contacts[].urls[].type` | `string` | no | O rótulo da URL, como HOME ou WORK. · up to 64 characters | Shape 9: `type = "reaction"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | yes | Sempre reaction. · Values: reaction | | `reaction` | `object` | yes | | | `reaction.message_id` | `string` | yes | A mensagem que recebe a reação: o wamid que a Meta atribuiu ou o id da Luna (UUID), que a Luna troca pelo wamid. O content da mensagem enviada mostra o wamid. · 1 to 256 characters | | `reaction.emoji` | `string` | yes | O emoji da reação. Mande vazio para remover uma reação que já tinha sido posta. · up to 16 characters | Shape 10: `type = "interactive"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | yes | Sempre interactive. · Values: interactive | | `interactive` | `object` | yes | A mensagem interativa: botões de resposta (button), lista de opções (list), botão com URL (cta_url), pedido de localização (location_request_message), pedido de endereço (address_message), carrossel de mídia (carousel), Flow (flow), um produto do catálogo (product) ou uma lista de produtos do catálogo (product_list). | | `interactive.type` | `string` | no | Sempre button. · Values: button | | `interactive.header` | `object` | no | O cabeçalho, exibido acima do corpo. | | `interactive.header.type` | `string` | yes | O que o cabeçalho carrega. · Values: text, image, video, document | | `interactive.header.text` | `string` | no | O texto do cabeçalho, quando type é text. · up to 60 characters | | `interactive.header.image` | `object` | no | A imagem do cabeçalho, quando type é image. | | `interactive.header.image.id` | `string` | no | O identificador de um arquivo já enviado à Meta. Use este OU link, nunca os dois. A Meta retém o arquivo enviado por 30 dias. · 1 to 128 characters | | `interactive.header.image.link` | `string (uri)` | no | A URL pública do arquivo, que a Meta baixa no momento do envio. Use esta OU id, nunca os dois. Ela precisa responder sem autenticação. · up to 2048 characters | | `interactive.header.video` | `object` | no | O vídeo do cabeçalho, quando type é video. | | `interactive.header.video.id` | `string` | no | O identificador de um arquivo já enviado à Meta. Use este OU link, nunca os dois. A Meta retém o arquivo enviado por 30 dias. · 1 to 128 characters | | `interactive.header.video.link` | `string (uri)` | no | A URL pública do arquivo, que a Meta baixa no momento do envio. Use esta OU id, nunca os dois. Ela precisa responder sem autenticação. · up to 2048 characters | | `interactive.header.document` | `object` | no | O documento do cabeçalho, quando type é document. | | `interactive.header.document.id` | `string` | no | O identificador de um arquivo já enviado à Meta. Use este OU link, nunca os dois. A Meta retém o arquivo enviado por 30 dias. · 1 to 128 characters | | `interactive.header.document.link` | `string (uri)` | no | A URL pública do arquivo, que a Meta baixa no momento do envio. Use esta OU id, nunca os dois. Ela precisa responder sem autenticação. · up to 2048 characters | | `interactive.header.document.filename` | `string` | no | up to 240 characters | | `interactive.body` | `object` | no | O corpo da mensagem interativa. | | `interactive.body.text` | `string` | yes | O texto do corpo. · 1 to 1024 characters | | `interactive.footer` | `object` | no | O rodapé, exibido abaixo dos botões. | | `interactive.footer.text` | `string` | yes | O texto do rodapé. · up to 60 characters | | `interactive.action` | `object` | no | | | `interactive.action.buttons` | `array` | yes | Os botões de resposta. De um a três, o teto da Cloud API. · 1 to 3 items | | `interactive.action.buttons[].type` | `string` | yes | Sempre reply. · Values: reply | | `interactive.action.buttons[].reply` | `object` | yes | | | `interactive.action.buttons[].reply.id` | `string` | yes | O identificador que volta no webhook quando o botão é tocado. · 1 to 256 characters | | `interactive.action.buttons[].reply.title` | `string` | yes | O rótulo do botão. Limite de 20 caracteres. · 1 to 20 characters | | `interactive.action.button` | `string` | yes | O rótulo do botão que abre a lista. Limite de 20 caracteres. · 1 to 20 characters | | `interactive.action.sections` | `array` | yes | As seções da lista. De uma a dez, o teto da Cloud API. · 1 to 10 items | | `interactive.action.sections[].title` | `string` | no | O título da seção. · up to 24 characters | | `interactive.action.sections[].rows` | `array` | yes | As linhas da seção. De uma a dez. · 1 to 10 items | | `interactive.action.sections[].rows[].id` | `string` | yes | O identificador que volta no webhook quando a linha é escolhida. · 1 to 200 characters | | `interactive.action.sections[].rows[].title` | `string` | yes | O título da linha. · 1 to 24 characters | | `interactive.action.sections[].rows[].description` | `string` | no | A descrição da linha. · up to 72 characters | | `interactive.action.name` | `string` | no | Sempre cta_url. · default: "cta_url" · Values: cta_url | | `interactive.action.parameters` | `object` | yes | | | `interactive.action.parameters.display_text` | `string` | yes | O rótulo do botão. Limite de 20 caracteres. · 1 to 20 characters | | `interactive.action.parameters.url` | `string (uri)` | yes | O endereço que o botão abre. · up to 2048 characters | | `interactive.action.parameters.country` | `string` | no | O país do endereço, em duas letras (ISO 3166). O padrão é BR. · /^[A-Za-z]{2}$/ · default: "BR" | | `interactive.action.parameters.values` | `object` | no | Os campos do endereço já preenchidos, com os nomes que a Meta define para o país. | | `interactive.action.parameters.saved_addresses` | `array` | no | Endereços salvos que o usuário pode escolher, no máximo vinte. · up to 20 items | | `interactive.action.parameters.saved_addresses[].id` | `string` | yes | O identificador do endereço salvo. · 1 to 128 characters | | `interactive.action.parameters.saved_addresses[].value` | `object` | yes | Os campos do endereço salvo. | | `interactive.action.parameters.validation_errors` | `object` | no | Mensagens de erro por campo, para quando você devolve o formulário depois de uma validação. | | `interactive.action.cards` | `array` | yes | Os cartões, de dois a dez. · 2 to 10 items | | `interactive.action.cards[].card_index` | `integer` | yes | A posição do cartão, de 0 a 9. Não repita. · minimum 0 · maximum 9 | | `interactive.action.cards[].type` | `string` | no | Sempre cta_url. · default: "cta_url" · Values: cta_url | | `interactive.action.cards[].header` | `object` | yes | A mídia do cartão. | | `interactive.action.cards[].header.type` | `string` | yes | O que o cartão mostra. · Values: image, video | | `interactive.action.cards[].header.image` | `object` | no | A imagem do cartão, quando type é image. | | `interactive.action.cards[].header.image.id` | `string` | no | O identificador de um arquivo já enviado à Meta. Use este OU link, nunca os dois. A Meta retém o arquivo enviado por 30 dias. · 1 to 128 characters | | `interactive.action.cards[].header.image.link` | `string (uri)` | no | A URL pública do arquivo, que a Meta baixa no momento do envio. Use esta OU id, nunca os dois. Ela precisa responder sem autenticação. · up to 2048 characters | | `interactive.action.cards[].header.video` | `object` | no | O vídeo do cartão, quando type é video. | | `interactive.action.cards[].header.video.id` | `string` | no | O identificador de um arquivo já enviado à Meta. Use este OU link, nunca os dois. A Meta retém o arquivo enviado por 30 dias. · 1 to 128 characters | | `interactive.action.cards[].header.video.link` | `string (uri)` | no | A URL pública do arquivo, que a Meta baixa no momento do envio. Use esta OU id, nunca os dois. Ela precisa responder sem autenticação. · up to 2048 characters | | `interactive.action.cards[].body` | `object` | no | O texto do cartão. | | `interactive.action.cards[].body.text` | `string` | yes | O texto do cartão. Limite de 160 caracteres. · 1 to 160 characters | | `interactive.action.cards[].action` | `object` | yes | | | `interactive.action.cards[].action.name` | `string` | no | Sempre cta_url. · default: "cta_url" · Values: cta_url | | `interactive.action.cards[].action.parameters` | `object` | yes | | | `interactive.action.cards[].action.parameters.display_text` | `string` | yes | O rótulo do botão. Limite de 20 caracteres. · 1 to 20 characters | | `interactive.action.cards[].action.parameters.url` | `string (uri)` | yes | O endereço que o botão abre. · up to 2048 characters | | `interactive.action.parameters.flow_message_version` | `string` | no | A versão do formato da mensagem de Flow. O padrão é 3, a corrente na Meta. · 1 to 8 characters · default: "3" | | `interactive.action.parameters.flow_id` | `string` | no | O identificador do Flow. Use este OU flow_name. · 1 to 64 characters | | `interactive.action.parameters.flow_name` | `string` | no | O nome do Flow. Use este OU flow_id. · 1 to 200 characters | | `interactive.action.parameters.flow_cta` | `string` | yes | O rótulo do botão que abre o Flow. A Meta limita o tamanho (o limite exato está a confirmar na doc da Meta). · 1 to 40 characters | | `interactive.action.parameters.flow_token` | `string` | no | O que você quer receber de volta na resposta do Flow, para ligá-la a este envio. · up to 256 characters | | `interactive.action.parameters.flow_action` | `string` | no | navigate (padrão da Meta) ou data_exchange. · 1 to 32 characters | | `interactive.action.parameters.flow_action_payload` | `object` | no | A tela e os dados de abertura, quando flow_action é navigate. | | `interactive.action.parameters.flow_action_payload.screen` | `string` | yes | A tela do Flow que abre primeiro. · 1 to 200 characters | | `interactive.action.parameters.flow_action_payload.data` | `object` | no | Os dados que o Flow recebe nessa tela. | | `interactive.action.parameters.mode` | `string` | no | draft para testar um Flow ainda não publicado, ou published (padrão da Meta). · 1 to 16 characters | | `interactive.action.catalog_id` | `string` | yes | O identificador do catálogo na conta de negócio do número (catalog_id da Meta). · 1 to 64 characters | | `interactive.action.product_retailer_id` | `string` | yes | O identificador do produto no catálogo, o ID de conteúdo ou SKU (product_retailer_id da Meta). · 1 to 256 characters | | `interactive.action.sections[].product_items` | `array` | yes | Os produtos da seção. · 1 to 30 items | | `interactive.action.sections[].product_items[].product_retailer_id` | `string` | yes | O identificador do produto no catálogo, o ID de conteúdo ou SKU (product_retailer_id da Meta). · 1 to 256 characters | Shape 11: `type = "template"` | Field | Type | Required | Description | | --- | --- | --- | --- | | `from` | `string` | yes | O número de origem: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `to` | `string` | no | O telefone do destinatário com DDI e DDD, só dígitos, sem o sinal de mais. Nesta versão a Luna começa conversa só com telefones do Brasil (começam por 55 e têm 12 ou 13 dígitos); outro formato é recusado com 400, salvo para quem já escreveu para o seu número. Envie to OU recipient: um dos dois é obrigatório, e os dois juntos são recusados com 400. · /^[1-9]\d{7,14}$/ | | `recipient` | `string` | no | O BSUID do destinatário (por exemplo US.13491208655302741918), o identificador do usuário que não depende do telefone, como o evento recebido o traz em user_id. Use no lugar de to quando você só tem o BSUID. Templates de autenticação não vão para BSUID: eles precisam do telefone em to. | | `context` | `object` | no | Responder citando uma mensagem da mesma conversa. Não vale em template nem em reação: a Meta não aceita, e a Luna recusa com 400 antes de enfileirar. | | `context.message_id` | `string` | yes | A mensagem que esta responde, citada. Aceita o id da Luna (o UUID que POST /v1/messages devolveu ou que o evento traz em message.id) ou o wamid da Meta. A Luna resolve o id para o wamid antes de enviar. · 1 to 256 characters | | `callbackData` | `string` | no | Uma etiqueta sua, de 1 a 512 caracteres, que a Luna guarda com a mensagem e devolve em callback_data no evento message.status (todos os estados) e em callbackData em GET /v1/messages e GET /v1/messages/{id}. Serve para ligar a mensagem a algo seu, como o cliente ou o atendimento, sem manter uma tabela de ids. A Luna repassa o valor à Meta (biz_opaque_callback_data) e não o interpreta. Não ponha dado pessoal nela: ela viaja nos eventos. · 1 to 512 characters | | `typingMs` | `integer` | no | Mostra o indicador de digitando por este tempo, em milissegundos (de 1 a 25000), antes de a mensagem sair. A Luna liga o indicador na última mensagem que o contato mandou e envia depois da espera, sem segurar as outras conversas. Só vale dentro da janela de atendimento: se a conversa não tem mensagem recebida nas últimas 24 horas, a Luna ignora o campo e envia na hora. Ligar o indicador também marca essa mensagem recebida como lida. · minimum 1 · maximum 25000 | | `type` | `string` | yes | Sempre template. · Values: template | | `template` | `object` | yes | | | `template.name` | `string` | yes | O nome do template já aprovado pela Meta. · 1 to 512 characters | | `template.language` | `object` | yes | | | `template.language.code` | `string` | yes | O código do idioma do template, como pt_BR. Ele precisa bater com o aprovado. · 2 to 16 characters | | `template.components` | `array` | no | Os componentes que preenchem as variáveis do template. · up to 32 items | | `template.components[].type` | `string` | yes | Qual parte do template este componente preenche. · Values: header, body, button | | `template.components[].sub_type` | `string` | no | O subtipo, exigido pela Cloud API quando type é button. · up to 64 characters | | `template.components[].index` | `string` | no | A posição do botão, exigida pela Cloud API quando type é button. · up to 8 characters | | `template.components[].parameters` | `array` | no | Os valores das variáveis desta parte, na forma que a Cloud API define. · up to 64 items | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "from": "1000000000000001", "to": "5511900000000", "text": { "body": "Olá! Recebemos seu pedido e já estamos preparando." } }' ``` #### Responses **202**: Accepted: the request was recorded and will be processed. ```json { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "status": "queued" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "window_closed", "docsUrl": "https://lunahia.com.br/docs/enviar-mensagens", "message": "A janela de atendimento desta conversa está fechada. Só é possível enviar mensagem livre até 24 horas depois da última mensagem do contato.", "fechadaEm": "2026-10-06T12:00:00.000Z", "acaoRecomendada": "Para falar com este contato agora, envie um template aprovado. A mensagem livre volta a ser aceita quando o contato responder, porque é a resposta dele que abre a janela. Se este contato escreveu há pouco e a janela devia estar aberta, confira o campo to: use o telefone do evento recebido (wa_id).", "detalheTecnico": "A Luna já acha a conversa do celular brasileiro com e sem o nono dígito, mas qualquer outra diferença no telefone não encontra a conversa. Se o contato escreveu sem telefone (só com BSUID, o identificador de usuário), envie com recipient igual ao user_id do evento, e não com to." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Mark a message as read `POST /v1/messages/{id}/read` Marks a message you received as read on Meta, and returns 200 once it accepts. Authentication: API key. Required scope: `messages:write` Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-post-v1-messages-id-read #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador da mensagem na Luna, como GET /v1/messages o devolve. | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/messages/YOUR_ID/read" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: A Meta aceitou a marcação. ```json {} ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Show the typing indicator `POST /v1/messages/{id}/typing` Shows the recipient that you are writing, and returns 200 once Meta accepts. Authentication: API key. Required scope: `messages:write` Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-post-v1-messages-id-typing #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador da mensagem na Luna, como GET /v1/messages o devolve. | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/messages/YOUR_ID/typing" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: A Meta aceitou o indicador. ```json {} ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read one message's state `GET /v1/messages/{id}` Returns the message's current state, the timestamp of each step, and what Meta said whenever it refused something. Authentication: API key. Required scope: `messages:read` Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-get-v1-messages-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador da mensagem na Luna, como GET /v1/messages o devolve. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/messages/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "wamid": null, "content": null, "status": "failed", "criadaEm": "2026-08-24T12:24:02.085Z", "enviadaEm": null, "entregueEm": null, "lidaEm": null, "callbackData": null, "pricing": null, "erros": [ { "codigo": 131026, "categoria": "nao_entregavel", "mensagem": "O destinatário não pode receber esta mensagem: o número não tem WhatsApp, ou não existe.", "acaoRecomendada": "Confira o número do destinatário e reenvie para o número correto. Repetir o envio para o mesmo número não muda o resultado.", "original": { "error": { "message": "Message undeliverable", "type": "OAuthException", "code": 131026, "fbtrace_id": "AbCdEfGhIjK" } } } ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Cancel a message in the queue `DELETE /v1/messages/{id}` Cancels a message still in the outbound queue (accepted) and answers 204. It moves to the terminal state canceled, and the message.status event with status canceled reaches your webhook. If the message already went to Meta or has an outcome, it answers 409 message_not_cancelable with the current state. Authentication: API key. Required scope: `messages:write` Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-delete-v1-messages-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador da mensagem na Luna, como POST /v1/messages o devolveu. | #### Code examples ```bash curl -X DELETE "https://api.lunahia.com.br/v1/messages/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **204**: No content: the operation was done and the response has no body. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "message_not_cancelable", "docsUrl": "https://lunahia.com.br/docs/enviar-mensagens", "message": "Só uma mensagem que ainda está na fila de saída pode ser cancelada, e esta já saiu para a Meta ou já tem um desfecho. O estado atual vem em status; confira o resultado com GET /v1/messages/{id}.", "status": "sent" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Replay a message's webhook `POST /v1/messages/{id}/replay` Asks for this message's event to be delivered to your endpoint again: the message.received if it was received, or the latest message.status if it was sent, with the same format and the same signature as the original. The response is 202: the request was recorded, and delivery happens asynchronously. A sent message that has no state yet, or that Meta has not accepted yet, answers 400. Authentication: API key. Required scope: `webhooks:write` Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-post-v1-messages-id-replay #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador da mensagem na Luna, como GET /v1/messages o devolve. | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/messages/YOUR_ID/replay" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **202**: O pedido de reenvio foi registrado. A entrega acontece de forma assíncrona, pelo mesmo caminho de sempre. ```json { "deliveryId": "9f2a1b0c-3d4e-4f5a-8b9c-0d1e2f3a4b5c", "requestedAt": "2026-08-26T18:30:00.000Z" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "no_webhook_endpoint", "docsUrl": "https://lunahia.com.br/docs/receber-eventos", "message": "Não há endpoint de webhook ativo para entregar este reenvio. Cadastre um em POST /v1/webhooks/endpoints, ou retome um pausado em PATCH /v1/webhooks/endpoints/{id}, e peça de novo." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Simulate a received message `POST /v1/test-mode/inbound-messages` Delivers ONE example message.received to your webhook endpoints, signed and with test: true on the envelope, so you can exercise your code without waiting for a contact to write. The message goes out in about half a second, and nothing is stored or goes through a number of yours or through Meta. It works with the test key and with the regular key. Authentication: API key. Required scope: `messages:write` #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `phoneNumberId` | `string` | no | O phone_number_id que aparece no evento. Texto livre: a Luna não procura o número. Ausente, 123456789012345. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `waId` | `string` | no | O telefone de quem "escreveu", só dígitos. Ausente, 5511900000000. · /^[1-9]\d{7,14}$/ | | `text` | `string` | no | O texto da mensagem recebida. Ausente, um texto de exemplo. · 1 to 4096 characters | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/test-mode/inbound-messages" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "phoneNumberId": "YOUR_PHONENUMBERID", "waId": "YOUR_WAID", "text": "YOUR_TEXT" }' ``` #### Responses **202**: Accepted: the request was recorded and will be processed. ```json { "id": "3f6a1c52-9d4e-4b87-a1f0-5e2c7b9d8a14", "wamid": "wamid.TESTE_3f6a1c529d4e4b87a1f05e2c7b9d8a14", "endpoints": 1 } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ## Conversations One row per contact per number, with the state of the 24 hour customer service window. ### List conversations `GET /v1/conversations` One row per correspondent per number, from the most active to the most idle. Authentication: API key. Required scope: `messages:read` Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-get-v1-conversations #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `limit` | `integer` | no | | | `phoneNumberId` | `string` | no | O número: o UUID da Luna (o id de GET /v1/numbers) ou o id da Meta (metaPhoneNumberId). Os dois valem. | | `externalId` | `string` | no | O rótulo que você deu ao seu cliente (externalId): só as conversas dos números dele. Igualdade exata; um rótulo sem número devolve lista vazia. | | `waId` | `string` | no | O identificador do interlocutor no WhatsApp (o waId da conversa, em geral o telefone só com dígitos): só as conversas dele, em cada número. Igualdade exata, mas o celular brasileiro vale nas duas grafias, com e sem o 9 depois do DDD (a Meta entrega alguns sem ele); um waId sem conversa devolve lista vazia. | | `userId` | `string` | no | O BSUID do interlocutor (userId), o identificador do usuário que não depende do telefone: só a conversa dele, em cada número. Igualdade exata; um userId sem conversa devolve lista vazia. | | `cursor` | `string` | no | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/conversations" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "id": "0f2c8e6a-1d3b-4a5c-9e7f-2b4d6a8c0e12", "waId": "5511900000000", "userId": "BR.13491208655302741918", "parentUserId": null, "username": null, "phoneNumberId": "7a1c9d3e-5f2b-4c8a-9d6e-1b3f5a7c9e11", "numberId": "7a1c9d3e-5f2b-4c8a-9d6e-1b3f5a7c9e11", "externalId": "cliente-8841", "contactName": "Maria Souza", "displayNumber": "+55 11 90000-0000", "createdAt": "2026-08-07T11:35:10.000Z", "lastMessage": { "direction": "outbound", "type": "text", "bodyText": "Olá! Recebemos seu pedido e já estamos preparando.", "createdAt": "2026-08-07T12:24:02.085Z" }, "windowOpen": true, "windowExpiresAt": "2026-08-08T11:35:10.000Z", "windowSource": "usuario" } ], "nextCursor": null } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ## Media Upload a file to Meta and download the media that arrived in a message. ### Get a message's media `GET /v1/messages/{id}/media` Returns a signed URL, issued by Luna, to download media that has already been persisted. Authentication: API key. Required scope: `messages:read` Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-get-v1-messages-id-media #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador da mensagem na Luna, como GET /v1/messages o devolve. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/messages/YOUR_ID/media" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "url": "https://c1b129d42065073c6f8b203801c44b2d.r2.cloudflarestorage.com/lunabucket/midia/ae60f288-7565-4315-a440-3663e9c231e1?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expires=300&X-Amz-Signature=EXEMPLO", "expiraEm": "2026-08-24T12:29:02.085Z" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "media_not_ready", "docsUrl": "https://lunahia.com.br/docs/enviar-mensagens", "message": "A mídia desta mensagem ainda não está disponível.", "estado": "pendente" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Download media through the notice link `GET /v1/media/{token}` The link that comes in media.url on the message.received and message.echo notices. It asks for no API key: the token in the address is the credential. Ready media answers 302 to a short-lived signed URL; media still being downloaded from Meta, 409 with Retry-After; a token that does not exist or has expired, 404. Authentication: Public, no key Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-get-v1-media-token #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `token` | `string` | yes | O token do link, como veio em media.url. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/media/YOUR_TOKEN" ``` #### Responses **302**: Redirect: follow the Location header, which leads to the signed URL of the file. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "media_not_ready", "docsUrl": "https://lunahia.com.br/docs/enviar-mensagens", "message": "A mídia desta mensagem ainda não está disponível.", "estado": "pendente" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Upload a file and get its media identifier `POST /v1/numbers/{id}/media` Takes a file in multipart/form-data under the field file, uploads it to Meta and returns its identifier. Authentication: API key. Required scope: `messages:write` Topic guide: https://lunahia.com.br/en/docs/send-messages#rota-post-v1-numbers-id-media #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Request body `multipart/form-data` | Field | Type | Required | Description | | --- | --- | --- | --- | | `file` | `string (binary)` | yes | The file to upload, in the file field. | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/numbers/YOUR_ID/media" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -F "file=@./pedido.jpg;type=image/jpeg" ``` #### Responses **200**: Success. ```json { "mediaId": "1425835918205946" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **413**: The file is over the size ceiling, which is the same for every customer. ```json { "error": "file_too_large", "docsUrl": "https://lunahia.com.br/docs/enviar-mensagens", "message": "O arquivo passa do tamanho que a plataforma aceita. O limite é o mesmo para todos os clientes: ele existe por capacidade de infraestrutura." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ## Templates Messages pre-approved by Meta, required to start a conversation outside the 24 hour window. Approved is not cleared for volume: Meta applies a pace of its own over the first sends of a new template, and publishes no deadline and no mechanics. Ramp up your first send instead of scheduling it for a date, and watch the state of the template. Above three buttons, only two appear in the delivered message. Meta accepts the template with more and delivers two, so the arrangement has to be decided before the flow is designed. ### List templates `GET /v1/templates` This customer's templates, newest first. Authentication: API key. Required scope: `templates:read` Topic guide: https://lunahia.com.br/en/docs/templates#rota-get-v1-templates #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `status` | `string` | no | Devolve apenas os templates cujo último estado observado é exatamente este valor. A comparação é literal e sensível a maiúsculas. Valores comuns: APPROVED, PENDING, REJECTED, PAUSED, DISABLED, mas o campo é texto livre, porque a Meta acrescenta estado sem aviso e um conjunto fechado impediria você de filtrar pelo estado novo. | | `wabaId` | `string` | no | Devolve apenas os templates desta conta de negócio na Meta (WABA), o wabaId que GET /v1/business-accounts devolve. Com um cliente seu por conta, é o jeito de ver só os templates dele. Comparação exata. | | `phoneNumberId` | `string` | no | Devolve apenas os templates da conta de negócio a que este número pertence. Aceita o UUID da Luna (o id de GET /v1/numbers) ou o id da Meta (metaPhoneNumberId). Template é da conta, e não do número: todos os números da conta compartilham os mesmos templates. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/templates" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "metaTemplateId": "1259544702043801", "wabaId": "102290129340398", "name": "numero_conectado", "language": "pt_BR", "category": "UTILITY", "status": "APPROVED", "createdAt": "2026-08-10T12:24:02.085Z", "updatedAt": "2026-08-10T12:31:47.004Z", "bodyText": "Olá {{primeiro_nome}}, o seu número foi conectado.", "header": null, "headerMedia": null, "footer": null, "buttons": [], "variables": [ { "name": "primeiro_nome", "example": "Maria" } ], "rejectedReason": null, "qualityScore": "GREEN", "previousCategory": null, "allowedActions": [ "edit", "delete" ] } ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Create a template `POST /v1/templates` Creates the template in the customer's account and submits it to Meta for approval. Authentication: API key. Required scope: `templates:write` Topic guide: https://lunahia.com.br/en/docs/templates#rota-post-v1-templates #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `wabaId` | `string` | yes | 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `name` | `string` | yes | /^[a-z0-9_]{1,512}$/ | | `bodyText` | `string` | yes | 1 to 1024 characters | | `examples` | `object` | no | Um valor de amostra por variável do corpo. Obrigatório quando o corpo tem `{{variavel}}`, porque a Meta recusa parâmetro sem exemplo. | | `header` | `string` | no | Cabeçalho de texto, exibido acima do corpo. Para cabeçalho de imagem, vídeo ou documento, use headerMedia. · 1 to 60 characters | | `headerMedia` | `object` | no | Cabeçalho de imagem, vídeo ou documento. O handle vem de POST /v1/template-assets, e não do identificador de mídia de mensagem. O arquivo é o exemplo que a Meta revisa, e não o conteúdo entregue: cada mensagem enviada fornece a própria mídia. | | `headerMedia.format` | `string` | yes | IMAGE, VIDEO ou DOCUMENT. Para documento a Meta aceita apenas PDF. · Values: IMAGE, VIDEO, DOCUMENT | | `headerMedia.handle` | `string` | yes | O handle devolvido por POST /v1/template-assets. · 1 to 2048 characters | | `footer` | `string` | no | Rodapé, exibido abaixo do corpo. Não aceita variável. · 1 to 60 characters | | `buttons` | `array` | no | Até 10 botões no total, somando todos os tipos. Se houver respostas rápidas junto de outros botões, os dois conjuntos precisam ficar agrupados: respostas rápidas de um lado, o resto do outro. Acima de três botões, apenas dois aparecem na mensagem entregue: a Meta aceita o template e entrega dois. | | `buttons[].type` | `string` | no | Values: QUICK_REPLY | | `buttons[].text` | `string` | no | 1 to 25 characters | | `buttons[].url` | `string` | no | 1 to 2000 characters | | `buttons[].example` | `array` | no | up to 1 items | | `buttons[].phone_number` | `string` | no | 1 to 20 characters | | `category` | `string` | no | A categoria do template. Ausente vale UTILITY, que é o comportamento de quem já integra e não manda o campo. A Meta pode reclassificar na criação: o template continua aprovado, com outra categoria, e a resposta traz a que ela atribuiu. Template de autenticação tem corpo próprio e ainda não é criado por esta rota. · Values: MARKETING, UTILITY | | `language` | `string` | no | O código de idioma do template, na grafia da Meta: sublinhado e não hífen. pt_BR, pt_PT, en_US, es_MX, fr. A lista completa está em Supported Languages, na documentação da Meta, e o campo aceita qualquer código que ela publicar, porque um conjunto fechado aqui impediria você de usar o próximo. Ausente vale pt_BR. Atenção ao que o idioma custa: cada idioma é um template separado para a Meta, e o teto é de 250 templates por conta de WhatsApp Business. · /^[a-z]{2,3}(_[A-Z]{2})?$/ | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/templates" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "wabaId": "YOUR_WABAID", "name": "YOUR_NAME", "bodyText": "YOUR_BODYTEXT" }' ``` #### Responses **201**: Created. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "metaTemplateId": "YOUR_METATEMPLATEID", "wabaId": "YOUR_WABAID", "name": "YOUR_NAME", "language": "YOUR_LANGUAGE", "category": "YOUR_CATEGORY", "status": "YOUR_STATUS", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read a template `GET /v1/templates/{id}` The template's current state at Meta, the content you wrote, and what Meta announced about it. Authentication: API key. Required scope: `templates:read` Topic guide: https://lunahia.com.br/en/docs/templates#rota-get-v1-templates-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/templates/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "metaTemplateId": "YOUR_METATEMPLATEID", "wabaId": "YOUR_WABAID", "name": "YOUR_NAME", "language": "YOUR_LANGUAGE", "category": "YOUR_CATEGORY", "status": "YOUR_STATUS", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT", "bodyText": "YOUR_BODYTEXT", "header": "YOUR_HEADER", "headerMedia": { "format": "YOUR_FORMAT" }, "footer": "YOUR_FOOTER", "buttons": [ { "type": "QUICK_REPLY", "text": "YOUR_TEXT" } ], "variables": [ { "name": "YOUR_NAME", "example": "YOUR_EXAMPLE" } ], "rejectedReason": "YOUR_REJECTEDREASON", "qualityScore": "YOUR_QUALITYSCORE", "previousCategory": "YOUR_PREVIOUSCATEGORY", "allowedActions": [ "edit" ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Edit a template `PATCH /v1/templates/{id}` Changes the components of an existing template. Authentication: API key. Required scope: `templates:write` Topic guide: https://lunahia.com.br/en/docs/templates#rota-patch-v1-templates-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `bodyText` | `string` | no | 1 to 1024 characters | | `examples` | `object` | no | | | `header` | `string` | no | Cabeçalho de texto, exibido acima do corpo. Para cabeçalho de imagem, vídeo ou documento, use headerMedia. · 1 to 60 characters | | `footer` | `string` | no | Rodapé, exibido abaixo do corpo. Não aceita variável. · 1 to 60 characters | | `buttons` | `array` | no | Até 10 botões no total, somando todos os tipos. Se houver respostas rápidas junto de outros botões, os dois conjuntos precisam ficar agrupados: respostas rápidas de um lado, o resto do outro. Acima de três botões, apenas dois aparecem na mensagem entregue: a Meta aceita o template e entrega dois. | | `buttons[].type` | `string` | no | Values: QUICK_REPLY | | `buttons[].text` | `string` | no | 1 to 25 characters | | `buttons[].url` | `string` | no | 1 to 2000 characters | | `buttons[].example` | `array` | no | up to 1 items | | `buttons[].phone_number` | `string` | no | 1 to 20 characters | #### Code examples ```bash curl -X PATCH "https://api.lunahia.com.br/v1/templates/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "bodyText": "YOUR_BODYTEXT", "examples": {}, "header": "YOUR_HEADER" }' ``` #### Responses **200**: Success. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "metaTemplateId": "YOUR_METATEMPLATEID", "wabaId": "YOUR_WABAID", "name": "YOUR_NAME", "language": "YOUR_LANGUAGE", "category": "YOUR_CATEGORY", "status": "YOUR_STATUS", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Delete a template `DELETE /v1/templates/{id}` Deletes the template at Meta and from your listing. Authentication: API key. Required scope: `templates:write` Topic guide: https://lunahia.com.br/en/docs/templates#rota-delete-v1-templates-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Code examples ```bash curl -X DELETE "https://api.lunahia.com.br/v1/templates/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **204**: No content: the operation was done and the response has no body. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read the template rules `GET /v1/templates/rules` The categories, the suggested languages, the name format, the maximum lengths of body, header and footer, and the button limits. It is what POST /v1/templates enforces, served so you can show the same limit without copying the number. Authentication: API key. Required scope: `templates:read` #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/templates/rules" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "categories": [ { "value": "MARKETING", "label": "Marketing", "summary": "Promove, convida ou tenta reengajar: oferta, novidade, carrinho esquecido. A Meta pode reclassificar um template de utilidade para marketing." } ], "languages": [ { "code": "pt_BR", "label": "Português (Brasil)" } ], "namePattern": "^[a-z0-9_]{1,512}$", "nameExample": "confirmacao_do_pedido", "bodyMaxLength": 1024, "headerMaxLength": 60, "footerMaxLength": 60, "buttonLimits": { "total": 10, "byType": { "QUICK_REPLY": 10, "URL": 2, "PHONE_NUMBER": 1, "COPY_CODE": 1 } } } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Create an authentication template `POST /v1/templates/authentication` Creates an authentication template with a copy code button, and submits it to Meta for approval. Authentication: API key. Required scope: `templates:write` Topic guide: https://lunahia.com.br/en/docs/templates#rota-post-v1-templates-authentication #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `wabaId` | `string` | yes | 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `name` | `string` | yes | /^[a-z0-9_]{1,512}$/ | | `language` | `string` | no | O código de idioma do template, na grafia da Meta: sublinhado e não hífen. pt_BR, pt_PT, en_US, es_MX, fr. A lista completa está em Supported Languages, na documentação da Meta, e o campo aceita qualquer código que ela publicar, porque um conjunto fechado aqui impediria você de usar o próximo. Ausente vale pt_BR. Atenção ao que o idioma custa: cada idioma é um template separado para a Meta, e o teto é de 250 templates por conta de WhatsApp Business. · /^[a-z]{2,3}(_[A-Z]{2})?$/ | | `addSecurityRecommendation` | `boolean` | no | Se o template deve incluir o aviso de segurança da Meta, que pede para não compartilhar o código. O texto é da Meta, é gerado no idioma do template e não é customizável. Ausente vale falso. | | `codeExpirationMinutes` | `integer` | yes | Em quantos minutos o código expira. Vai para o rodapé do template, num texto da Meta que não é customizável. O teto aceito aqui é uma guarda desta plataforma contra valor absurdo, e não uma afirmação sobre a faixa que a Meta aceita: essa faixa não está publicada na documentação dela. · minimum 1 · maximum 1440 | | `buttonText` | `string` | no | O rótulo do botão de copiar código. Omitir é o recomendado: sem ele a Meta usa o rótulo padrão do idioma do template, que já está traduzido. Máximo de 25 caracteres. · 1 to 25 characters | | `messageSendTtlSeconds` | `integer` | no | Tempo de vida, em segundos, das mensagens enviadas com este template. Ausente, o campo não é enviado à Meta e vale o padrão dela. Um código de verificação que chega tarde demais já não serve, e é para isso que ele existe. · minimum 1 | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/templates/authentication" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "wabaId": "YOUR_WABAID", "name": "YOUR_NAME", "codeExpirationMinutes": 10 }' ``` #### Responses **201**: Created. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "metaTemplateId": "YOUR_METATEMPLATEID", "wabaId": "YOUR_WABAID", "name": "YOUR_NAME", "language": "YOUR_LANGUAGE", "category": "YOUR_CATEGORY", "status": "YOUR_STATUS", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Copy a template to other customers `POST /v1/templates/{id}/copy` Creates a copy of the template in up to 50 destinations, each a business account (wabaId) or a customer of yours (externalId). Answers 200 with one result per destination, and a destination that fails does not bring the others down. The copy goes through the same path and the same rules as POST /v1/templates. Authentication: API key. Required scope: `templates:write` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `targets` | `array` | yes | Os destinos, de 1 a 50. Cada um é { wabaId } ou { externalId }. · 1 to 50 items | | `targets[].wabaId` | `string` | no | A conta de negócio de destino, pelo id dela na Meta (wabaId). · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `targets[].externalId` | `string` | no | O rótulo do cliente de destino (externalId): a cópia vai para cada conta de WhatsApp Business dos números dele. · 1 to 128 characters | | `headerMediaHandle` | `string` | no | O handle do arquivo de exemplo do cabeçalho de mídia, para template de origem que tem um. A Luna guarda só o formato do cabeçalho, não o arquivo. · 1 to 1024 characters | | `authentication` | `object` | no | Os parâmetros do template de autenticação, obrigatórios quando o template de origem é de autenticação: a Luna não os guarda. | | `authentication.addSecurityRecommendation` | `boolean` | no | Se o template deve incluir o aviso de segurança da Meta, que pede para não compartilhar o código. O texto é da Meta, é gerado no idioma do template e não é customizável. Ausente vale falso. | | `authentication.codeExpirationMinutes` | `integer` | yes | Em quantos minutos o código expira. Vai para o rodapé do template, num texto da Meta que não é customizável. O teto aceito aqui é uma guarda desta plataforma contra valor absurdo, e não uma afirmação sobre a faixa que a Meta aceita: essa faixa não está publicada na documentação dela. · minimum 1 · maximum 1440 | | `authentication.buttonText` | `string` | no | O rótulo do botão de copiar código. Omitir é o recomendado: sem ele a Meta usa o rótulo padrão do idioma do template, que já está traduzido. Máximo de 25 caracteres. · 1 to 25 characters | | `authentication.messageSendTtlSeconds` | `integer` | no | Tempo de vida, em segundos, das mensagens enviadas com este template. Ausente, o campo não é enviado à Meta e vale o padrão dela. Um código de verificação que chega tarde demais já não serve, e é para isso que ele existe. · minimum 1 | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/templates/YOUR_ID/copy" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "targets": [ { "wabaId": "YOUR_WABAID", "externalId": "YOUR_EXTERNALID" } ] }' ``` #### Responses **200**: Success. ```json { "results": [ { "target": { "wabaId": "YOUR_WABAID", "externalId": "YOUR_EXTERNALID" }, "wabaId": "YOUR_WABAID", "status": 1, "template": { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "metaTemplateId": "YOUR_METATEMPLATEID", "wabaId": "YOUR_WABAID", "name": "YOUR_NAME", "language": "YOUR_LANGUAGE", "category": "YOUR_CATEGORY", "status": "YOUR_STATUS", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT" }, "error": { "error": "YOUR_ERROR", "message": "YOUR_MESSAGE" } } ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "template_content_unknown", "docsUrl": "https://lunahia.com.br/docs/templates", "message": "A Luna não conhece o conteúdo deste template: ele foi criado direto no painel da Meta, ou antes de a Luna guardar o conteúdo. Sem o conteúdo não há o que copiar. Crie o template de novo por POST /v1/templates e copie o novo." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Upload the example file for a media header `POST /v1/template-assets` Takes a file in multipart/form-data under the field file and returns the handle that template creation accepts in headerMedia.handle. Authentication: API key. Required scope: `templates:write` Topic guide: https://lunahia.com.br/en/docs/templates#rota-post-v1-template-assets #### Request body `multipart/form-data` | Field | Type | Required | Description | | --- | --- | --- | --- | | `file` | `string (binary)` | yes | The file to upload, in the file field. | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/template-assets" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -F "file=@./pedido.jpg;type=image/jpeg" ``` #### Responses **200**: Success. ```json { "handle": "4:cGVkaWRvLnBuZw==:aW1hZ2UvcG5n:ARb0Xk:e:1790451084:1269849425120687:0" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **413**: The file is over the size ceiling, which is the same for every customer. ```json { "error": "file_too_large", "docsUrl": "https://lunahia.com.br/docs/enviar-mensagens", "message": "O arquivo passa do tamanho que a plataforma aceita. O limite é o mesmo para todos os clientes: ele existe por capacidade de infraestrutura." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ## Phone numbers The connected numbers: connect, read state, quality and throughput, edit and disconnect. Migrating a number that is already on another provider's API is a supported path, and it needs no new number and loses no existing one. A number already registered on another provider's Cloud API almost always has two step verification configured there, and Meta requires the existing PIN to register it again: there is no endpoint to read or to turn that PIN off, so it has to come from the end business. Give the PIN at POST /v1/numbers/{id}/pin, or ask the end business to turn two step verification off in its WhatsApp Manager. The other prerequisites are on its side too: it has to own the WhatsApp Business account and have the number released by the previous provider. A number that today exists only in the WhatsApp Business App, the phone application, is the other case, and Meta calls it coexistence. It has never been through any API. The connection starts from the same Meta window, and the option only shows up once the end business account is enabled for it on Meta's side and the app on the device is version 2.24.17 or later. Connected this way, the number keeps working in the phone application, and the earlier conversations on the device are imported into the platform: they show up in GET /v1/messages next to the new ones. The import has a deadline to finish, and what tells you where it stands is GET /v1/numbers/{id}, in the fields sincronizacaoDoHistorico and sincronizacaoPrazo. The same resource carries tetoDeVazaoPorSegundo, which is the fixed sending speed ceiling of a number in coexistence and does not go up over time. And what the business owner answers from the phone application arrives too, in the recipient's conversation. ### Read the business profile `GET /v1/numbers/{id}/profile` The profile the contact sees on WhatsApp: about text, address, description, email, websites, vertical and the picture. It does not work on a number in coexistence. Authentication: API key. Required scope: `numbers:read` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers/YOUR_ID/profile" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "about": "Atendimento de segunda a sexta", "address": "YOUR_ADDRESS", "description": "YOUR_DESCRIPTION", "email": "ana@suaempresa.com.br", "websites": [ "YOUR_WEBSITES" ], "vertical": "YOUR_VERTICAL", "profilePictureUrl": "YOUR_PROFILEPICTUREURL" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "not_available_in_coexistence", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "Este número está conectado em coexistência, e a Meta não aceita esta operação por API nesse caso. Faça a mudança no aplicativo WhatsApp Business do celular do negócio." } ``` **422**: The request is well formed and Luna passed it on, and Meta refused it. The meta field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. ```json { "error": "meta_rejected", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "A Meta recusou esta operação. O campo meta traz o que aconteceu, o que fazer e o erro original dela.", "meta": { "codigo": 131030, "categoria": "nao_entregavel", "mensagem": "A Meta recusou o pedido.", "acaoRecomendada": "Confira os campos enviados e tente de novo.", "original": { "error": { "message": "Invalid parameter", "type": "OAuthException", "code": 131030, "fbtrace_id": "AbCdEfGhIjK" } } } } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Change the business profile `PATCH /v1/numbers/{id}/profile` Changes the fields you send and leaves the others as they are. With displayName, it requests the display name change and answers 202: the name stays under review at Meta. It does not work on a number in coexistence. Authentication: API key. Required scope: `numbers:write` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `about` | `string` | no | O recado curto. Até 139 caracteres. · 1 to 139 characters | | `address` | `string` | no | O endereço. Até 256 caracteres. · 1 to 256 characters | | `description` | `string` | no | A descrição. Até 512 caracteres. · 1 to 512 characters | | `email` | `string` | no | O e-mail de contato. Até 128 caracteres. · 1 to 128 characters | | `websites` | `array` | no | Até dois sites. A lista inteira substitui a que existe. · up to 2 items | | `vertical` | `string` | no | O ramo de atividade, no vocabulário da Meta. · 1 to 64 characters | | `displayName` | `string` | no | Pede à Meta a mudança do nome de exibição (o nome que o contato vê no topo da conversa). A resposta é 202: o pedido está em revisão e displayNameStatus passa a pending_review. A Meta aceita até 10 mudanças a cada 30 dias, e é ela quem julga o nome. O evento number.display_name_reviewed avisa o resultado. Um nome aprovado só passa a valer depois que o número é registrado de novo. · 1 to 512 characters | | `profilePictureHandle` | `string` | no | O handle de uma foto que você subiu pelo envio resumível da Meta. O mesmo handle que POST /v1/template-assets devolve serve de foto do perfil, o que está a confirmar na doc da Meta. · 1 to 1024 characters | #### Code examples ```bash curl -X PATCH "https://api.lunahia.com.br/v1/numbers/YOUR_ID/profile" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "about": "YOUR_ABOUT", "address": "YOUR_ADDRESS", "description": "YOUR_DESCRIPTION" }' ``` #### Responses **200**: Success. ```json { "updatedFields": [ "YOUR_UPDATEDFIELDS" ] } ``` **202**: Accepted: the request was recorded and will be processed. ```json { "updatedFields": [ "YOUR_UPDATEDFIELDS" ], "displayNameStatus": "pending_review", "pendingDisplayName": "YOUR_PENDINGDISPLAYNAME" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "not_available_in_coexistence", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "Este número está conectado em coexistência, e a Meta não aceita esta operação por API nesse caso. Faça a mudança no aplicativo WhatsApp Business do celular do negócio." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **422**: The request is well formed and Luna passed it on, and Meta refused it. The meta field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. ```json { "error": "meta_rejected", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "A Meta recusou esta operação. O campo meta traz o que aconteceu, o que fazer e o erro original dela.", "meta": { "codigo": 131030, "categoria": "nao_entregavel", "mensagem": "A Meta recusou o pedido.", "acaoRecomendada": "Confira os campos enviados e tente de novo.", "original": { "error": { "message": "Invalid parameter", "type": "OAuthException", "code": 131030, "fbtrace_id": "AbCdEfGhIjK" } } } } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### List blocked users `GET /v1/numbers/{id}/blocked-users` Who this number has blocked, in pages. The cursor is Meta's, and its shape does not change. Authentication: API key. Required scope: `messages:read` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `limit` | `integer` | no | Quantos por página, de 1 a 100. | | `cursor` | `string` | no | O nextCursor da página anterior. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers/YOUR_ID/blocked-users" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "waId": "YOUR_WAID", "userId": "YOUR_USERID" } ], "nextCursor": "YOUR_NEXTCURSOR" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "number_disconnected", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Este número foi desconectado da Luna e não envia mais. O histórico foi preservado. Para voltar a usá-lo, conecte-o de novo com um link de conexão (POST /v1/onboarding/links)." } ``` **422**: The request is well formed and Luna passed it on, and Meta refused it. The meta field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. ```json { "error": "meta_rejected", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "A Meta recusou esta operação. O campo meta traz o que aconteceu, o que fazer e o erro original dela.", "meta": { "codigo": 131030, "categoria": "nao_entregavel", "mensagem": "A Meta recusou o pedido.", "acaoRecomendada": "Confira os campos enviados e tente de novo.", "original": { "error": { "message": "Invalid parameter", "type": "OAuthException", "code": 131030, "fbtrace_id": "AbCdEfGhIjK" } } } } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Block users `POST /v1/numbers/{id}/blocked-users` Blocks people who wrote to the number in the last 24 hours. Each user is a phone number or a BSUID, and the response separates the ones Meta accepted from the ones it refused, with the reason. Authentication: API key. Required scope: `messages:write` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `users` | `array` | yes | Os usuários a bloquear, de um a cinquenta. · 1 to 50 items | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/numbers/YOUR_ID/blocked-users" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "users": [ "YOUR_USERS" ] }' ``` #### Responses **200**: Success. ```json { "done": [ { "input": "YOUR_INPUT", "waId": "YOUR_WAID", "userId": "YOUR_USERID", "reasons": [ "YOUR_REASONS" ] } ], "failed": [ { "input": "YOUR_INPUT", "waId": "YOUR_WAID", "userId": "YOUR_USERID", "reasons": [ "YOUR_REASONS" ] } ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "number_disconnected", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Este número foi desconectado da Luna e não envia mais. O histórico foi preservado. Para voltar a usá-lo, conecte-o de novo com um link de conexão (POST /v1/onboarding/links)." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **422**: The request is well formed and Luna passed it on, and Meta refused it. The meta field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. ```json { "error": "meta_rejected", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "A Meta recusou esta operação. O campo meta traz o que aconteceu, o que fazer e o erro original dela.", "meta": { "codigo": 131030, "categoria": "nao_entregavel", "mensagem": "A Meta recusou o pedido.", "acaoRecomendada": "Confira os campos enviados e tente de novo.", "original": { "error": { "message": "Invalid parameter", "type": "OAuthException", "code": 131030, "fbtrace_id": "AbCdEfGhIjK" } } } } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Unblock a user `DELETE /v1/numbers/{id}/blocked-users/{user}` Unblocks a user, by the phone number or the BSUID in the path. It stays open on a suspended account: unblocking is never the problem. Authentication: API key. Required scope: `messages:write` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | | `user` | `string` | yes | O telefone (só dígitos) ou o BSUID do usuário. | #### Code examples ```bash curl -X DELETE "https://api.lunahia.com.br/v1/numbers/YOUR_ID/blocked-users/YOUR_USER" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "done": [ { "input": "YOUR_INPUT", "waId": "YOUR_WAID", "userId": "YOUR_USERID", "reasons": [ "YOUR_REASONS" ] } ], "failed": [ { "input": "YOUR_INPUT", "waId": "YOUR_WAID", "userId": "YOUR_USERID", "reasons": [ "YOUR_REASONS" ] } ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "number_disconnected", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Este número foi desconectado da Luna e não envia mais. O histórico foi preservado. Para voltar a usá-lo, conecte-o de novo com um link de conexão (POST /v1/onboarding/links)." } ``` **422**: The request is well formed and Luna passed it on, and Meta refused it. The meta field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. ```json { "error": "meta_rejected", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "A Meta recusou esta operação. O campo meta traz o que aconteceu, o que fazer e o erro original dela.", "meta": { "codigo": 131030, "categoria": "nao_entregavel", "mensagem": "A Meta recusou o pedido.", "acaoRecomendada": "Confira os campos enviados e tente de novo.", "original": { "error": { "message": "Invalid parameter", "type": "OAuthException", "code": 131030, "fbtrace_id": "AbCdEfGhIjK" } } } } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### List the QR codes `GET /v1/numbers/{id}/qr-codes` The codes that exist on this number, with each one's short link. Authentication: API key. Required scope: `numbers:read` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers/YOUR_ID/qr-codes" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "code": "4O4YGZEG3RIVE1", "prefilledMessage": "YOUR_PREFILLEDMESSAGE", "link": "https://exemplo.com.br/arquivo", "imageUrl": "YOUR_IMAGEURL" } ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "number_disconnected", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Este número foi desconectado da Luna e não envia mais. O histórico foi preservado. Para voltar a usá-lo, conecte-o de novo com um link de conexão (POST /v1/onboarding/links)." } ``` **422**: The request is well formed and Luna passed it on, and Meta refused it. The meta field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. ```json { "error": "meta_rejected", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "A Meta recusou esta operação. O campo meta traz o que aconteceu, o que fazer e o erro original dela.", "meta": { "codigo": 131030, "categoria": "nao_entregavel", "mensagem": "A Meta recusou o pedido.", "acaoRecomendada": "Confira os campos enviados e tente de novo.", "original": { "error": { "message": "Invalid parameter", "type": "OAuthException", "code": 131030, "fbtrace_id": "AbCdEfGhIjK" } } } } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Create a QR code and a short link `POST /v1/numbers/{id}/qr-codes` Creates a code that opens a conversation with the number, with the message already written. It returns the code, the short link and, if you asked for it, the address of the image. Authentication: API key. Required scope: `numbers:write` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `prefilledMessage` | `string` | yes | A mensagem que já vem escrita. Até 140 caracteres, o limite da Meta, que está a confirmar na doc dela. · 1 to 140 characters | | `imageFormat` | `string` | no | Peça a imagem do QR em PNG ou SVG. Sem isto, só o código e o link voltam. · Values: PNG, SVG | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/numbers/YOUR_ID/qr-codes" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "prefilledMessage": "YOUR_PREFILLEDMESSAGE" }' ``` #### Responses **201**: Created. ```json { "code": "4O4YGZEG3RIVE1", "prefilledMessage": "YOUR_PREFILLEDMESSAGE", "link": "https://exemplo.com.br/arquivo", "imageUrl": "YOUR_IMAGEURL" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "number_disconnected", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Este número foi desconectado da Luna e não envia mais. O histórico foi preservado. Para voltar a usá-lo, conecte-o de novo com um link de conexão (POST /v1/onboarding/links)." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **422**: The request is well formed and Luna passed it on, and Meta refused it. The meta field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. ```json { "error": "meta_rejected", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "A Meta recusou esta operação. O campo meta traz o que aconteceu, o que fazer e o erro original dela.", "meta": { "codigo": 131030, "categoria": "nao_entregavel", "mensagem": "A Meta recusou o pedido.", "acaoRecomendada": "Confira os campos enviados e tente de novo.", "original": { "error": { "message": "Invalid parameter", "type": "OAuthException", "code": 131030, "fbtrace_id": "AbCdEfGhIjK" } } } } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Delete a QR code `DELETE /v1/numbers/{id}/qr-codes/{code}` Deletes the code and the short link: whoever still has the QR printed stops opening the conversation. It stays open on a suspended account. Authentication: API key. Required scope: `numbers:write` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | | `code` | `string` | yes | O código do QR, como a criação o devolveu. | #### Code examples ```bash curl -X DELETE "https://api.lunahia.com.br/v1/numbers/YOUR_ID/qr-codes/YOUR_CODE" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **204**: No content: the operation was done and the response has no body. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "number_disconnected", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Este número foi desconectado da Luna e não envia mais. O histórico foi preservado. Para voltar a usá-lo, conecte-o de novo com um link de conexão (POST /v1/onboarding/links)." } ``` **422**: The request is well formed and Luna passed it on, and Meta refused it. The meta field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. ```json { "error": "meta_rejected", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "A Meta recusou esta operação. O campo meta traz o que aconteceu, o que fazer e o erro original dela.", "meta": { "codigo": 131030, "categoria": "nao_entregavel", "mensagem": "A Meta recusou o pedido.", "acaoRecomendada": "Confira os campos enviados e tente de novo.", "original": { "error": { "message": "Invalid parameter", "type": "OAuthException", "code": 131030, "fbtrace_id": "AbCdEfGhIjK" } } } } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Open a connection session `POST /v1/onboarding/sessions` Creates the session that Meta's connection flow fills in, and returns the sessionId and the csrfState. Authentication: API key. Required scope: `onboarding:write` Topic guide: https://lunahia.com.br/en/docs/connect-a-number#rota-post-v1-onboarding-sessions #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/sessions" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **201**: Created. ```json { "sessionId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "state": "YOUR_STATE", "configId": "YOUR_CONFIGID", "sdkVersion": "YOUR_SDKVERSION", "csrfState": "YOUR_CSRFSTATE", "expiresAt": "YOUR_EXPIRESAT" } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "number_capacity_reached", "message": "Esta conta já tem 20 números ativos, o máximo contratado (20). Para conectar outro, desconecte um número (DELETE /v1/numbers/{id}) ou escreva para contato@lunahia.com.br.", "capacity": 20, "activeNumbers": 20 } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read a connection session `GET /v1/onboarding/sessions/{id}` The session's current state and the matching guidance text, ready to display. Authentication: API key. Required scope: `onboarding:write` Topic guide: https://lunahia.com.br/en/docs/connect-a-number#rota-get-v1-onboarding-sessions-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/onboarding/sessions/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "sessionId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "state": "YOUR_STATE", "orientacao": "YOUR_ORIENTACAO", "terminal": true, "proximoPasso": "YOUR_PROXIMOPASSO", "attemptCount": 1, "nextAttemptAt": "YOUR_NEXTATTEMPTAT", "retryNotBefore": "YOUR_RETRYNOTBEFORE", "expiresAt": "YOUR_EXPIRESAT", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Report an abandoned or failed flow `POST /v1/onboarding/sessions/{id}/abandon` Telemetry about what happened in Meta's window when the flow did not complete: which screen the customer stopped on, or which error Meta reported. Authentication: API key. Required scope: `onboarding:write` Topic guide: https://lunahia.com.br/en/docs/connect-a-number#rota-post-v1-onboarding-sessions-id-abandon #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `csrfState` | `string` | yes | | | `currentStep` | `string \| null` | no | 1 to 120 characters | | `errorCode` | `integer \| null` | no | | | `errorMessage` | `string \| null` | no | | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/sessions/YOUR_ID/abandon" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "csrfState": "YOUR_CSRFSTATE" }' ``` #### Responses **200**: Success. ```json { "sessionId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "state": "YOUR_STATE", "orientacao": "YOUR_ORIENTACAO", "abandonedAtStep": "YOUR_ABANDONEDATSTEP" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Complete the connection `POST /v1/onboarding/sessions/{id}/complete` Exchanges the embedded flow's code for permanent access to the customer's account, and drives the session to the end: sealed token, app subscribed to the account, phone number registered. Authentication: API key. Required scope: `onboarding:write` Topic guide: https://lunahia.com.br/en/docs/connect-a-number#rota-post-v1-onboarding-sessions-id-complete #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `code` | `string` | yes | | | `csrfState` | `string` | yes | | | `wabaId` | `string \| null` | no | | | `phoneNumberId` | `string \| null` | no | | | `businessId` | `string \| null` | no | | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/sessions/YOUR_ID/complete" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "code": "YOUR_CODE", "csrfState": "YOUR_CSRFSTATE" }' ``` #### Responses **200**: Success. ```json { "sessionId": "77012a00-f049-4523-a658-3a3a4b105de6", "state": "APP_SUBSCRIBED", "orientacao": "O número está registrado na Meta e pronto para trocar mensagem.", "terminal": true, "proximoPasso": null, "motivo": null, "podeRetentar": false, "wabaId": "2000000000000001", "phoneNumberId": "1000000000000001" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### List connected phone numbers `GET /v1/numbers` Every WhatsApp number connected to this customer, with state, quality, sending speed and daily conversation limit. Filters: externalId (exact match), q (prefix search over externalId, label and displayNumber), state, wabaId, qualityRating, connectionStatus, ready and canSend. A parameter the route does not know answers 400. Authentication: API key. Required scope: `numbers:read` Topic guide: https://lunahia.com.br/en/docs/plan-and-numbers#rota-get-v1-numbers #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `externalId` | `string` | no | O rótulo que você deu ao seu cliente. Igualdade exata; rótulo sem número devolve lista vazia. | | `state` | `string` | no | O estado do número (state): PENDING, REGISTER_SENT, REGISTERED, PIN_REQUIRED, BLOCKED ou DISCONNECTED. | | `q` | `string` | no | Busca por prefixo, sem diferenciar maiúscula, em externalId, label e displayNumber. Quem digita só o número de telefone acha o número mesmo sem os espaços e o hífen. | | `wabaId` | `string` | no | O id da conta de negócio na Meta (waba.id): só os números dela. Igualdade exata; uma conta sem número seu devolve lista vazia. | | `qualityRating` | `string` | no | A qualidade que a Meta informou para o número (qualityRating): GREEN, YELLOW, RED, NA ou UNKNOWN. Número cuja qualidade a Luna ainda não leu (qualityRating nulo) não entra em nenhum valor. | | `connectionStatus` | `string` | no | Só os números com este connection.status: connected, connecting, action_required ou disconnected. | | `ready` | `string` | no | true: só os números prontos para enviar e receber. false: só os que ainda não estão. | | `canSend` | `string` | no | true: só os números por onde enviar funciona agora (connection.canSend). false: só os que não. | | `limit` | `integer` | no | Quantos números por página: de 1 a 100, 50 se omitido. | | `cursor` | `string` | no | O nextCursor da resposta anterior. Opaco: carrega posição, não contagem. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "metaPhoneNumberId": "YOUR_METAPHONENUMBERID", "displayNumber": "YOUR_DISPLAYNUMBER", "state": "YOUR_STATE", "retryNotBefore": "YOUR_RETRYNOTBEFORE", "podeRetentar": true, "qualityRating": "YOUR_QUALITYRATING", "throughputLevel": "YOUR_THROUGHPUTLEVEL", "limiteDiarioDeConversas": "YOUR_LIMITEDIARIODECONVERSAS", "codeVerificationStatus": "YOUR_CODEVERIFICATIONSTATUS", "displayName": "YOUR_DISPLAYNAME", "displayNameStatus": "YOUR_DISPLAYNAMESTATUS", "pendingDisplayName": "YOUR_PENDINGDISPLAYNAME", "autoRead": true, "externalId": "YOUR_EXTERNALID", "label": "YOUR_LABEL", "orientacao": "YOUR_ORIENTACAO", "awaitingPaymentSince": "YOUR_AWAITINGPAYMENTSINCE", "waba": { "id": "YOUR_ID", "restricted": true, "disabled": true, "credentialExpiresAt": "YOUR_CREDENTIALEXPIRESAT", "credentialNeverExpires": true, "paymentMethodOnMeta": true, "currency": "YOUR_CURRENCY" }, "ready": true, "connection": { "status": "connected", "canSend": true, "reasons": [ { "code": "YOUR_CODE", "message": "YOUR_MESSAGE", "solution": "YOUR_SOLUTION", "action": "send_pin", "actionUrl": null, "docsUrl": null, "since": null } ] }, "allowedActions": [ "disconnect" ], "blockedActions": [ { "action": "disconnect", "message": "YOUR_MESSAGE" } ], "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT" } ], "nextCursor": "YOUR_NEXTCURSOR" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read one phone number `GET /v1/numbers/{id}` One number, with everything the listing carries plus the health of its connection to Meta. Authentication: API key. Required scope: `numbers:read` Topic guide: https://lunahia.com.br/en/docs/plan-and-numbers#rota-get-v1-numbers-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "id": "ed404df1-b420-4ed6-8743-ba1609892e0a", "metaPhoneNumberId": "1000000000000001", "displayNumber": "+55 11 90000-0000", "state": "REGISTERED", "retryNotBefore": null, "podeRetentar": false, "qualityRating": "GREEN", "throughputLevel": "STANDARD", "limiteDiarioDeConversas": "TIER_10K", "codeVerificationStatus": "VERIFIED", "displayName": "Clínica Sorriso", "displayNameStatus": "approved", "pendingDisplayName": null, "autoRead": false, "externalId": "cliente-8841", "label": "Atendimento Pinheiros", "orientacao": "Número conectado e operando. Mensagens já entram e saem por ele.", "awaitingPaymentSince": null, "waba": { "id": "102290129340398", "restricted": false, "disabled": false, "credentialExpiresAt": null, "credentialNeverExpires": true, "paymentMethodOnMeta": true, "currency": "BRL" }, "ready": true, "connection": { "status": "connected", "canSend": true, "reasons": [], "steps": [ { "key": "authorized", "label": "Autorização do negócio", "status": "done" }, { "key": "receiving", "label": "Recebimento das mensagens", "status": "done" }, { "key": "registered", "label": "Número registrado", "status": "done" }, { "key": "ready", "label": "Pronto para usar", "status": "done" } ] }, "allowedActions": [ "disconnect", "edit_label" ], "blockedActions": [], "createdAt": "2026-08-07T11:28:14.597Z", "updatedAt": "2026-08-07T11:28:28.703Z", "tetoDeVazaoPorSegundo": null, "sincronizacaoDoHistorico": null, "sincronizacaoPrazo": null, "sincronizacaoProgresso": null, "subscriptionConfirmedAt": "2026-08-07T11:27:47.141Z", "credentialStatus": "active", "podeReconectar": false, "coexistence": false } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Edit a number `PATCH /v1/numbers/{id}` Changes a number's externalId and label, and turns autoRead (mark every received message as read on its own) on or off. It is how you reuse a number for another customer of yours, or name a number that was connected through the console, without a link. Authentication: API key. Required scope: `numbers:write` Topic guide: https://lunahia.com.br/en/docs/plan-and-numbers#rota-patch-v1-numbers-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `externalId` | `string \| null` | no | O seu identificador para o cliente dono do número (1 a 128 caracteres). null limpa. · 1 to 128 characters | | `label` | `string \| null` | no | Um nome livre e curto para reconhecer o número (1 a 128 caracteres). null limpa. · 1 to 128 characters | | `autoRead` | `boolean` | no | true: a Luna marca como lida, na Meta, cada mensagem que o número receber daqui em diante, sem indicador de digitando. false desliga. Ausente não muda. O padrão de um número é false. | #### Code examples ```bash curl -X PATCH "https://api.lunahia.com.br/v1/numbers/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "externalId": "YOUR_EXTERNALID", "label": "YOUR_LABEL", "autoRead": true }' ``` #### Responses **200**: Success. ```json { "id": "ed404df1-b420-4ed6-8743-ba1609892e0a", "metaPhoneNumberId": "1000000000000001", "displayNumber": "+55 11 90000-0000", "state": "REGISTERED", "retryNotBefore": null, "podeRetentar": false, "qualityRating": "GREEN", "throughputLevel": "STANDARD", "limiteDiarioDeConversas": "TIER_10K", "codeVerificationStatus": "VERIFIED", "displayName": "Clínica Sorriso", "displayNameStatus": "approved", "pendingDisplayName": null, "autoRead": false, "externalId": "cliente-8841", "label": "Atendimento Pinheiros", "orientacao": "Número conectado e operando. Mensagens já entram e saem por ele.", "awaitingPaymentSince": null, "waba": { "id": "102290129340398", "restricted": false, "disabled": false, "credentialExpiresAt": null, "credentialNeverExpires": true, "paymentMethodOnMeta": true, "currency": "BRL" }, "ready": true, "connection": { "status": "connected", "canSend": true, "reasons": [], "steps": [ { "key": "authorized", "label": "Autorização do negócio", "status": "done" }, { "key": "receiving", "label": "Recebimento das mensagens", "status": "done" }, { "key": "registered", "label": "Número registrado", "status": "done" }, { "key": "ready", "label": "Pronto para usar", "status": "done" } ] }, "allowedActions": [ "disconnect", "edit_label" ], "blockedActions": [], "createdAt": "2026-08-07T11:28:14.597Z", "updatedAt": "2026-08-07T11:28:28.703Z", "tetoDeVazaoPorSegundo": null, "sincronizacaoDoHistorico": null, "sincronizacaoPrazo": null, "sincronizacaoProgresso": null, "subscriptionConfirmedAt": "2026-08-07T11:27:47.141Z", "credentialStatus": "active", "podeReconectar": false, "coexistence": false } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Disconnect a number `DELETE /v1/numbers/{id}` Takes the number off Luna. It is how you open a slot in the plan capacity: the number stops counting from this instant, and your customer can be swapped for another. Authentication: API key. Required scope: `numbers:write` Topic guide: https://lunahia.com.br/en/docs/plan-and-numbers#rota-delete-v1-numbers-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Code examples ```bash curl -X DELETE "https://api.lunahia.com.br/v1/numbers/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **204**: No content: the operation was done and the response has no body. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Give a number's two step verification PIN `POST /v1/numbers/{id}/pin` Gives the two step verification PIN of a number that is already registered on another provider's Cloud API, so Luna can register it without the end business having to turn verification off. Authentication: API key. Required scope: `onboarding:write` Topic guide: https://lunahia.com.br/en/docs/connect-a-number#rota-post-v1-numbers-id-pin #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `pin` | `string` | yes | O PIN de verificação em duas etapas deste número, com exatamente seis dígitos. Quando o número já tem verificação em duas etapas configurada em outro provedor, é o PIN existente dele, e apenas o negócio final o conhece: não existe endpoint para ler nem para desligar o PIN de um número. Quando o número não tem verificação em duas etapas, este valor passa a ser o PIN dele. · /^\d{6}$/ | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/numbers/YOUR_ID/pin" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "pin": "YOUR_PIN" }' ``` #### Responses **200**: Success. ```json { "id": "ed404df1-b420-4ed6-8743-ba1609892e0a", "state": "PENDING" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "pin_not_applicable", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Este número não está aguardando o PIN de verificação em duas etapas. O campo state diz em que ponto ele está." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Reconnect a number whose authorisation died `POST /v1/onboarding/reconnect` Opens a connection session for a number that already exists, when the authorisation granted by the customer expired or was revoked. Authentication: API key. Required scope: `onboarding:write` Topic guide: https://lunahia.com.br/en/docs/connect-a-number#rota-post-v1-onboarding-reconnect #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `numberId` | `string` | yes | O número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/reconnect" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "numberId": "YOUR_NUMBERID" }' ``` #### Responses **201**: Created. ```json { "sessionId": "77012a00-f049-4523-a658-3a3a4b105de6", "state": "STARTED", "configId": "1234567890", "sdkVersion": "v26.0", "csrfState": "Xk3s...", "expiresAt": "2026-08-26T18:30:00.000Z" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "reconnect_not_applicable", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "A autorização deste número não admite reconexão.", "credentialStatus": "active" } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### List business accounts `GET /v1/business-accounts` The WhatsApp Business accounts this customer has connected, newest first, each with its name at Meta, its WhatsApp Manager address and its numbers. Authentication: API key. Required scope: `numbers:read` Topic guide: https://lunahia.com.br/en/docs/connect-a-number#rota-get-v1-business-accounts #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/business-accounts" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "id": "ed404df1-b420-4ed6-8743-ba1609892e0a", "wabaId": "102290129340398", "numbers": [ "+55 11 90000-0000" ], "name": "Padaria do Zé", "managerUrl": "https://business.facebook.com/latest/whatsapp_manager/overview?asset_id=102290129340398", "phoneNumbers": [ { "id": "a3c1f5b2-7d4e-4b8a-9c21-5e6f7a8b9c0d", "displayNumber": "+55 11 90000-0000", "externalId": "cliente-8841", "label": "Atendimento Pinheiros" } ], "status": { "restricted": false, "restrictions": [], "disabled": false, "violationType": null, "reportedAt": null }, "credentialExpiresAt": null, "credentialNeverExpires": true, "paymentMethodOnMeta": true, "currency": "BRL", "createdAt": "2026-08-07T11:27:41.208Z" } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Check the account payment method at Meta now `POST /v1/business-accounts/{id}/payment-method/check` Reads from Meta whether the account has a payment method on file, without waiting for the hourly read, and returns the result. The webhook notice follows the usual path: number.action_required (reason payment_method_missing) when it is missing and number.action_resolved when it shows up. A read newer than 60 seconds is returned without calling Meta, and the call respects the account call budget. Authentication: API key. Required scope: `numbers:read` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O id da conta de negócio na Luna, o mesmo que GET /v1/business-accounts devolve em id. | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/business-accounts/YOUR_ID/payment-method/check" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "id": "ed404df1-b420-4ed6-8743-ba1609892e0a", "wabaId": "102290129340398", "paymentMethodOnMeta": false, "currency": "BRL", "checkedAt": "2026-11-05T14:02:11.000Z", "refreshed": true, "reason": "checked" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read the health of a phone number `GET /v1/numbers/{id}/health` The quality rating, throughput level and daily conversation limit Meta assigns to this number right now, and the changes the platform has observed over time. Authentication: API key. Required scope: `numbers:read` Topic guide: https://lunahia.com.br/en/docs/account-health#rota-get-v1-numbers-id-health #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do número: o UUID da Luna (o id que GET /v1/numbers devolve) ou o id da Meta (metaPhoneNumberId). Os dois valem. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/numbers/YOUR_ID/health" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "qualityRating": "GREEN", "throughputLevel": "HIGH", "tetoDeVazaoPorSegundo": null, "sincronizacaoDoHistorico": "em_curso", "sincronizacaoPrazo": "2026-09-19T09:00:00.000Z", "sincronizacaoProgresso": 40, "limiteDiarioDeConversas": "TIER_10K", "codeVerificationStatus": "VERIFIED", "checkedAt": "2026-08-26T12:00:00.000Z", "transitions": [ { "qualityRating": "GREEN", "throughputLevel": "HIGH", "limiteDiarioDeConversas": "TIER_2K", "codeVerificationStatus": "VERIFIED", "observedAt": "2026-08-24T10:00:00.000Z" } ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read the Meta usage of a number or a customer `GET /v1/usage` The usage Meta measures for a number (numberId) or for all the numbers of one of your customers (externalId), passed through as Meta reports it, with each account's currency and no sums. format=csv returns text/csv. Luna only reads and shows it: none of it goes into the Luna subscription. Authentication: API key. Required scope: `numbers:read` #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `numberId` | `string` | no | O número a consultar: o UUID da Luna (o id de GET /v1/numbers) ou o id da Meta (metaPhoneNumberId). Os dois valem. Mande este ou externalId, nunca os dois. | | `externalId` | `string` | no | O rótulo do seu cliente (o externalId do link de conexão): lê o consumo de todos os números dele, cada um na moeda da conta dele. Mande este ou numberId, nunca os dois. | | `start` | `any` | no | O começo do período, em ISO 8601 (data ou data e hora, em UTC). Ausente, o primeiro dia do mês corrente. | | `end` | `any` | no | O fim do período, em ISO 8601. Ausente, agora (arredondado para baixo a cada cinco minutos). | | `granularity` | `string` | no | O tamanho de cada ponto, no vocabulário da Meta: HALF_HOUR, DAILY (o padrão) ou MONTHLY. A Meta limita o período de cada um, e recusa o que passa do limite dela. | | `format` | `string` | no | json (o padrão) ou csv. O csv vem em text/csv, uma linha por ponto, com numberId, phoneNumberId e currency em cada linha, para planilha. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/usage" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "numberId": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phoneNumberId": "123456789012345", "externalId": null, "start": "2026-11-01T00:00:00.000Z", "end": "2026-11-03T15:00:00.000Z", "granularity": "DAILY", "readAt": "2026-11-03T15:00:12.000Z", "notice": "Valores aproximados, como a Meta os informa, na moeda da conta do negócio na Meta. A Meta cobra o uso do WhatsApp direto do negócio dono do número, e a fatura dela é a referência: este consumo pode divergir dela. A Luna só repassa a leitura, e nada daqui entra na assinatura da Luna.", "numbers": [ { "numberId": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phoneNumberId": "123456789012345", "currency": "BRL", "read": true, "reason": null } ], "data": [ { "numberId": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phoneNumberId": "123456789012345", "currency": "BRL", "start": "2026-11-02T03:00:00.000Z", "end": "2026-11-03T03:00:00.000Z", "pricingCategory": "UTILITY", "pricingType": "REGULAR", "tier": null, "country": "BR", "volume": 12, "cost": 0.5 } ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "number_disconnected", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Este número foi desconectado da Luna e não envia mais. O histórico foi preservado. Para voltar a usá-lo, conecte-o de novo com um link de conexão (POST /v1/onboarding/links)." } ``` **422**: The request is well formed and Luna passed it on, and Meta refused it. The meta field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. ```json { "error": "meta_rejected", "docsUrl": "https://lunahia.com.br/docs/numero-na-meta", "message": "A Meta recusou esta operação. O campo meta traz o que aconteceu, o que fazer e o erro original dela.", "meta": { "codigo": 131030, "categoria": "nao_entregavel", "mensagem": "A Meta recusou o pedido.", "acaoRecomendada": "Confira os campos enviados e tente de novo.", "original": { "error": { "message": "Invalid parameter", "type": "OAuthException", "code": 131030, "fbtrace_id": "AbCdEfGhIjK" } } } } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ## Connection links A link your customer opens to connect their WhatsApp number, without receiving your console login. One link per customer of yours, tied to the externalId you chose. ### List connect links `GET /v1/onboarding/links` The links you created, newest first, revoked ones included. Filters: externalId (exact), q (start of the externalId) and status (open, used, expired or revoked). Authentication: API key. Required scope: `numbers:read` Topic guide: https://lunahia.com.br/en/docs/saas-with-n-customers#rota-get-v1-onboarding-links #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `q` | `string` | no | O começo do rótulo do seu cliente: os links cujo externalId começa com este texto, sem diferenciar maiúscula. Use no lugar de externalId quando você só lembra do começo. Combina com os outros filtros. | | `externalId` | `string` | no | O rótulo que você deu ao seu cliente (externalId): só os links dele. Igualdade exata; um rótulo sem link devolve lista vazia. | | `status` | `string` | no | Só os links neste estado: open, used, expired ou revoked. | | `limit` | `integer` | no | | | `cursor` | `string` | no | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/onboarding/links" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "externalId": "YOUR_EXTERNALID", "status": "open", "createdAt": "YOUR_CREATEDAT", "purpose": "new", "revokedAt": "YOUR_REVOKEDAT", "lastFailure": { "step": "YOUR_STEP", "reason": "YOUR_REASON", "at": "YOUR_AT" }, "allowedActions": [ "revoke" ], "expiresAt": "YOUR_EXPIRESAT", "usedAt": "YOUR_USEDAT", "redirectUrl": "YOUR_REDIRECTURL", "displayName": "YOUR_DISPLAYNAME", "numberId": "3fa85f64-5717-4562-b3fc-2c963f66afa6" } ], "nextCursor": "YOUR_NEXTCURSOR" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Create a connect link for your customer `POST /v1/onboarding/links` Creates a link your customer opens to connect their own WhatsApp number, without being given your console login. Authentication: API key. Required scope: `onboarding:write` Topic guide: https://lunahia.com.br/en/docs/saas-with-n-customers#rota-post-v1-onboarding-links #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `externalId` | `string` | no | O seu identificador para este cliente, em texto livre de 1 a 128 caracteres. A Luna não o interpreta: ele volta como externalId no link e no número que resultar da conexão. · 1 to 128 characters | | `displayName` | `string` | no | O nome do seu cliente, em texto livre de 1 a 120 caracteres, que a página do link mostra ("Conectar o WhatsApp de ..."). Serve para o cliente reconhecer de quem é o pedido. É só texto da página: a janela da Meta que abre em seguida mostra o nome da Luna e não pode ser mudada. · 1 to 120 characters | | `redirectUrl` | `string` | no | Para onde a página do link leva o seu cliente quando a conexão termina (https, até 2048 caracteres). A página acrescenta status (o estado final da conexão) e numberId (o número, quando a Luna já o registrou) na query. Ausente, o cliente fica na página da Luna. · up to 2048 characters · /^https:\/\/[^\s]+$/ | | `numberId` | `string` | no | O número a reconectar: o UUID da Luna (o id de GET /v1/numbers) ou o id da Meta (metaPhoneNumberId). Com ele, o link abre a reconexão daquele número em vez de uma conexão nova. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/links" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "externalId": "YOUR_EXTERNALID", "displayName": "YOUR_DISPLAYNAME", "redirectUrl": "YOUR_REDIRECTURL" }' ``` #### Responses **201**: Created. ```json { "id": "5b8a0e0e-9a1f-4d1c-8d27-2f0c5f3a7d10", "url": "https://app.lunahia.com.br/conectar/0f2c8e6a-1d3b-4a5c-9e7f-2b4d6a8c0e12.k3JrYq1w2hX9s0Zt4uVb7nLmP5dQe8aRfG6yTcIoWxU", "expiresAt": "2026-10-10T14:00:00.000Z", "externalId": "cliente-8841", "redirectUrl": "https://app.exemplo.com.br/whatsapp/conectado", "displayName": "Escritório Silva & Filhos" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "number_capacity_reached", "message": "Esta conta já tem 20 números ativos, o máximo contratado (20). Para conectar outro, desconecte um número (DELETE /v1/numbers/{id}) ou escreva para contato@lunahia.com.br.", "capacity": 20, "activeNumbers": 20 } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read a connect link `GET /v1/onboarding/links/{id}` A link's state: open, used, expired or revoked, with its purpose, its last failure and what the account can do with it. Authentication: API key. Required scope: `numbers:read` Topic guide: https://lunahia.com.br/en/docs/saas-with-n-customers#rota-get-v1-onboarding-links-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/onboarding/links/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "externalId": "YOUR_EXTERNALID", "status": "open", "createdAt": "YOUR_CREATEDAT", "purpose": "new", "revokedAt": "YOUR_REVOKEDAT", "lastFailure": { "step": "YOUR_STEP", "reason": "YOUR_REASON", "at": "YOUR_AT" }, "allowedActions": [ "revoke" ], "expiresAt": "YOUR_EXPIRESAT", "usedAt": "YOUR_USEDAT", "redirectUrl": "YOUR_REDIRECTURL", "displayName": "YOUR_DISPLAYNAME", "numberId": "3fa85f64-5717-4562-b3fc-2c963f66afa6" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Revoke a connect link `DELETE /v1/onboarding/links/{id}` Revokes the link. The url stops working at once and answers 404 to whoever opens it, like one that never existed. A connection the customer had already started in Meta's window can no longer be completed through it. The link stays in your list, with status revoked and revokedAt. Revoking an already revoked link answers 404. Authentication: API key. Required scope: `onboarding:write` Topic guide: https://lunahia.com.br/en/docs/saas-with-n-customers#rota-delete-v1-onboarding-links-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Code examples ```bash curl -X DELETE "https://api.lunahia.com.br/v1/onboarding/links/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **204**: No content: the operation was done and the response has no body. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Create several connect links at once `POST /v1/onboarding/links/batch` Creates up to 100 links, each item in the same shape as POST /v1/onboarding/links and under the same rules, plan capacity included. Answers 200 with one result per item, with the url of each created link; an item that fails does not bring the others down. Authentication: API key. Required scope: `onboarding:write` #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `links` | `array` | yes | De 1 a 100 links, cada um no mesmo formato do corpo de POST /v1/onboarding/links: externalId, displayName, redirectUrl e numberId, todos opcionais. · 1 to 100 items | | `links[].externalId` | `string` | no | O seu identificador para este cliente, em texto livre de 1 a 128 caracteres. A Luna não o interpreta: ele volta como externalId no link e no número que resultar da conexão. · 1 to 128 characters | | `links[].displayName` | `string` | no | O nome do seu cliente, em texto livre de 1 a 120 caracteres, que a página do link mostra ("Conectar o WhatsApp de ..."). Serve para o cliente reconhecer de quem é o pedido. É só texto da página: a janela da Meta que abre em seguida mostra o nome da Luna e não pode ser mudada. · 1 to 120 characters | | `links[].redirectUrl` | `string` | no | Para onde a página do link leva o seu cliente quando a conexão termina (https, até 2048 caracteres). A página acrescenta status (o estado final da conexão) e numberId (o número, quando a Luna já o registrou) na query. Ausente, o cliente fica na página da Luna. · up to 2048 characters · /^https:\/\/[^\s]+$/ | | `links[].numberId` | `string` | no | O número a reconectar: o UUID da Luna (o id de GET /v1/numbers) ou o id da Meta (metaPhoneNumberId). Com ele, o link abre a reconexão daquele número em vez de uma conexão nova. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/links/batch" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "links": [ { "externalId": "YOUR_EXTERNALID", "displayName": "YOUR_DISPLAYNAME", "redirectUrl": "YOUR_REDIRECTURL" } ] }' ``` #### Responses **200**: Success. ```json { "results": [ { "index": 1, "status": 1, "link": { "id": "5b8a0e0e-9a1f-4d1c-8d27-2f0c5f3a7d10", "url": "https://app.lunahia.com.br/conectar/0f2c8e6a-1d3b-4a5c-9e7f-2b4d6a8c0e12.k3JrYq1w2hX9s0Zt4uVb7nLmP5dQe8aRfG6yTcIoWxU", "expiresAt": "2026-10-10T14:00:00.000Z", "externalId": "cliente-8841", "redirectUrl": "https://app.exemplo.com.br/whatsapp/conectado", "displayName": "Escritório Silva & Filhos" }, "error": { "error": "YOUR_ERROR", "message": "YOUR_MESSAGE" } } ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Generate the url of a connect link again `POST /v1/onboarding/links/{id}/reissue` Generates a new token for the same link (same id, label and expiry): the old url stops working at once and the new one appears only in this response. Only for an open link; used, expired or revoked answers 409. Use it when your customer lost the url, instead of revoking and creating another. Authentication: API key. Required scope: `onboarding:write` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/onboarding/links/YOUR_ID/reissue" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "id": "5b8a0e0e-9a1f-4d1c-8d27-2f0c5f3a7d10", "url": "https://app.lunahia.com.br/conectar/0f2c8e6a-1d3b-4a5c-9e7f-2b4d6a8c0e12.k3JrYq1w2hX9s0Zt4uVb7nLmP5dQe8aRfG6yTcIoWxU", "expiresAt": "2026-10-10T14:00:00.000Z", "externalId": "cliente-8841", "redirectUrl": "https://app.exemplo.com.br/whatsapp/conectado", "displayName": "Escritório Silva & Filhos" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "link_not_open", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Só um link aberto pode ser reemitido, e este está usado. Crie um link novo com POST /v1/onboarding/links.", "status": "used" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ## Webhooks and events Where Luna delivers what arrives at your number, the secret that signs those deliveries, and the event types, each with its schema and an example. ### List webhook endpoints `GET /v1/webhooks/endpoints` The endpoints registered for this customer, newest first, with the endpoint limit and whether another can still be registered (limit and canCreate). Each endpoint carries deliveryStatus. Authentication: API key. Required scope: `webhooks:read` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-get-v1-webhooks-endpoints #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/webhooks/endpoints" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Os endpoints cadastrados neste cliente, do mais recente para o mais antigo, com o limite de endpoints e se ainda dá para cadastrar outro (limit e canCreate). ```json { "data": [ { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "url": "https://exemplo.com.br/arquivo", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT", "previousSecretExpiresAt": "YOUR_PREVIOUSSECRETEXPIRESAT", "paused": true, "pausedAt": "YOUR_PAUSEDAT", "eventTypes": [ "YOUR_EVENTTYPES" ], "externalIds": [ "YOUR_EXTERNALIDS" ], "phoneNumberIds": [ "YOUR_PHONENUMBERIDS" ], "headerNames": [ "YOUR_HEADERNAMES" ], "lastDeliveryAt": "YOUR_LASTDELIVERYAT", "lastFailureAt": "YOUR_LASTFAILUREAT", "lastHttpStatus": 1, "deliveryStatus": "ok" } ], "limit": 1, "canCreate": true } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Register the webhook endpoint `POST /v1/webhooks/endpoints` Registers your server's URL and returns the secret that signs the deliveries. headers, optional, carries up to 5 own HTTP headers that Luna sends on every delivery (for a gateway that requires a fixed token); the values are secret and no response returns them. Authentication: API key. Required scope: `webhooks:write` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-post-v1-webhooks-endpoints #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `url` | `string` | yes | A URL do seu servidor que vai receber os eventos. Precisa ser https e precisa resolver para um endereço público. · up to 2048 characters | | `eventTypes` | `array` | no | Os tipos de evento que este endpoint recebe, por exemplo ["message.received", "message.status"]. Ausente ou vazio quer dizer todos, inclusive os tipos que a Luna criar depois. Com a lista preenchida, o endpoint só recebe esses tipos, e um tipo novo não chega até você incluí-lo. O filtro é só por tipo. O evento webhook.test não é filtrável: ele só sai quando você o pede. Os tipos estão no guia Receber eventos. · up to 30 items | | `externalIds` | `array` | no | Os clientes seus (externalId) de que este endpoint recebe eventos, por exemplo ["cliente-42"]. Ausente ou vazio quer dizer todos. Com a lista preenchida, o endpoint só recebe eventos de números com um destes externalId, inclusive os conectados depois, e dos links de conexão com ele. Eventos que não falam de um cliente (os de template, por exemplo) só chegam se a conta do template tem um número dele. O filtro é só por identificador. · up to 100 items | | `phoneNumberIds` | `array` | no | Os números de que este endpoint recebe eventos: o UUID da Luna (o id de GET /v1/numbers) ou o id da Meta (metaPhoneNumberId), em qualquer mistura. A resposta devolve os ids da Meta, os mesmos que os eventos trazem em phone_number_id. Ausente ou vazio quer dizer todos. Um número que não é da conta responde 400. Para cobrir números que ainda serão conectados, use externalIds. · up to 100 items | | `headers` | `object` | no | Cabeçalhos HTTP que a Luna envia em cada entrega a este endpoint, como { "X-Token": "valor" }, até 5. Para quem tem um gateway que exige um token fixo. Os valores são segredo: ficam cifrados, e nenhuma resposta os devolve, só os nomes (headerNames). Não valem os de transporte (content-type, host, content-length e afins) nem os x-luna-*. O valor tem até 1024 caracteres ASCII visíveis. No PATCH, o objeto enviado substitui o anterior, e {} remove todos. | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://exemplo.com.br/arquivo" }' ``` #### Responses **201**: O endpoint recém-criado, com o segredo de assinatura. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "url": "https://exemplo.com.br/arquivo", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT", "previousSecretExpiresAt": "YOUR_PREVIOUSSECRETEXPIRESAT", "paused": true, "pausedAt": "YOUR_PAUSEDAT", "eventTypes": [ "YOUR_EVENTTYPES" ], "externalIds": [ "YOUR_EXTERNALIDS" ], "phoneNumberIds": [ "YOUR_PHONENUMBERIDS" ], "headerNames": [ "YOUR_HEADERNAMES" ], "lastDeliveryAt": "YOUR_LASTDELIVERYAT", "lastFailureAt": "YOUR_LASTFAILUREAT", "lastHttpStatus": 1, "deliveryStatus": "ok", "secret": "YOUR_SECRET" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "webhook_endpoint_limit", "docsUrl": "https://lunahia.com.br/docs/receber-eventos", "message": "Este cliente já tem o máximo de endpoints de webhook, e o limite é o mesmo para todos. Remova um endpoint com DELETE /v1/webhooks/endpoints/{id} para liberar a vaga.", "limit": 25 } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### List the event types `GET /v1/webhooks/event-types` The event types Luna delivers, which eventTypes accepts when you register or update an endpoint. Each item carries the type, which is the value to send, a sentence that says what the event is, and the group it belongs to (group and groupLabel). Authentication: API key. Required scope: `webhooks:read` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-get-v1-webhooks-event-types #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/webhooks/event-types" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Os tipos de evento que a Luna entrega, na ordem do contrato. O evento webhook.test não está na lista: ele só sai quando você o pede. ```json { "data": [ { "type": "YOUR_TYPE", "summary": "YOUR_SUMMARY", "group": "messages", "groupLabel": "YOUR_GROUPLABEL" } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read the webhook endpoint `GET /v1/webhooks/endpoints/{id}` The endpoint's configuration. Authentication: API key. Required scope: `webhooks:read` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-get-v1-webhooks-endpoints-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: A configuração do endpoint. O segredo NÃO vem aqui: ele sai uma vez, no cadastro e na rotação. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "url": "https://exemplo.com.br/arquivo", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT", "previousSecretExpiresAt": "YOUR_PREVIOUSSECRETEXPIRESAT", "paused": true, "pausedAt": "YOUR_PAUSEDAT", "eventTypes": [ "YOUR_EVENTTYPES" ], "externalIds": [ "YOUR_EXTERNALIDS" ], "phoneNumberIds": [ "YOUR_PHONENUMBERIDS" ], "headerNames": [ "YOUR_HEADERNAMES" ], "lastDeliveryAt": "YOUR_LASTDELIVERYAT", "lastFailureAt": "YOUR_LASTFAILUREAT", "lastHttpStatus": 1, "deliveryStatus": "ok" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Update the webhook endpoint `PATCH /v1/webhooks/endpoints/{id}` Changes the URL, pauses or resumes the endpoint, or changes the event types it receives. Send url, paused, eventTypes, externalIds, phoneNumberIds, headers or any combination: a body with none of them answers 400. Authentication: API key. Required scope: `webhooks:write` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-patch-v1-webhooks-endpoints-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `url` | `string` | no | A URL nova. Passa pela mesma validação do cadastro: https e endereço público. O segredo de assinatura continua o mesmo. · up to 2048 characters | | `paused` | `boolean` | no | true pausa o endpoint: os eventos que ocorrerem enquanto ele estiver pausado não são entregues, nem depois. false o retoma, e ele passa a receber os eventos a partir desse momento. | | `eventTypes` | `array` | no | Troca a lista de tipos que o endpoint recebe: a lista enviada substitui a anterior. Lista vazia volta a receber todos. O que ocorreu antes da troca e foi filtrado não é entregue depois. · up to 30 items | | `externalIds` | `array` | no | Troca a lista de clientes de que o endpoint recebe eventos: a lista enviada substitui a anterior, e lista vazia volta a receber de todos. Vale daí em diante. · up to 100 items | | `phoneNumberIds` | `array` | no | Troca a lista de números de que o endpoint recebe eventos: a lista enviada substitui a anterior, e lista vazia volta a receber de todos. Aceita o UUID da Luna ou o id da Meta. · up to 100 items | | `headers` | `object` | no | Cabeçalhos HTTP que a Luna envia em cada entrega a este endpoint, como { "X-Token": "valor" }, até 5. Para quem tem um gateway que exige um token fixo. Os valores são segredo: ficam cifrados, e nenhuma resposta os devolve, só os nomes (headerNames). Não valem os de transporte (content-type, host, content-length e afins) nem os x-luna-*. O valor tem até 1024 caracteres ASCII visíveis. No PATCH, o objeto enviado substitui o anterior, e {} remove todos. | #### Code examples ```bash curl -X PATCH "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://exemplo.com.br/arquivo", "paused": true, "eventTypes": [ "message.received" ] }' ``` #### Responses **200**: A configuração do endpoint. O segredo NÃO vem aqui: ele sai uma vez, no cadastro e na rotação. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "url": "https://exemplo.com.br/arquivo", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT", "previousSecretExpiresAt": "YOUR_PREVIOUSSECRETEXPIRESAT", "paused": true, "pausedAt": "YOUR_PAUSEDAT", "eventTypes": [ "YOUR_EVENTTYPES" ], "externalIds": [ "YOUR_EXTERNALIDS" ], "phoneNumberIds": [ "YOUR_PHONENUMBERIDS" ], "headerNames": [ "YOUR_HEADERNAMES" ], "lastDeliveryAt": "YOUR_LASTDELIVERYAT", "lastFailureAt": "YOUR_LASTFAILUREAT", "lastHttpStatus": 1, "deliveryStatus": "ok" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Remove the webhook endpoint `DELETE /v1/webhooks/endpoints/{id}` Removes the endpoint. The response is 204, and the endpoint stops receiving events. Authentication: API key. Required scope: `webhooks:write` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-delete-v1-webhooks-endpoints-id #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. | #### Code examples ```bash curl -X DELETE "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **204**: No content: the operation was done and the response has no body. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### List the endpoint's deliveries `GET /v1/webhooks/endpoints/{id}/deliveries` The delivery attempts to the endpoint over the last 7 days, newest first: eventId, eventType, status, httpStatus (null when your server did not answer), durationMs, attempt and at. Filters: status (success or failed), eventType and since. It does not carry the body sent or what your server answered. Authentication: API key. Required scope: `webhooks:read` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-get-v1-webhooks-endpoints-id-deliveries #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. | #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `limit` | `integer` | no | Quantos itens trazer. Padrão 50, máximo 100, igual para todos. | | `status` | `string` | no | success: só as tentativas que o seu servidor aceitou (2xx). failed: só as que falharam, com outro status ou sem resposta. | | `eventType` | `string` | no | Só as tentativas de eventos deste tipo (um valor de GET /v1/webhooks/event-types). | | `since` | `any` | no | Só as tentativas deste instante em diante (ISO 8601, ou a data pura, que vale meia-noite UTC). O histórico guarda 7 dias. | | `cursor` | `string` | no | O nextCursor da página anterior. Omita na primeira. | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID/deliveries" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: O histórico de entregas do endpoint nos últimos 7 dias, uma linha por tentativa. Não traz o corpo enviado nem o que o seu servidor respondeu: só o status. ```json { "data": [ { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "eventId": "YOUR_EVENTID", "eventType": "YOUR_EVENTTYPE", "status": "success", "httpStatus": 1, "durationMs": 1, "attempt": 1, "at": "YOUR_AT" } ], "nextCursor": "YOUR_NEXTCURSOR" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Send a test event `POST /v1/webhooks/endpoints/{id}/test` Sends ONE webhook.test event to the endpoint, now, and returns the result in the response itself. The event goes out signed, with the same headers, the same signature and the same destination defenses as a real delivery, so a test that passes proves that the URL and signature verification work. With eventType in the body, the event is an example of that type, with a made-up body and test: true in the envelope. Authentication: API key. Required scope: `webhooks:write` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-post-v1-webhooks-endpoints-id-test #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `eventType` | `string` | no | Um tipo de GET /v1/webhooks/event-types. A Luna entrega ao endpoint um exemplo desse tipo, com corpo de mentira (identificadores que não existem) e test: true no envelope, para você exercitar o seu código sem esperar o evento de verdade. Ausente, o teste é o webhook.test de sempre. O exemplo não passa por nenhum número seu. · Values: message.received, message.status, contact.identity_changed, contact.preferences_changed, backlog.dropped, history_sync.deadline_approaching, message.echo, template.status, number.connected, number.payment_required, number.payment_resolved, account.restricted, account.violation, account.disabled, account.reinstated, account.update, account.limit_changed, number.disconnected, number.quality_changed, number.display_name_reviewed, number.credential_expiring, account.alert, number.action_required, number.action_resolved, onboarding.link.completed, onboarding.link.opened, onboarding.link.failed, onboarding.link.expired, template.category, template.quality | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID/test" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "eventType": "message.received" }' ``` #### Responses **200**: O resultado do evento de teste. O corpo que o seu servidor respondeu não volta aqui, de propósito. ```json { "delivered": true, "statusCode": 1, "durationMs": 1, "failure": "timeout" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Rotate the signing secret `POST /v1/webhooks/endpoints/{id}/rotacionar` Mints a new secret and returns it once. Store it now, as on registration. Authentication: API key. Required scope: `webhooks:write` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-post-v1-webhooks-endpoints-id-rotacionar #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador do endpoint, devolvido no cadastro. | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `revokePrevious` | `boolean` | no | Com true, o segredo anterior deixa de valer no mesmo instante, em vez de seguir válido por sete dias. Use quando o segredo anterior vazou. As entregas que já saíram assinadas só com ele falham na verificação do seu lado. | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/endpoints/YOUR_ID/rotacionar" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "revokePrevious": true }' ``` #### Responses **200**: O endpoint com o segredo novo. O anterior continua válido até previousSecretExpiresAt, então você pode trocar a configuração do seu lado sem pressa e sem perder entrega. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "url": "https://exemplo.com.br/arquivo", "createdAt": "YOUR_CREATEDAT", "updatedAt": "YOUR_UPDATEDAT", "previousSecretExpiresAt": "YOUR_PREVIOUSSECRETEXPIRESAT", "paused": true, "pausedAt": "YOUR_PAUSEDAT", "eventTypes": [ "YOUR_EVENTTYPES" ], "externalIds": [ "YOUR_EXTERNALIDS" ], "phoneNumberIds": [ "YOUR_PHONENUMBERIDS" ], "headerNames": [ "YOUR_HEADERNAMES" ], "lastDeliveryAt": "YOUR_LASTDELIVERYAT", "lastFailureAt": "YOUR_LASTFAILUREAT", "lastHttpStatus": 1, "deliveryStatus": "ok", "secret": "YOUR_SECRET" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### List deliveries that failed for good `GET /v1/webhooks/dlq` The events Luna tried to deliver to your endpoint and gave up on, newest first, each with the number, the customer label, the attempts, the last HTTP status and what can be done with it (allowedActions). Filters: endpointId, externalId and requeued. Authentication: API key. Required scope: `webhooks:read` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-get-v1-webhooks-dlq #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `cursor` | `string` | no | O cursor devolvido em nextCursor pela chamada anterior. Omita na primeira página. | | `limit` | `integer` | no | Quantos itens trazer nesta página. Máximo 100, igual para todos. | | `endpointId` | `string` | no | Só os itens deste endpoint. | | `externalId` | `string` | no | Só os itens dos números deste cliente seu (externalId do número). Igualdade exata; um rótulo sem item devolve lista vazia. | | `requeued` | `string` | no | true: só os já re-enfileirados. false: só os que ainda podem ser (os que têm requeue em allowedActions). | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/webhooks/dlq" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Uma página da fila de rejeitados. Sem total e sem contagem: a Luna não soma entregas, e nenhum número desta resposta alimenta cobrança. attempts e lastHttpStatus descrevem UMA entrega que falhou, e não um agregado. ```json { "items": [ { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "endpointId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "eventType": "message.received", "wamid": "YOUR_WAMID", "rejectedAt": "YOUR_REJECTEDAT", "failureReason": "http_4xx", "requeuedAt": "YOUR_REQUEUEDAT", "numberId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "externalId": "YOUR_EXTERNALID", "attempts": 1, "lastHttpStatus": 1, "allowedActions": [ "requeue" ] } ], "nextCursor": "YOUR_NEXTCURSOR" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Requeue a failed delivery `POST /v1/webhooks/dlq/{id}/reenfileirar` Puts the event back on the delivery queue. The response is 202: the request was recorded, and delivery happens asynchronously. Authentication: API key. Required scope: `webhooks:write` Topic guide: https://lunahia.com.br/en/docs/receive-events#rota-post-v1-webhooks-dlq-id-reenfileirar #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | O identificador deste item na fila de rejeitados. | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/webhooks/dlq/YOUR_ID/reenfileirar" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **202**: O item foi recolocado na fila de entrega. A entrega em si é assíncrona, como qualquer outra: se o seu endpoint ainda estiver fora do ar, ela será adiada e retentada pela mesma política de sempre. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "requeuedAt": "YOUR_REQUEUEDAT" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "already_requeued", "docsUrl": "https://lunahia.com.br/docs/receber-eventos", "message": "Este item já foi re-enfileirado.", "reenfileiradoEm": "2026-10-06T12:00:00.000Z" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ## Keys Create, list and revoke the credentials that authenticate your calls. ### List API keys `GET /v1/api-keys` This customer's keys, with scopes, profile, status (active, revoked or expired), creation date, last use, revocation and what the account can do with each one (allowedActions). Authentication: API key. Required scope: `keys:read` Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-get-v1-api-keys #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `kind` | `string` | no | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/api-keys" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json [ { "id": "7d1f4c02-9a3b-4e51-8c7d-2f0b6a91e334", "label": "integração de produção", "kind": "integration", "scopes": [ "messages:write", "messages:read", "numbers:read" ], "mode": "live", "externalId": null, "createdAt": "2026-08-07T12:10:44.201Z", "expiresAt": null, "revokedAt": null, "lastUsedAt": "2026-08-10T09:02:18.664Z", "status": "active", "profile": "agent", "allowedActions": [ "revoke" ] } ] ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Create an API key `POST /v1/api-keys` Mints a new key and returns the secret exactly once. Store it the moment you receive it, because no route will return it again. Authentication: API key. Required scope: `keys:write` Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-post-v1-api-keys #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `label` | `string` | no | 1 to 120 characters | | `scopes` | `array` | no | O que a chave pode fazer, escopo por escopo. Mande scopes ou profile, e nunca os dois: a lista de escopos que cada perfil concede está em GET /v1/api-keys/profiles. · at least 1 items | | `profile` | `string` | no | Um perfil pronto no lugar de scopes: agent (atendimento), full (integração completa) ou read_only (somente leitura). A chave nasce com os escopos que o perfil concede no momento da criação, e a lista deles está em GET /v1/api-keys/profiles. · Values: agent, full, read_only | | `expiresAt` | `string (date-time)` | no | | | `mode` | `string` | no | live (o padrão) é a chave de sempre. test cria uma chave do modo de teste: POST /v1/messages com ela NÃO vai à Meta, não usa número seu e não conta na capacidade do plano; a Luna devolve ao seu webhook eventos simulados, assinados e com test: true. Uma chave de teste só usa POST /v1/messages e POST /v1/test-mode/inbound-messages, e não aceita externalId. Não dá para mudar depois: crie outra. · Values: live, test | | `externalId` | `string` | no | O seu identificador para o cliente a que esta chave pertence (1 a 128 caracteres), o mesmo externalId do link de conexão e dos números. Com ele, a chave é de UM cliente seu: só lê e envia pelos números com este externalId (inclusive os conectados depois), só cria link com ele, e não lista nem cria endpoints de webhook nem chaves. Sem ele, a chave é da conta inteira. Não dá para mudar depois: crie outra. · 1 to 128 characters | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/api-keys" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "label": "YOUR_LABEL", "scopes": [ "keys:read" ], "profile": "agent" }' ``` #### Responses **201**: Created. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "label": "YOUR_LABEL", "kind": "integration", "scopes": [ "YOUR_SCOPES" ], "mode": "live", "externalId": "YOUR_EXTERNALID", "createdAt": "YOUR_CREATEDAT", "expiresAt": "YOUR_EXPIRESAT", "revokedAt": "YOUR_REVOKEDAT", "lastUsedAt": "YOUR_LASTUSEDAT", "status": "active", "profile": "agent", "allowedActions": [ "revoke" ], "secret": "YOUR_SECRET" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### List the scopes a key can have `GET /v1/api-keys/scopes` The scopes an integration key can receive, each with its name in Portuguese, what it allows and whether it gives a power that calls for care. Authentication: API key. Required scope: `keys:read` #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/api-keys/scopes" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "scope": "messages:write", "label": "Enviar mensagens", "summary": "Envia mensagens e templates pelos números conectados.", "sensitive": false }, { "scope": "keys:write", "label": "Criar e revogar chaves", "summary": "Permite que esta chave crie outras chaves, sem prazo. Dê só a quem precisa.", "sensitive": true } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### List the key profiles `GET /v1/api-keys/profiles` The ready-made key profiles (agent, full and read_only) and the scopes each one grants. In POST /v1/api-keys, profile stands in for scopes. Authentication: API key. Required scope: `keys:read` #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/api-keys/profiles" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "id": "read_only", "label": "Somente leitura", "summary": "Consulta tudo e não altera nada.", "scopes": [ "keys:read", "numbers:read", "messages:read", "templates:read", "webhooks:read" ] } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read one API key `GET /v1/api-keys/{id}` One key's metadata. The secret does not come back, for the reason described on the listing route. Authentication: API key. Required scope: `keys:read` #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/api-keys/YOUR_ID" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "id": "7d1f4c02-9a3b-4e51-8c7d-2f0b6a91e334", "label": "integração de produção", "kind": "integration", "scopes": [ "messages:write", "messages:read", "numbers:read" ], "mode": "live", "externalId": null, "createdAt": "2026-08-07T12:10:44.201Z", "expiresAt": null, "revokedAt": null, "lastUsedAt": "2026-08-10T09:02:18.664Z", "status": "active", "profile": "agent", "allowedActions": [ "revoke" ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Revoke an API key `POST /v1/api-keys/{id}/revoke` Invalidates the key immediately. The operation is idempotent, so revoking again returns the same result without an error. Authentication: API key. Required scope: `keys:write` Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-post-v1-api-keys-id-revoke #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | yes | | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/api-keys/YOUR_ID/revoke" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "id": "7d1f4c02-9a3b-4e51-8c7d-2f0b6a91e334", "label": "integração de produção", "kind": "integration", "scopes": [ "messages:write", "messages:read", "numbers:read" ], "mode": "live", "externalId": null, "createdAt": "2026-08-07T12:10:44.201Z", "expiresAt": null, "revokedAt": null, "lastUsedAt": "2026-08-10T09:02:18.664Z", "status": "active", "profile": "agent", "allowedActions": [ "revoke" ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ## Account and plan The credential's account, the plan, the number capacity and how many are in use in the period. ### Read the plan and the subscription `GET /v1/subscription` The account's plan (free trial or contracted), the number capacity and how many are in use, and what Helsen charges for the period: the capacity of active numbers, and nothing beyond that. Authentication: API key. Required scope: `numbers:read` Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-get-v1-subscription #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `inicio` | `string` | no | | | `fim` | `string` | no | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/subscription" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "planName": "Growth", "status": "trial", "suspendedReason": null, "capacity": 20, "activeNumbers": 3, "trialEndsAt": "2026-11-03T13:00:00.000Z", "trialDaysLeft": 5, "periodo": { "inicio": "2026-03-01T00:00:00.000Z", "fim": "2026-04-01T00:00:00.000Z" }, "canConnectNumber": true, "capacityLeft": 17, "capacityNotice": null, "writesAllowed": true, "suspendedNotice": null, "pricePerMonth": 990, "currency": "BRL", "contactEmail": "contato@lunahia.com.br", "numerosAtivos": 3, "phoneNumberIds": [ "15550001111", "15550002222" ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read the platform's technical limits `GET /v1/limits` The ceilings the API applies, each with its value, unit and reason. They are the same for every customer and do not depend on the plan: they exist for infrastructure capacity or because Meta imposes them. They are not a count of your usage and do not enter billing. Authentication: API key. Required scope: `numbers:read` #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/limits" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "data": [ { "key": "webhook_endpoints", "label": "Endpoints de webhook por cliente", "value": 25, "unit": "endpoints", "reason": "Cada evento é entregue a cada endpoint que o aceita. Remover um endpoint libera a vaga." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read Meta's pricing rules `GET /v1/meta-pricing` The rules by which Meta charges for the use of WhatsApp to the business that owns the number, and the day Luna read them. It carries no monetary values: the rate table stays at Meta. Luna charges none of this. Authentication: API key. Required scope: `numbers:read` #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/meta-pricing" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "readAt": "2026-10-07", "sourceUrl": "https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing", "aiProvidersUrl": "https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ai-providers", "rules": [ { "key": "marketing_templates", "title": "Template de marketing", "text": "É sempre cobrado pela Meta, dentro ou fora da janela de 24 horas." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read your own account `GET /v1/account` Returns the account behind the credential presented: identifier, name, whether the email has been confirmed, and when the account was created. Authentication: API key. Required scope: `numbers:read` Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-get-v1-account #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/account" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "name": "YOUR_NAME", "emailConfirmed": true, "createdAt": "YOUR_CREATEDAT", "operatorEmail": "YOUR_OPERATOREMAIL" } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Rename the account `PATCH /v1/account` Changes the account name, the same one GET /v1/account returns. Returns the account with the new name. Only the console session does this. Authentication: API key. Required scope: `session:end` #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `name` | `string` | yes | O novo nome da conta, de 1 a 120 caracteres: o mesmo limite do cadastro. · 1 to 120 characters | #### Code examples ```bash curl -X PATCH "https://api.lunahia.com.br/v1/account" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "YOUR_NAME" }' ``` #### Responses **200**: Success. ```json { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "name": "YOUR_NAME", "emailConfirmed": true, "createdAt": "YOUR_CREATEDAT", "operatorEmail": "YOUR_OPERATOREMAIL" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### See the account summary `GET /v1/account/overview` What the account needs to look at now (alerts, most serious first), the four first steps, and the numbers by connection state. Everything is decided by the API, so a home screen has nothing to calculate. Authentication: API key. Required scope: `numbers:read` #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/account/overview" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "attention": [ { "code": "number_credential_expiring", "severity": "warning", "title": "Autorização do cliente perto de vencer (+55 11 90000-0000)", "message": "A autorização que o seu cliente deu à Luna vence em até 14 dias. O número continua enviando até lá.", "solution": "Gere um link de reconexão com POST /v1/onboarding/links informando numberId e envie ao seu cliente.", "resource": { "type": "number", "id": "ed404df1-b420-4ed6-8743-ba1609892e0a" }, "action": "reconnect_link", "actionUrl": null, "since": "2026-10-25T12:00:00.000Z" } ], "checklist": [ { "key": "connect_number", "done": true, "doneAt": "2026-08-07T11:28:14.597Z" }, { "key": "create_key", "done": true, "doneAt": "2026-08-07T12:10:44.201Z" }, { "key": "add_webhook_endpoint", "done": true, "doneAt": "2026-08-08T09:00:00.000Z" }, { "key": "send_message", "done": false, "doneAt": null } ], "numbers": { "total": 1, "byStatus": { "connected": 1, "connecting": 0, "action_required": 0, "disconnected": 0 } } } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ## Status Availability probes and the state of the platform. No authentication. ### Check whether the API is up `GET /healthz` Answers 200 while the process is running. It requires no authentication and touches neither database nor queue, because it probes the process and not its dependencies. A 200 here does not promise that message sending works. Authentication: Public, no key #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/healthz" ``` #### Responses **200**: Success. ### See whether Luna is receiving and delivering `GET /status` Answers 200 with the platform state, measured every few minutes by a synthetic message that enters through the same door Meta uses and has to reach a destination over HTTPS. It requires no authentication and reveals no account data. When there is no recent check yet, the state is unknown, never ok. Authentication: Public, no key #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/status" ``` #### Responses **200**: Success. ```json { "status": "ok", "checkedAt": "YOUR_CHECKEDAT", "components": { "ingestion": "ok", "delivery": "ok", "partitions": "ok" }, "since": "YOUR_SINCE" } ``` ### Introduce the API `GET /` Answers 200 with the API name and the addresses of the documentation and of the OpenAPI specification. It requires no authentication and touches neither database nor queue. Authentication: Public, no key #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/" ``` #### Responses **200**: Success. ```json { "name": "YOUR_NAME", "docs": "YOUR_DOCS", "openapi": "YOUR_OPENAPI" } ``` ## Console and public pages Routes the Luna console and the public connection link page use: sign-up, login, session and completion of the flow. You normally do not need them. They exist here because the console is a client of this same API, with no privileged route. ### Read the connect link (customer page) `GET /v1/public/onboarding-links/{token}` For the page your customer opens. Returns the name of the account that asked for the connection, the link status, and the public identifiers of the Meta app that the connection window uses. Nothing else about your account comes out here. Authentication: Public, no key Topic guide: https://lunahia.com.br/en/docs/saas-with-n-customers#rota-get-v1-public-onboarding-links-token #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `token` | `string` | yes | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/public/onboarding-links/YOUR_TOKEN" ``` #### Responses **200**: Success. ```json { "accountName": "YOUR_ACCOUNTNAME", "displayName": "YOUR_DISPLAYNAME", "status": "open", "expiresAt": "YOUR_EXPIRESAT", "metaAppId": "YOUR_METAAPPID", "metaConfigId": "YOUR_METACONFIGID", "sdkVersion": "YOUR_SDKVERSION", "redirectUrl": "YOUR_REDIRECTURL", "reconnect": true } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Open the connection session through the link `POST /v1/public/onboarding-links/{token}/sessions` Opens the session that Meta's window fills in, for the account that owns the link. It is the same opening as POST /v1/onboarding/sessions, through the token's door. On a reconnection link (created with numberId), the session is born bound to the number's account, as in POST /v1/onboarding/reconnect. Authentication: Public, no key Topic guide: https://lunahia.com.br/en/docs/saas-with-n-customers#rota-post-v1-public-onboarding-links-token-sessions #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `token` | `string` | yes | | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/public/onboarding-links/YOUR_TOKEN/sessions" ``` #### Responses **201**: Created. ```json { "sessionId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "state": "YOUR_STATE", "configId": "YOUR_CONFIGID", "sdkVersion": "YOUR_SDKVERSION", "csrfState": "YOUR_CSRFSTATE", "expiresAt": "YOUR_EXPIRESAT" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **409**: The request is well formed, but the resource state does not allow it. The error field says which case it is. ```json { "error": "account_at_capacity", "docsUrl": "https://lunahia.com.br/docs/plano-e-numeros", "message": "A conta que pediu esta conexão atingiu o máximo de números. Avise quem enviou este link: assim que ela abrir uma vaga, ele poderá enviar um link novo." } ``` **410**: The connect link expired or was already used. The error field says which of the two. ```json { "error": "link_expired", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Este link venceu. Peça um novo a quem enviou este." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Complete the connection through the link `POST /v1/public/onboarding-links/{token}/sessions/{sessionId}/complete` Exchanges the code from Meta's window for access to the customer's account. It is the same completion as POST /v1/onboarding/sessions/{id}/complete, through the token's door, and the same warning holds: the code lasts 30 seconds, so call it the moment it arrives. Authentication: Public, no key Topic guide: https://lunahia.com.br/en/docs/saas-with-n-customers#rota-post-v1-public-onboarding-links-token-sessions-sessionid-complete #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `token` | `string` | yes | | | `sessionId` | `string` | yes | | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `code` | `string` | yes | | | `csrfState` | `string` | yes | | | `wabaId` | `string \| null` | no | | | `phoneNumberId` | `string \| null` | no | | | `businessId` | `string \| null` | no | | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/public/onboarding-links/YOUR_TOKEN/sessions/YOUR_SESSION_ID/complete" \ -H "Content-Type: application/json" \ -d '{ "code": "YOUR_CODE", "csrfState": "YOUR_CSRFSTATE" }' ``` #### Responses **200**: Success. ```json { "sessionId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "state": "YOUR_STATE", "orientacao": "YOUR_ORIENTACAO", "terminal": true, "motivo": "YOUR_MOTIVO", "podeRetentar": true, "numberId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "returnUrl": "YOUR_RETURNURL" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **410**: The connect link expired or was already used. The error field says which of the two. ```json { "error": "link_used", "docsUrl": "https://lunahia.com.br/docs/conectar-numero", "message": "Este link já foi usado. Se precisar conectar outro número, peça um novo a quem enviou este." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Report an abandoned or failed flow through the link `POST /v1/public/onboarding-links/{token}/sessions/{sessionId}/abandon` Telemetry about what happened in Meta's window when the customer did not complete. It is the same report as POST /v1/onboarding/sessions/{id}/abandon, through the token's door, and it only applies to a session opened by this same link. Authentication: Public, no key Topic guide: https://lunahia.com.br/en/docs/saas-with-n-customers#rota-post-v1-public-onboarding-links-token-sessions-sessionid-abandon #### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `token` | `string` | yes | | | `sessionId` | `string` | yes | | #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `csrfState` | `string` | yes | | | `currentStep` | `string \| null` | no | 1 to 120 characters | | `errorCode` | `integer \| null` | no | | | `errorMessage` | `string \| null` | no | | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/public/onboarding-links/YOUR_TOKEN/sessions/YOUR_SESSION_ID/abandon" \ -H "Content-Type: application/json" \ -d '{ "csrfState": "YOUR_CSRFSTATE" }' ``` #### Responses **200**: Success. ```json { "sessionId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "state": "YOUR_STATE", "orientacao": "YOUR_ORIENTACAO", "abandonedAtStep": "YOUR_ABANDONEDATSTEP" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **404**: The resource does not exist, or is not yours. The two answers are identical, byte for byte. ```json { "error": "not_found", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Recurso não encontrado." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Create an account `POST /v1/operators/signup` Creates the account and its first operator, in a single call and with no credential. Authentication: Public, no key Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-post-v1-operators-signup #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `email` | `string` | yes | up to 254 characters | | `password` | `string` | yes | 12 to 512 characters | | `tenantName` | `string` | yes | 1 to 120 characters | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/signup" \ -H "Content-Type: application/json" \ -d '{ "email": "ana@suaempresa.com.br", "password": "YOUR_PASSWORD", "tenantName": "YOUR_TENANTNAME" }' ``` #### Responses **201**: Created. ```json { "nextStep": "login" } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Confirm an account's email `GET /v1/operators/confirm` Destination of the link sent by email when the account is created. It answers with a redirect to the console, and not with JSON, because a person in a browser is what opens it. Authentication: Public, no key Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-get-v1-operators-confirm #### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `token` | `string` | no | | #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/operators/confirm" ``` #### Responses **200**: Success. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Ask for a password reset `POST /v1/operators/password/forgot` Asks for a link to choose a new password. It takes only the account email. Authentication: Public, no key Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-post-v1-operators-password-forgot #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `email` | `string` | yes | up to 254 characters | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/password/forgot" \ -H "Content-Type: application/json" \ -d '{ "email": "ana@suaempresa.com.br" }' ``` #### Responses **202**: Accepted: the request was recorded and will be processed. ```json { "accepted": true } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Choose a new password `POST /v1/operators/password/reset` Changes the operator's password from the token in the link sent by email, and answers 204. Authentication: Public, no key Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-post-v1-operators-password-reset #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `token` | `string` | yes | up to 512 characters | | `password` | `string` | yes | 12 to 512 characters | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/password/reset" \ -H "Content-Type: application/json" \ -d '{ "token": "YOUR_TOKEN", "password": "YOUR_PASSWORD" }' ``` #### Responses **204**: No content: the operation was done and the response has no body. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Check the reset link `POST /v1/operators/password/reset/check` Answers 204 when the link token is still valid and 400 when it is not, without consuming it. Lets the screen warn before the person types the new password. Authentication: Public, no key #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `token` | `string` | yes | up to 512 characters | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/password/reset/check" \ -H "Content-Type: application/json" \ -d '{ "token": "YOUR_TOKEN" }' ``` #### Responses **204**: No content: the operation was done and the response has no body. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read the password rule `GET /v1/public/password-policy` The minimum length of an operator password, the same at signup, reset and change. It asks for no credential. Authentication: Public, no key #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/public/password-policy" ``` #### Responses **200**: Success. ```json { "minLength": 12 } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Change the password `POST /v1/operators/password/change` Changes the password of the operator behind the presented session, checking the current password, and answers 204. The operator's other sessions are ended and the presented one stays valid. A wrong current password, or a credential with no operator (an integration key), answers 401. Authentication: API key. Required scope: `session:elevate` #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `currentPassword` | `string` | yes | A senha de hoje do operador da sessão. · up to 512 characters | | `newPassword` | `string` | yes | A senha nova, pela mesma regra do cadastro (GET /v1/public/password-policy diz o mínimo). · 12 to 512 characters | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/password/change" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "currentPassword": "YOUR_CURRENTPASSWORD", "newPassword": "YOUR_NEWPASSWORD" }' ``` #### Responses **204**: No content: the operation was done and the response has no body. **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Resend the confirmation email `POST /v1/operators/confirmation/resend` Sends the confirmation link again to the email of the operator behind the session, and invalidates the previous link if it had not been opened. The new link is valid for seven days and is accepted a single time. Authentication: API key. Required scope: `session:end` Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-post-v1-operators-confirmation-resend #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/confirmation/resend" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **202**: Accepted: the request was recorded and will be processed. ```json { "emailConfirmed": true } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Authenticate an operator `POST /v1/operators/login` Exchanges email and password for an eight hour session credential, used by the web console. Authentication: Public, no key Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-post-v1-operators-login #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `email` | `string` | yes | 1 to 254 characters | | `password` | `string` | yes | 1 to 512 characters | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/login" \ -H "Content-Type: application/json" \ -d '{ "email": "ana@suaempresa.com.br", "password": "YOUR_PASSWORD" }' ``` #### Responses **200**: Success. ```json { "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "operatorId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "token": "YOUR_TOKEN", "expiresAt": "YOUR_EXPIRESAT", "scopes": [ "YOUR_SCOPES" ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Re-authenticate for a sensitive action `POST /v1/operators/step-up` Confirms the password of the operator behind the session presented, and opens a two hour window in which that same session can create and revoke API keys. Authentication: API key. Required scope: `session:elevate` Topic guide: https://lunahia.com.br/en/docs/account-and-keys#rota-post-v1-operators-step-up #### Request body `application/json` | Field | Type | Required | Description | | --- | --- | --- | --- | | `password` | `string` | yes | 1 to 512 characters | #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/step-up" \ -H "Authorization: Bearer $LUNA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "password": "YOUR_PASSWORD" }' ``` #### Responses **200**: Success. ```json { "elevatedUntil": "YOUR_ELEVATEDUNTIL", "scopes": [ "YOUR_SCOPES" ] } ``` **400**: The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. ```json { "error": "invalid_request", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisição inválida.", "campos": [ { "campo": "text.body", "motivo": "Não pode ficar vazio." } ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **415**: The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. ```json { "error": "unsupported_media_type", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Envie o corpo como application/json." } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### Read the presented session `GET /v1/operators/session` When the presented credential expires, until when the elevation opened by POST /v1/operators/step-up lasts (null with no elevation or with the window closed) and the scopes it has now. It reads only the credential itself: the identifier comes from authentication and never from the path. Authentication: API key. Required scope: `session:end` #### Code examples ```bash curl -X GET "https://api.lunahia.com.br/v1/operators/session" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **200**: Success. ```json { "expiresAt": "2026-11-03T20:00:00.000Z", "elevatedUntil": "2026-11-03T14:30:00.000Z", "scopes": [ "numbers:read", "session:end", "session:elevate", "keys:write" ] } ``` **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ### End the session `POST /v1/operators/logout` Revokes the credential presented, and only it. The identifier comes from the authentication itself and never from the body, so this route cannot revoke someone else's key. Authentication: API key. Required scope: `session:end` #### Code examples ```bash curl -X POST "https://api.lunahia.com.br/v1/operators/logout" \ -H "Authorization: Bearer $LUNA_API_KEY" ``` #### Responses **204**: No content: the operation was done and the response has no body. **401**: The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. ```json { "error": "unauthorized", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Credencial ausente ou inválida." } ``` **403**: The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. ```json { "error": "forbidden", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Esta chave não tem o escopo numbers:read, que esta operação exige. Crie uma chave com esse escopo (Integração, Chaves de API, no console) e use-a no lugar desta.", "requiredScope": "numbers:read" } ``` **429**: Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. ```json { "error": "rate_limited", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Requisições demais. Tente novamente em instantes." } ``` **503**: The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. ```json { "error": "unavailable", "docsUrl": "https://lunahia.com.br/docs/erros", "message": "Não foi possível concluir a operação agora. Tente novamente em instantes." } ``` ## Webhook events Luna POSTs the event to the endpoint you registered, with the body as application/json and the signature header. Answer 2xx to confirm; any other answer, or none, counts as a failure and is repeated by the retry policy. Verify the signature over the raw body before trusting the content. `x-luna-signature`: The delivery signature: t=,v1=."> with the endpoint secret. During a secret rotation the header carries two v1= values, and one matching is enough. Reject deliveries whose t is more than 300 seconds from your clock. ### Message received `message.received` A contact wrote to one of your numbers. It carries the text, and the content when the message is of another type (media, tapped button, location, contacts, reaction). | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"message.received"` | yes | | | `message` | `object` | yes | Uma mensagem que chegou de um interlocutor. Além de wamid, wa_id (que pode ser nulo), user_id, parent_user_id, username, type e text, ela traz o conteúdo que o tipo carrega (mídia, botão ou item clicado, resposta de Flow, localização, contatos, reação, pedido, edição, apagamento, aviso de tipo sem suporte), a citação, o anúncio de origem e o nome de perfil. Os nomes dentro desses campos são os da Meta. Todo campo está sempre presente, e é nulo quando não se aplica. | | `message.id` | `string (uuid)` | yes | O identificador da mensagem na Luna. É o id que GET /v1/messages/{id}/media, POST /v1/messages/{id}/read, POST /v1/messages/{id}/typing e POST /v1/messages/{id}/replay pedem. | | `message.wamid` | `string` | yes | O identificador da mensagem na Meta. | | `message.wa_id` | `string \| null` | yes | O identificador do interlocutor na Meta, em E.164 sem o sinal de mais: o telefone. Nulo quando o usuário escreveu sem que o telefone apareça (nome de usuário adotado): use user_id. | | `message.user_id` | `string \| null` | yes | O BSUID do interlocutor, o identificador do usuário que não depende do telefone (por exemplo US.13491208655302741918), como a Meta o mandou. Nulo quando a Meta ainda não o mandou para esta conversa. Quando wa_id é nulo, é o único identificador do interlocutor. | | `message.parent_user_id` | `string \| null` | yes | O BSUID pai do interlocutor (por exemplo US.ENT.11815799212886844830). Só existe quando a Meta o manda; nulo no demais. | | `message.username` | `string \| null` | yes | O nome de usuário do interlocutor. Só existe quando ele adotou um; nulo no demais. | | `message.type` | `string` | yes | O tipo da mensagem, no vocabulário da Meta. | | `message.text` | `string \| null` | yes | O texto da mensagem, quando o tipo é texto. Nulo nos demais tipos: a legenda de uma mídia está em media.caption, e o título de um botão clicado em interactive.title. | | `message.profile_name` | `string \| null` | yes | O nome que o interlocutor exibe no WhatsApp. Nulo quando a Meta não o mandou. | | `message.media` | `object \| null` | yes | | | `message.media.mime_type` | `string \| null` | yes | O tipo MIME do arquivo, como a Meta o informou. Nulo na mídia enviada: a Luna não guarda os dados do arquivo que você subiu. | | `message.media.sha256` | `string \| null` | yes | O resumo SHA-256 do arquivo, como a Meta o informou. Nulo na mídia enviada, pela mesma razão do mime_type. | | `message.media.caption` | `string \| null` | yes | A legenda. Nula em áudio e em figurinha, e quando o interlocutor não escreveu uma. | | `message.media.filename` | `string \| null` | yes | O nome do arquivo. Só documento tem. | | `message.media.voice` | `boolean \| null` | yes | Verdadeiro quando o áudio foi gravado na hora, como mensagem de voz. Só áudio tem. | | `message.media.animated` | `boolean \| null` | yes | Verdadeiro quando a figurinha é animada. Só figurinha tem. | | `message.media.url` | `string \| null` | yes | Link da Luna para baixar o arquivo, sem chave de API: GET desse endereço responde 302 para uma URL assinada de vida curta. É credencial de portador (quem tiver o link baixa o arquivo): não registre em log. É o mesmo em toda reentrega do aviso, e vale por 30 dias contados do recebimento. Se a Luna ainda estiver baixando o arquivo da Meta, responde 409 com Retry-After: tente de novo. Nulo quando a mídia não pode ser obtida (a Meta não mandou identificador, ou o prazo de obtenção acabou). GET /v1/messages/{id}/media, com chave, continua valendo. | | `message.interactive` | `object \| null` | yes | A resposta a uma mensagem interativa que você enviou: o botão ou o item que o interlocutor escolheu. | | `message.interactive.type` | `string \| null` | yes | Qual resposta foi dada: button_reply (botão de resposta), list_reply (item de lista) ou nfm_reply (resposta de um Flow). | | `message.interactive.id` | `string \| null` | yes | O id que você deu ao botão ou ao item quando enviou a mensagem. Nulo em nfm_reply. | | `message.interactive.title` | `string \| null` | yes | O título do botão ou do item, como estava na mensagem. Nulo em nfm_reply. | | `message.interactive.description` | `string \| null` | yes | A descrição do item da lista. Nula nos demais. | | `message.interactive.name` | `string \| null` | yes | O nome do Flow. Só em nfm_reply. | | `message.interactive.response_json` | `string \| null` | yes | As respostas do Flow, como o texto JSON que a Meta mandou, sem interpretar. Só em nfm_reply. | | `message.button` | `object \| null` | yes | O clique num botão de resposta rápida de um template. | | `message.button.payload` | `string \| null` | yes | O payload que você definiu no botão de resposta rápida do template. | | `message.button.text` | `string \| null` | yes | O texto do botão. | | `message.location` | `object \| null` | yes | A localização que o interlocutor compartilhou. | | `message.location.latitude` | `number \| null` | yes | A latitude, em graus decimais. | | `message.location.longitude` | `number \| null` | yes | A longitude, em graus decimais. | | `message.location.name` | `string \| null` | yes | O nome do lugar, quando o interlocutor escolheu um. | | `message.location.address` | `string \| null` | yes | O endereço, quando há. | | `message.location.url` | `string \| null` | yes | O endereço web do lugar, quando há. | | `message.contacts` | `array \| null` | yes | Os cartões de contato que o interlocutor compartilhou. | | `message.contacts[].name` | `object \| null` | yes | O nome do contato, nos campos da Meta. | | `message.contacts[].name.formatted_name` | `string \| null` | yes | | | `message.contacts[].name.first_name` | `string \| null` | yes | | | `message.contacts[].name.last_name` | `string \| null` | yes | | | `message.contacts[].name.middle_name` | `string \| null` | yes | | | `message.contacts[].name.prefix` | `string \| null` | yes | | | `message.contacts[].name.suffix` | `string \| null` | yes | | | `message.contacts[].phones` | `array \| null` | yes | Os telefones do contato. wa_id só existe quando o telefone tem WhatsApp. | | `message.contacts[].phones[].phone` | `string \| null` | yes | | | `message.contacts[].phones[].wa_id` | `string \| null` | yes | | | `message.contacts[].phones[].type` | `string \| null` | yes | | | `message.contacts[].emails` | `array \| null` | yes | Os e-mails do contato. | | `message.contacts[].emails[].email` | `string \| null` | yes | | | `message.contacts[].emails[].type` | `string \| null` | yes | | | `message.contacts[].org` | `object \| null` | yes | A organização do contato. | | `message.contacts[].org.company` | `string \| null` | yes | | | `message.contacts[].org.department` | `string \| null` | yes | | | `message.contacts[].org.title` | `string \| null` | yes | | | `message.reaction` | `object \| null` | yes | A reação a uma mensagem, ou a retirada dela. | | `message.reaction.wamid` | `string \| null` | yes | O wamid da mensagem que recebeu a reação. | | `message.reaction.emoji` | `string \| null` | yes | O emoji. Nulo quando o interlocutor retirou a reação. | | `message.context` | `object \| null` | yes | A resposta citando uma mensagem, ou o aviso de que a mensagem foi encaminhada. | | `message.context.wamid` | `string \| null` | yes | O wamid da mensagem que o interlocutor citou ao responder. | | `message.context.from` | `string \| null` | yes | Quem enviou a mensagem citada. | | `message.context.forwarded` | `boolean \| null` | yes | Verdadeiro quando a mensagem foi encaminhada. | | `message.context.frequently_forwarded` | `boolean \| null` | yes | Verdadeiro quando a mensagem foi encaminhada muitas vezes. | | `message.referral` | `object \| null` | yes | O anúncio Click to WhatsApp ou a publicação que levou o interlocutor a escrever. | | `message.referral.source_type` | `string \| null` | yes | A origem do clique, como ad ou post. | | `message.referral.source_id` | `string \| null` | yes | O identificador do anúncio ou da publicação na Meta. | | `message.referral.source_url` | `string \| null` | yes | O endereço do anúncio ou da publicação. | | `message.referral.headline` | `string \| null` | yes | O título do anúncio. | | `message.referral.body` | `string \| null` | yes | O texto do anúncio. | | `message.referral.media_type` | `string \| null` | yes | O tipo da mídia do anúncio, como image ou video. | | `message.referral.ctwa_clid` | `string \| null` | yes | O identificador do clique, para atribuição de conversão. | | `message.unsupported` | `object \| null` | yes | Presente quando o interlocutor mandou algo que a Cloud API não entrega (type é unsupported). Não há conteúdo a ler: o aviso existe para o seu agente poder responder "não consigo ver isso". | | `message.unsupported.code` | `integer \| null` | yes | O código de erro da Meta, como ela mandou (131051 é "tipo de mensagem sem suporte"). | | `message.unsupported.title` | `string \| null` | yes | O título do erro, como a Meta o mandou. | | `message.unsupported.details` | `string \| null` | yes | O detalhe do erro, como a Meta o mandou. | | `message.edit` | `object \| null` | yes | Presente quando o interlocutor editou uma mensagem que já tinha mandado (type é edit). | | `message.edit.wamid` | `string \| null` | yes | O wamid da mensagem que foi editada. | | `message.edit.type` | `string \| null` | yes | O tipo do conteúdo novo, como text. | | `message.edit.text` | `string \| null` | yes | O texto novo, quando o conteúdo novo é texto. | | `message.revoke` | `object \| null` | yes | Presente quando o interlocutor apagou uma mensagem para todos (type é revoke). | | `message.revoke.wamid` | `string \| null` | yes | O wamid da mensagem que o interlocutor apagou para todos. | | `message.order` | `object \| null` | yes | O pedido que o interlocutor montou num catálogo e enviou (type é order). | | `message.order.catalog_id` | `string \| null` | yes | O catálogo de onde veio o pedido. | | `message.order.text` | `string \| null` | yes | O texto que o interlocutor escreveu junto com o pedido. | | `message.order.items` | `array \| null` | yes | Os itens do pedido. | | `message.order.items[].product_retailer_id` | `string \| null` | yes | O identificador do produto no seu catálogo. | | `message.order.items[].quantity` | `string \| null` | yes | A quantidade pedida, como a Meta mandou. | | `message.order.items[].item_price` | `string \| null` | yes | O preço unitário, como a Meta mandou. | | `message.order.items[].currency` | `string \| null` | yes | A moeda do preço. | ```json { "version": "2026-11-10", "event_id": "1fd66b6f86489c36c3552f14dbf49f50df6b2d946c259f7b0eaa0ef88f58adb5", "event_type": "message.received", "occurred_at": "2026-10-06T14:05:40.120Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "7d1c4b8e-2a3f-4e5d-9c6b-1f0a2b3c4d5e", "wamid": "wamid.EXAMPLE_BUTTON_CLICK", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "interactive", "text": null, "profile_name": "Maria Souza", "media": null, "interactive": { "type": "button_reply", "id": "rastrear", "title": "Rastrear pedido", "description": null, "name": null, "response_json": null }, "button": null, "location": null, "contacts": null, "reaction": null, "context": { "wamid": "wamid.EXAMPLE_MESSAGE_WITH_BUTTONS", "from": "5511900000001", "forwarded": null, "frequently_forwarded": null }, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` ```json { "version": "2026-11-10", "event_id": "0ab56cecd18b825ebeb4548219cb8fe392fec9e56301e52be1086f3c734ace86", "event_type": "message.received", "occurred_at": "2026-10-06T14:07:03.900Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "4c9e2d1a-8b7f-4a6c-b5d3-0e1f2a3b4c5d", "wamid": "wamid.EXAMPLE_IMAGE", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "image", "text": null, "profile_name": "Maria Souza", "media": { "mime_type": "image/jpeg", "sha256": "EXAMPLE_SHA256_OF_THE_FILE", "caption": "A nota fiscal do pedido", "filename": null, "voice": null, "animated": null, "url": "https://api.lunahia.com.br/v1/media/6f1a2b3c-4d5e-4f60-8a7b-9c0d1e2f3a4b.EXEMPLO_DO_SEGREDO_DE_43_CARACTERES_AAAAAAAA" }, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` ```json { "version": "2026-11-10", "event_id": "a2f4909b0fd2db8ab8b1bfe4e16487f49b86113e27bf8c3c9d10a2d0fefebc72", "event_type": "message.received", "occurred_at": "2026-10-06T14:02:11.482Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "b6d84033-a8e8-4db9-aab6-565ce203cc51", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "text", "text": "Oi! Queria saber o status do meu pedido.", "profile_name": "Maria Souza", "media": null, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` ```json { "version": "2026-11-10", "event_id": "e2f81dd079e4419dac363779655be694a25cc502b7646be51cdac4b0cfc276fb", "event_type": "message.received", "occurred_at": "2026-11-03T14:02:11.482Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "c8a1e5d2-6f3b-4a7c-9e0d-1b2c3d4e5f60", "wamid": "wamid.EXAMPLE_NO_PHONE", "wa_id": null, "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": "mariasouza", "type": "text", "text": "Oi! Queria saber o status do meu pedido.", "profile_name": "Maria Souza", "media": null, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` ```json { "version": "2026-11-10", "event_id": "1eaa360e693d1a7366e66ba81d7bee362a56c2b4f4ef4854e43ad35861bd7ae1", "event_type": "message.received", "occurred_at": "2026-11-04T14:10:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "f3a8c1d2-5b6e-4f70-8a9b-0c1d2e3f4a5b", "wamid": "wamid.EXAMPLE_ORDER", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "order", "text": null, "profile_name": "Maria Souza", "media": null, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": { "catalog_id": "EXAMPLE_CATALOG_ID", "text": "Quero estes dois, por favor.", "items": [ { "product_retailer_id": "sku-001", "quantity": "2", "item_price": "49.90", "currency": "BRL" }, { "product_retailer_id": "sku-002", "quantity": "1", "item_price": "15.00", "currency": "BRL" } ] } } } ``` ```json { "version": "2026-11-10", "event_id": "b9714a025db0a22bd3a63f9dfd9aa52aed7ddcae4efde825dfb2fa41e1736dd2", "event_type": "message.received", "occurred_at": "2026-11-04T14:12:30.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "a4b9d2e3-6c7f-4081-9bac-1d2e3f4a5b6c", "wamid": "wamid.EXAMPLE_FLOW_REPLY", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "interactive", "text": null, "profile_name": "Maria Souza", "media": null, "interactive": { "type": "nfm_reply", "id": null, "title": null, "description": null, "name": "flow", "response_json": "{\"flow_token\":\"EXAMPLE_FLOW_TOKEN\",\"nome\":\"Maria Souza\",\"data\":\"2026-11-10\"}" }, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` ### State of a message you sent `message.status` A message you sent changed state: sent, delivered, read or failed. On failed, the event carries the error. On sent and on one of delivered and read, it carries the pricing: the cost Meta applied to the message, with its names. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"message.status"` | yes | | | `message` | `object` | yes | Uma mudança de estado de uma mensagem que você enviou. | | `message.id` | `string (uuid) \| null` | yes | O identificador da mensagem na Luna, o mesmo que POST /v1/messages devolveu quando você a enviou. Nulo quando o status é de uma mensagem que a Luna não conhece. | | `message.wamid` | `string \| null` | yes | O identificador da mensagem na Meta. Nulo quando a Meta recusou o envio antes de aceitar a mensagem, caso em que ela nunca teve identificador: use id para correlacionar. | | `message.wa_id` | `string \| null` | yes | O identificador do interlocutor na Meta: o telefone. Nulo quando a conversa é só de BSUID: use user_id. | | `message.user_id` | `string \| null` | yes | O BSUID do interlocutor, o identificador do usuário que não depende do telefone (por exemplo US.13491208655302741918), como a Meta o mandou. Nulo quando a Meta ainda não o mandou para esta conversa. Quando wa_id é nulo, é o único identificador do interlocutor. | | `message.parent_user_id` | `string \| null` | yes | O BSUID pai do interlocutor (por exemplo US.ENT.11815799212886844830). Só existe quando a Meta o manda; nulo no demais. | | `message.username` | `string \| null` | yes | O nome de usuário do interlocutor. Só existe quando ele adotou um; nulo no demais. | | `message.status` | `string` | yes | O estado da mensagem, no vocabulário da Meta. Novos estados podem aparecer. | | `message.error_code` | `integer \| null` | yes | O código de erro da Meta quando o estado é de falha. Nulo nos demais. | | `message.error` | `object \| null` | yes | O primeiro erro que a Meta informou quando o estado é de falha, com code, title e message. Nulo nos demais estados. O detalhe completo, com a causa e a ação recomendada, está em GET /v1/messages/{id}. | | `message.error.code` | `integer \| null` | yes | O código do erro, como a Meta o informou. | | `message.error.title` | `string \| null` | yes | O título do erro, como a Meta o informou. | | `message.error.message` | `string \| null` | yes | A descrição do erro, como a Meta a informou. | | `message.pricing` | `object \| null` | yes | O custo que a Meta aplicou à mensagem. A Meta o informa só no estado sent e em um entre delivered e read, então nos demais estados vem nulo. Não é a fatura da Meta: a fonte da verdade é o painel de cobrança dela. | | `message.pricing.billable` | `boolean \| null` | yes | Se a Meta marcou a mensagem como cobrada. A Meta vai descontinuar este campo: use type e category juntos. | | `message.pricing.pricing_model` | `string \| null` | yes | O modelo de preço da Meta, como ela informou (hoje PMP ou CBP). | | `message.pricing.type` | `string \| null` | yes | O tipo de cobrança da Meta, como ela informou (por exemplo regular ou free_customer_service). Novos valores podem aparecer. | | `message.pricing.category` | `string \| null` | yes | A categoria da Meta, como ela informou (por exemplo service, utility ou marketing). Novos valores podem aparecer. | | `message.callback_data` | `string \| null` | yes | A etiqueta que você mandou em callbackData ao enviar a mensagem, devolvida como veio. Nulo quando o envio não trouxe etiqueta. Está em todos os estados da mensagem, inclusive failed. | ```json { "version": "2026-11-10", "event_id": "464e089a80690f1792db6249678ddeced5ad5be0d46d95e2daa263779f7d92e5", "event_type": "message.status", "occurred_at": "2026-10-06T14:02:14.090Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "status": "sent", "error_code": null, "error": null, "pricing": { "billable": false, "pricing_model": "PMP", "type": "free_customer_service", "category": "service" }, "callback_data": "atendimento-8841" } } ``` ```json { "version": "2026-11-10", "event_id": "6a79ec64bfea6acc67135d032067fd6261aa568c3aea35af7999790a7730cf69", "event_type": "message.status", "occurred_at": "2026-10-06T14:02:15.311Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "ae60f288-7565-4315-a440-3663e9c231e1", "wamid": "wamid.EXAMPLE_NOT_A_REAL_ID", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "status": "failed", "error_code": 131026, "error": { "code": 131026, "title": "Message undeliverable", "message": "Message undeliverable" }, "pricing": null, "callback_data": null } } ``` ### Contact changed phone number or BSUID `contact.identity_changed` A contact changed phone number (user_changed_number) or BSUID (user_changed_user_id). Luna linked the new identity to the same conversation. Use previous_user_id and user_id to update the contact in your records. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"contact.identity_changed"` | yes | | | `contact` | `object` | yes | O contato trocou de telefone ou de BSUID. A Luna ligou a nova identidade à mesma conversa. Use previous_user_id e user_id para atualizar o contato no seu cadastro. Todo campo está sempre presente, e é nulo quando não se aplica. | | `contact.wamid` | `string` | yes | O identificador, na Meta, da mensagem de sistema que avisou a troca. | | `contact.change_type` | `string` | yes | O que mudou, como a Meta informou: user_changed_number (o telefone) ou user_changed_user_id (o BSUID). Novos valores podem aparecer. | | `contact.wa_id` | `string \| null` | yes | O telefone do contato, quando a Meta o informa. Nulo quando ela não o manda (usuário com nome de usuário). | | `contact.user_id` | `string \| null` | yes | O BSUID do contato depois da troca, como a Meta mandou. | | `contact.previous_user_id` | `string \| null` | yes | O BSUID de antes da troca, quando a Meta o informa. Use-o para achar o contato no seu cadastro. | | `contact.parent_user_id` | `string \| null` | yes | O BSUID pai do contato depois da troca, quando a Meta o informa. | | `contact.previous_parent_user_id` | `string \| null` | yes | O BSUID pai de antes da troca, quando a Meta o informa. | ```json { "version": "2026-11-10", "event_id": "f73a65b1f155f86f94e0886ad29bac662a822fabf796b626cdf865c7060f0db9", "event_type": "contact.identity_changed", "occurred_at": "2026-11-03T15:20:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "contact": { "wamid": "wamid.EXAMPLE_IDENTITY_CHANGE", "change_type": "user_changed_user_id", "wa_id": null, "user_id": "BR.98765432109876543210", "previous_user_id": "BR.13491208655302741918", "parent_user_id": null, "previous_parent_user_id": null } } ``` ### Contact changed a preference `contact.preferences_changed` A contact changed a preference at Meta, today the one about receiving marketing messages: they asked to stop (for example value stop) or accepted again. The values arrive as Meta sent them. Luna does not block any send because of the notice: your system decides, and should stop sending marketing to whoever asked. It only arrives if the user_preferences field is subscribed on the Meta app. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"contact.preferences_changed"` | yes | | | `contact` | `object` | yes | Quem mudou a preferência. | | `contact.wa_id` | `string \| null` | yes | O telefone do contato, quando a Meta o informa. Nulo quando ela não o manda (usuário com nome de usuário): use user_id. | | `contact.user_id` | `string \| null` | yes | O BSUID do contato, como a Meta mandou. | | `contact.parent_user_id` | `string \| null` | yes | O BSUID pai do contato, quando a Meta o informa. | | `contact.username` | `string \| null` | yes | O nome de usuário do contato, quando ele adotou um. | | `contact.profile_name` | `string \| null` | yes | O nome que o contato exibe no WhatsApp, quando a Meta o manda. | | `preference` | `object` | yes | O que mudou. | | `preference.category` | `string \| null` | yes | A categoria da preferência, como a Meta informou (por exemplo marketing_messages). Novos valores podem aparecer. | | `preference.value` | `string \| null` | yes | O que o contato escolheu, como a Meta informou (por exemplo stop para parar de receber, resume para voltar). Novos valores podem aparecer. | | `preference.detail` | `string \| null` | yes | O texto que a Meta mandou para explicar a mudança. | ```json { "version": "2026-11-10", "event_id": "4236ccfb21e7cec359d1e1b5b5f3f8e65cb3e8a8db0fc86e4d95da037796e97c", "event_type": "contact.preferences_changed", "occurred_at": "2026-11-04T16:45:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "contact": { "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "profile_name": "Maria Souza" }, "preference": { "category": "marketing_messages", "value": "stop", "detail": "User requested to stop marketing messages" } } ``` ### Events dropped by unavailability `backlog.dropped` Your endpoint was down for too long, and the platform dropped what piled up. It says how many events and for what period. The notice is not dropped along with them. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"backlog.dropped"` | yes | | | `backlog` | `object` | yes | Eventos que a plataforma descartou sem entregar, e que não serão reenviados. | | `backlog.motivo` | `string` | yes | Qual limite foi atingido: idade, quando as mensagens ficaram velhas demais para serem acionáveis; volume, quando o acumulado deste endpoint passou do teto da plataforma. · Values: idade, volume | | `backlog.quantidade` | `integer` | yes | Quantos eventos foram descartados nesta ocorrência. | | `backlog.janela_inicio` | `string` | yes | O evento mais antigo descartado nesta ocorrência. | | `backlog.janela_fim` | `string` | yes | O evento mais recente descartado nesta ocorrência. | ```json { "version": "2026-11-10", "event_id": "f76937420c2e818b87ce9b6acc5cb192c059ed2e33cda23339d5cf650b762ce5", "event_type": "backlog.dropped", "occurred_at": "2026-10-06T14:30:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "backlog": { "motivo": "idade", "quantidade": 37, "janela_inicio": "2026-10-06T09:00:00.000Z", "janela_fim": "2026-10-06T14:30:00.000Z" } } ``` ### History import deadline approaching `history_sync.deadline_approaching` On a number connected in coexistence, the import of earlier conversations is still in progress and its deadline approaches. Once the deadline passes without completion, Meta disconnects the end business. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"history_sync.deadline_approaching"` | yes | | | `history_sync` | `object` | yes | A importação das conversas anteriores de um número em coexistência está em curso e o prazo dela se aproxima. O estado corrente, inclusive o progresso, está em GET /v1/numbers/{id}/health. | | `history_sync.prazo` | `string` | yes | Até quando a importação precisa terminar, em UTC. É o mesmo instante que sincronizacaoPrazo devolve na rota de saúde do número. | ```json { "version": "2026-11-10", "event_id": "d42ca56e44ef023d52b0a0739dcf3afb0d5054a8b84321c41e432ed6707b043f", "event_type": "history_sync.deadline_approaching", "occurred_at": "2026-10-07T03:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "history_sync": { "prazo": "2026-10-07T09:00:00.000Z" } } ``` ### Test event `webhook.test` The event POST /v1/webhooks/endpoints/{id}/test sends to your endpoint, so you can check the URL and the signature verification. It does not go through any number. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `null` | yes | Sempre null neste tipo: o evento de teste não passa por nenhum número. | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `null` | yes | Sempre null neste tipo: o evento não passa por um número. | | `event_type` | `"webhook.test"` | yes | | | `webhook_test` | `object` | yes | Um evento de teste, enviado porque você pediu em POST /v1/webhooks/endpoints/{id}/test. Ele nunca aparece se você não pediu, não tem número nem conversa, e serve para conferir a URL e a verificação da assinatura. | | `webhook_test.endpoint_id` | `string (uuid)` | yes | O endpoint que pediu este teste, o mesmo id que POST /v1/webhooks/endpoints devolveu. | ```json { "version": "2026-11-10", "event_id": "6af3f85d8fedc8bb0f6d5bb6b4631e324574c539763c25cf113fd40db822cea8", "event_type": "webhook.test", "occurred_at": "2026-10-07T12:00:00.000Z", "phone_number_id": null, "number": null, "webhook_test": { "endpoint_id": "5c0e9a52-3a0e-4c3f-9f3e-0b3f6f1a2c77" } } ``` ### Reply sent from the phone app `message.echo` The business owner answered a customer from the WhatsApp Business app on the phone. It only occurs on a number connected in coexistence. message.wa_id is the recipient. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"message.echo"` | yes | | | `message` | `object` | yes | Uma mensagem que o dono do negócio escreveu pelo aplicativo WhatsApp Business do celular, num número conectado em coexistência. Só ocorre em número conectado em coexistência. É o sinal para um agente automatizado ficar quieto na conversa: um humano respondeu. A forma é a de message.received, e wa_id é o destinatário. Todo campo está sempre presente, e é nulo quando não se aplica. | | `message.id` | `string (uuid)` | yes | O identificador da mensagem na Luna. É o id que GET /v1/messages/{id}/media, POST /v1/messages/{id}/read, POST /v1/messages/{id}/typing e POST /v1/messages/{id}/replay pedem. | | `message.wamid` | `string` | yes | O identificador da mensagem na Meta. | | `message.wa_id` | `string \| null` | yes | O identificador do DESTINATÁRIO na Meta, em E.164 sem o sinal de mais: o cliente final para quem o dono do negócio escreveu. É a conversa onde o seu agente deve ficar quieto. Nulo quando a conversa é só de BSUID: use user_id. | | `message.user_id` | `string \| null` | yes | O BSUID do interlocutor, o identificador do usuário que não depende do telefone (por exemplo US.13491208655302741918), como a Meta o mandou. Nulo quando a Meta ainda não o mandou para esta conversa. Quando wa_id é nulo, é o único identificador do interlocutor. | | `message.parent_user_id` | `string \| null` | yes | O BSUID pai do interlocutor (por exemplo US.ENT.11815799212886844830). Só existe quando a Meta o manda; nulo no demais. | | `message.username` | `string \| null` | yes | O nome de usuário do interlocutor. Só existe quando ele adotou um; nulo no demais. | | `message.type` | `string` | yes | O tipo da mensagem, no vocabulário da Meta. | | `message.text` | `string \| null` | yes | O texto da mensagem, quando o tipo é texto. Nulo nos demais tipos: a legenda de uma mídia está em media.caption, e o título de um botão clicado em interactive.title. | | `message.profile_name` | `string \| null` | yes | O nome que o interlocutor exibe no WhatsApp. Nulo quando a Meta não o mandou. | | `message.media` | `object \| null` | yes | | | `message.media.mime_type` | `string \| null` | yes | O tipo MIME do arquivo, como a Meta o informou. Nulo na mídia enviada: a Luna não guarda os dados do arquivo que você subiu. | | `message.media.sha256` | `string \| null` | yes | O resumo SHA-256 do arquivo, como a Meta o informou. Nulo na mídia enviada, pela mesma razão do mime_type. | | `message.media.caption` | `string \| null` | yes | A legenda. Nula em áudio e em figurinha, e quando o interlocutor não escreveu uma. | | `message.media.filename` | `string \| null` | yes | O nome do arquivo. Só documento tem. | | `message.media.voice` | `boolean \| null` | yes | Verdadeiro quando o áudio foi gravado na hora, como mensagem de voz. Só áudio tem. | | `message.media.animated` | `boolean \| null` | yes | Verdadeiro quando a figurinha é animada. Só figurinha tem. | | `message.media.url` | `string \| null` | yes | Link da Luna para baixar o arquivo, sem chave de API: GET desse endereço responde 302 para uma URL assinada de vida curta. É credencial de portador (quem tiver o link baixa o arquivo): não registre em log. É o mesmo em toda reentrega do aviso, e vale por 30 dias contados do recebimento. Se a Luna ainda estiver baixando o arquivo da Meta, responde 409 com Retry-After: tente de novo. Nulo quando a mídia não pode ser obtida (a Meta não mandou identificador, ou o prazo de obtenção acabou). GET /v1/messages/{id}/media, com chave, continua valendo. | | `message.interactive` | `object \| null` | yes | A resposta a uma mensagem interativa que você enviou: o botão ou o item que o interlocutor escolheu. | | `message.interactive.type` | `string \| null` | yes | Qual resposta foi dada: button_reply (botão de resposta), list_reply (item de lista) ou nfm_reply (resposta de um Flow). | | `message.interactive.id` | `string \| null` | yes | O id que você deu ao botão ou ao item quando enviou a mensagem. Nulo em nfm_reply. | | `message.interactive.title` | `string \| null` | yes | O título do botão ou do item, como estava na mensagem. Nulo em nfm_reply. | | `message.interactive.description` | `string \| null` | yes | A descrição do item da lista. Nula nos demais. | | `message.interactive.name` | `string \| null` | yes | O nome do Flow. Só em nfm_reply. | | `message.interactive.response_json` | `string \| null` | yes | As respostas do Flow, como o texto JSON que a Meta mandou, sem interpretar. Só em nfm_reply. | | `message.button` | `object \| null` | yes | O clique num botão de resposta rápida de um template. | | `message.button.payload` | `string \| null` | yes | O payload que você definiu no botão de resposta rápida do template. | | `message.button.text` | `string \| null` | yes | O texto do botão. | | `message.location` | `object \| null` | yes | A localização que o interlocutor compartilhou. | | `message.location.latitude` | `number \| null` | yes | A latitude, em graus decimais. | | `message.location.longitude` | `number \| null` | yes | A longitude, em graus decimais. | | `message.location.name` | `string \| null` | yes | O nome do lugar, quando o interlocutor escolheu um. | | `message.location.address` | `string \| null` | yes | O endereço, quando há. | | `message.location.url` | `string \| null` | yes | O endereço web do lugar, quando há. | | `message.contacts` | `array \| null` | yes | Os cartões de contato que o interlocutor compartilhou. | | `message.contacts[].name` | `object \| null` | yes | O nome do contato, nos campos da Meta. | | `message.contacts[].name.formatted_name` | `string \| null` | yes | | | `message.contacts[].name.first_name` | `string \| null` | yes | | | `message.contacts[].name.last_name` | `string \| null` | yes | | | `message.contacts[].name.middle_name` | `string \| null` | yes | | | `message.contacts[].name.prefix` | `string \| null` | yes | | | `message.contacts[].name.suffix` | `string \| null` | yes | | | `message.contacts[].phones` | `array \| null` | yes | Os telefones do contato. wa_id só existe quando o telefone tem WhatsApp. | | `message.contacts[].phones[].phone` | `string \| null` | yes | | | `message.contacts[].phones[].wa_id` | `string \| null` | yes | | | `message.contacts[].phones[].type` | `string \| null` | yes | | | `message.contacts[].emails` | `array \| null` | yes | Os e-mails do contato. | | `message.contacts[].emails[].email` | `string \| null` | yes | | | `message.contacts[].emails[].type` | `string \| null` | yes | | | `message.contacts[].org` | `object \| null` | yes | A organização do contato. | | `message.contacts[].org.company` | `string \| null` | yes | | | `message.contacts[].org.department` | `string \| null` | yes | | | `message.contacts[].org.title` | `string \| null` | yes | | | `message.reaction` | `object \| null` | yes | A reação a uma mensagem, ou a retirada dela. | | `message.reaction.wamid` | `string \| null` | yes | O wamid da mensagem que recebeu a reação. | | `message.reaction.emoji` | `string \| null` | yes | O emoji. Nulo quando o interlocutor retirou a reação. | | `message.context` | `object \| null` | yes | A resposta citando uma mensagem, ou o aviso de que a mensagem foi encaminhada. | | `message.context.wamid` | `string \| null` | yes | O wamid da mensagem que o interlocutor citou ao responder. | | `message.context.from` | `string \| null` | yes | Quem enviou a mensagem citada. | | `message.context.forwarded` | `boolean \| null` | yes | Verdadeiro quando a mensagem foi encaminhada. | | `message.context.frequently_forwarded` | `boolean \| null` | yes | Verdadeiro quando a mensagem foi encaminhada muitas vezes. | | `message.referral` | `object \| null` | yes | O anúncio Click to WhatsApp ou a publicação que levou o interlocutor a escrever. | | `message.referral.source_type` | `string \| null` | yes | A origem do clique, como ad ou post. | | `message.referral.source_id` | `string \| null` | yes | O identificador do anúncio ou da publicação na Meta. | | `message.referral.source_url` | `string \| null` | yes | O endereço do anúncio ou da publicação. | | `message.referral.headline` | `string \| null` | yes | O título do anúncio. | | `message.referral.body` | `string \| null` | yes | O texto do anúncio. | | `message.referral.media_type` | `string \| null` | yes | O tipo da mídia do anúncio, como image ou video. | | `message.referral.ctwa_clid` | `string \| null` | yes | O identificador do clique, para atribuição de conversão. | | `message.unsupported` | `object \| null` | yes | Presente quando o interlocutor mandou algo que a Cloud API não entrega (type é unsupported). Não há conteúdo a ler: o aviso existe para o seu agente poder responder "não consigo ver isso". | | `message.unsupported.code` | `integer \| null` | yes | O código de erro da Meta, como ela mandou (131051 é "tipo de mensagem sem suporte"). | | `message.unsupported.title` | `string \| null` | yes | O título do erro, como a Meta o mandou. | | `message.unsupported.details` | `string \| null` | yes | O detalhe do erro, como a Meta o mandou. | | `message.edit` | `object \| null` | yes | Presente quando o interlocutor editou uma mensagem que já tinha mandado (type é edit). | | `message.edit.wamid` | `string \| null` | yes | O wamid da mensagem que foi editada. | | `message.edit.type` | `string \| null` | yes | O tipo do conteúdo novo, como text. | | `message.edit.text` | `string \| null` | yes | O texto novo, quando o conteúdo novo é texto. | | `message.revoke` | `object \| null` | yes | Presente quando o interlocutor apagou uma mensagem para todos (type é revoke). | | `message.revoke.wamid` | `string \| null` | yes | O wamid da mensagem que o interlocutor apagou para todos. | | `message.order` | `object \| null` | yes | O pedido que o interlocutor montou num catálogo e enviou (type é order). | | `message.order.catalog_id` | `string \| null` | yes | O catálogo de onde veio o pedido. | | `message.order.text` | `string \| null` | yes | O texto que o interlocutor escreveu junto com o pedido. | | `message.order.items` | `array \| null` | yes | Os itens do pedido. | | `message.order.items[].product_retailer_id` | `string \| null` | yes | O identificador do produto no seu catálogo. | | `message.order.items[].quantity` | `string \| null` | yes | A quantidade pedida, como a Meta mandou. | | `message.order.items[].item_price` | `string \| null` | yes | O preço unitário, como a Meta mandou. | | `message.order.items[].currency` | `string \| null` | yes | A moeda do preço. | ```json { "version": "2026-11-10", "event_id": "01b53d46e858f6ab6c89e183ef9509d703f665f6cfe2eb1d6bb185df56224d88", "event_type": "message.echo", "occurred_at": "2026-10-07T13:02:30.250Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "message": { "id": "9a3e6b14-5c2d-4f81-b7a0-2d8e1c4f6a93", "wamid": "wamid.EXAMPLE_ECHO", "wa_id": "5511900000000", "user_id": "BR.13491208655302741918", "parent_user_id": null, "username": null, "type": "text", "text": "Oi, Maria! Já separei o seu pedido, sai hoje.", "profile_name": null, "media": null, "interactive": null, "button": null, "location": null, "contacts": null, "reaction": null, "context": null, "referral": null, "unsupported": null, "edit": null, "revoke": null, "order": null } } ``` ### A template changed state `template.status` Meta approved, rejected, paused or disabled a template, and the reason comes along when there is one. It has no number and no message. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `null` | yes | Sempre null neste tipo: o template pertence à conta de negócio, e não a um número. | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `null` | yes | Sempre null neste tipo: o evento não passa por um número. | | `event_type` | `"template.status"` | yes | | | `template` | `object` | yes | O estado de um template mudou na Meta: aprovado, rejeitado, pausado, desativado ou outro. Não tem número nem conversa, porque o template pertence à conta de negócio. | | `template.id` | `string (uuid)` | yes | O identificador do template na Luna, o mesmo que POST /v1/templates e GET /v1/templates devolvem. | | `template.name` | `string` | yes | O nome do template. | | `template.language` | `string` | yes | O idioma do template, no código da Meta. | | `template.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o template pertence, o mesmo id que GET /v1/business-accounts devolve em wabaId. | | `template.external_id` | `string \| null` | yes | O rótulo do cliente dono do template (o externalId que o seu sistema deu ao conectar o número). É o rótulo dos números da conta quando todos eles têm o mesmo. Nulo quando a conta tem números de clientes diferentes, quando algum número dela não tem rótulo e quando ela não tem número conectado: nesses casos, ligue o evento ao cliente por waba_id (GET /v1/business-accounts). | | `template.status` | `string` | yes | O novo estado do template, no vocabulário da Meta: APPROVED, REJECTED, PAUSED, DISABLED e outros. Novos estados podem aparecer. | | `template.category` | `string` | yes | A categoria do template, no vocabulário da Meta. | | `template.reason` | `string \| null` | yes | O motivo que a Meta informou para a rejeição ou a pausa. Nulo quando ela não informa um, como nas aprovações. | ```json { "version": "2026-11-10", "event_id": "821d41ec2c33a28abe8a0baf97db034baaef1dbe511a6e546a37eca4ad565c65", "event_type": "template.status", "occurred_at": "2026-10-07T13:20:00.000Z", "phone_number_id": null, "number": null, "template": { "id": "3f6a1c52-9d4e-4b87-a1f0-5e2c7b9d8a14", "name": "confirmacao_de_pedido", "language": "pt_BR", "waba_id": "102290129340398", "external_id": "cliente-8841", "status": "REJECTED", "category": "UTILITY", "reason": "INVALID_FORMAT" } } ``` ### Number connected `number.connected` A number finished connecting and is registered on the Cloud API. It is the signal that your customer completed the connection you opened with the connect link, and it carries their externalId. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object` | yes | Um número terminou de ser conectado e está registrado na Cloud API. É o sinal de que o seu cliente concluiu a conexão: você não precisa consultar a lista de números para descobrir. Para saber se o envio já está liberado, leia o campo ready de GET /v1/numbers/{id}. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `number.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o número pertence, o mesmo id que GET /v1/business-accounts devolve em wabaId. | | `number.coexistence` | `boolean` | yes | true quando a Luna já observou tráfego de coexistência neste número, ou seja, ele continua funcionando no aplicativo do celular. Pode ser false no instante da conexão e passar a true depois. O estado corrente está no campo coexistence de GET /v1/numbers/{id}. | | `event_type` | `"number.connected"` | yes | | ```json { "version": "2026-11-10", "event_id": "458470a340db14358f03ac02fde7e3839cb6887f3071c06c57a3d9d456621996", "event_type": "number.connected", "occurred_at": "2026-10-07T13:45:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "coexistence": false } } ``` ### Number waiting for a payment method at Meta `number.payment_required` Meta refused a send from this number for lack of a payment method on the business that owns the account (error 131042). It is sent once, when the state begins, and not for every refused message. The account owner fixes it in Meta’s WhatsApp Manager: Luna does not intermediate that payment. The Payment at Meta guide explains what to tell your customer. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object` | yes | A Meta recusou um envio deste número por falta de método de pagamento do negócio dono da conta (erro 131042). O número continua conectado e os eventos de entrada seguem chegando, mas os envios são recusados até o dono da conta cadastrar ou regularizar o método de pagamento no WhatsApp Manager da Meta. A Luna não intermedeia esse pagamento. O evento sai uma vez ao entrar no estado, e não a cada mensagem recusada: as mensagens recusadas chegam como message.status com status failed. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `number.awaiting_payment_since` | `string` | yes | Quando a Meta recusou o primeiro envio por falta de método de pagamento. É o mesmo valor que GET /v1/numbers/{id} devolve em awaitingPaymentSince enquanto a espera durar. | | `event_type` | `"number.payment_required"` | yes | | ```json { "version": "2026-11-10", "event_id": "50a49cee4b216c529e3f7cdd0be525f8902ff6aff66439e004dfe34a0c979fcf", "event_type": "number.payment_required", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "awaiting_payment_since": "2026-10-13T12:00:00.000Z" } } ``` ### Number sending again after the payment wait `number.payment_resolved` A send from this number was accepted by Meta again after a wait for a payment method. It is the only signal that payment was fixed: Meta does not announce it and offers no lookup. Messages refused during the wait are not resent on their own. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object` | yes | Um envio deste número voltou a ser aceito pela Meta depois de uma espera por método de pagamento. É o único sinal de que o pagamento foi regularizado: a Meta não avisa e não oferece consulta. As mensagens recusadas durante a espera não são reenviadas sozinhas; envie de novo o que ainda interessa. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `event_type` | `"number.payment_resolved"` | yes | | ```json { "version": "2026-11-10", "event_id": "6a956161dd17bb975533e63286e811ae62b77b3350107945952b2e53f0a9d1e2", "event_type": "number.payment_resolved", "occurred_at": "2026-10-13T15:30:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841" } } ``` ### Account restricted by Meta `account.restricted` Meta restricted the number’s WhatsApp Business account. It carries Meta’s type, deadline and guidance in restrictions. The notice belongs to the account: one event goes out per connected number of it, all with the same waba_id. The account owner fixes it in WhatsApp Manager. The Account health guide covers each case. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"account.restricted"` | yes | | | `waba` | `object` | yes | A Meta restringiu a conta de WhatsApp Business deste número. O que a restrição impede depende do tipo: confira restrictions[].restriction_type e o prazo em expiration. A Luna não levanta restrição; quem resolve é o dono da conta, no WhatsApp Manager da Meta. A Meta não avisa quando uma restrição por prazo termina. | | `waba.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `waba.number_id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `waba.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `waba.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `waba.restrictions` | `array` | yes | As restrições que a Meta aplicou à conta. Pode vir vazia quando a Meta avisa sem detalhar. | | `waba.restrictions[].restriction_type` | `string \| null` | yes | O tipo da restrição, no vocabulário da Meta. | | `waba.restrictions[].expiration` | `string \| null` | yes | Quando a restrição termina, como a Meta informou. Nulo quando ela não informa prazo. | | `waba.restrictions[].remediation` | `string \| null` | yes | O que a Meta diz que resolve a restrição, quando informa. | ```json { "version": "2026-11-10", "event_id": "d3b1b97cb8b69ac0bf9db087b5200febbea3dcbcc8d0a4108913592b51fdaf29", "event_type": "account.restricted", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "restrictions": [ { "restriction_type": "RESTRICTED_ADD_PHONE_NUMBER_ACTION", "expiration": "2026-11-13T12:00:00Z", "remediation": null } ] } } ``` ### Policy violation on the account `account.violation` Meta recorded a policy violation on the number’s WhatsApp Business account. It is a warning: the account can be restricted or disabled if the violation is not handled. One event goes out per number of the account. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"account.violation"` | yes | | | `waba` | `object` | yes | A Meta registrou uma violação de política na conta de WhatsApp Business deste número. É um aviso: a conta pode ser restringida ou desativada se a violação não for tratada. O dono da conta lê os detalhes no WhatsApp Manager da Meta. | | `waba.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `waba.number_id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `waba.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `waba.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `waba.violation_type` | `string \| null` | yes | O tipo da violação, no vocabulário da Meta. | ```json { "version": "2026-11-10", "event_id": "a2fa828795bf24fd8e7460738c1a1e11a1bcd278fc09a0d238f92ba8c5994441", "event_type": "account.violation", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "violation_type": "ALCOHOL_VIOLATION" } } ``` ### Account disabled by Meta `account.disabled` Meta disabled the number’s WhatsApp Business account, and sends stop being accepted. Luna does not reinstate accounts: the owner asks Meta for a review. One event goes out per number of the account, and account.reinstated announces it if the account comes back. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"account.disabled"` | yes | | | `waba` | `object` | yes | A Meta desativou a conta de WhatsApp Business deste número. Os envios param de ser aceitos. A Luna não reativa conta: o dono dela pede a revisão à Meta, e o evento account.reinstated avisa se a conta voltar. | | `waba.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `waba.number_id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `waba.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `waba.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `waba.ban_date` | `string \| null` | yes | A data da desativação, como a Meta informou. | ```json { "version": "2026-11-10", "event_id": "b0308dcc1ab6324eaea0474f1bcdec28146d3a6eb62668a1425fb3a7d6aad778", "event_type": "account.disabled", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "ban_date": "2026-10-13" } } ``` ### Account reinstated by Meta `account.reinstated` Meta reinstated the number’s WhatsApp Business account after a deactivation. One event goes out per number of the account. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"account.reinstated"` | yes | | | `waba` | `object` | yes | A Meta reativou a conta de WhatsApp Business deste número depois de uma desativação. | | `waba.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `waba.number_id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `waba.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `waba.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `waba.ban_date` | `string \| null` | yes | A data informada pela Meta junto com a reativação, quando houver. | ```json { "version": "2026-11-10", "event_id": "135a9c7b3f192a7cab5ea55f68e0a8113e8d8e80acaa0ae8dad7f20aaf61f2db", "event_type": "account.reinstated", "occurred_at": "2026-10-14T09:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "ban_date": null } } ``` ### Another account notice from Meta `account.update` An account notice from Meta that Luna does not translate into a type of its own, with Meta’s raw event field (for example ACCOUNT_DELETED, ACCOUNT_RECONNECTED or VOLUME_BASED_PRICING_TIER_UPDATE). If you do not use it, ignore it. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"account.update"` | yes | | | `waba` | `object` | yes | Um aviso de conta da Meta que a Luna não traduz em um tipo próprio. Chega com o event cru da Meta para que o seu sistema decida o que fazer com ele. Se você não usa, ignore. | | `waba.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `waba.number_id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `waba.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `waba.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `waba.event` | `string` | yes | O campo event do aviso account_update da Meta, sem tradução: ACCOUNT_DELETED, ACCOUNT_RECONNECTED, VOLUME_BASED_PRICING_TIER_UPDATE, DISABLED_UPDATE com um estado que não é desativação nem reativação, e outros. Novos valores podem aparecer. | | `waba.details` | `object` | yes | O restante do aviso da Meta, como ela mandou, sem o campo event. | ```json { "version": "2026-11-10", "event_id": "f663ad9f077e865db5d29245db96fe579e9aaa487bdf2f9d91a6e535af3d7949", "event_type": "account.update", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "event": "ACCOUNT_DELETED", "details": {} } } ``` ### Account limit changed `account.limit_changed` Meta changed the account limit: the messaging limit, which counts unique people outside the customer service window (TIER_250, TIER_2K, TIER_10K, TIER_100K or TIER_UNLIMITED), or the number ceiling. It is the granted ceiling, never how much was used. It holds for the whole portfolio, so one event goes out per number of the account. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"account.limit_changed"` | yes | | | `waba` | `object` | yes | A Meta mudou o limite desta conta. O limite é do portfólio de negócio, e vale para todos os números da conta. O valor corrente de cada número está em limiteDiarioDeConversas, em GET /v1/numbers. | | `waba.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `waba.number_id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `waba.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `waba.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `waba.daily_conversation_limit` | `string \| null` | yes | O limite de mensagens da Meta, no nome de faixa dela: TIER_250, TIER_2K, TIER_10K, TIER_100K ou TIER_UNLIMITED (250, 2.000, 10.000 e 100.000 pessoas por período de 24 horas, ou sem teto). Conta pessoas únicas a quem o negócio escreve fora da janela de atendimento, e é do portfólio empresarial. É o teto concedido, e nunca quanto foi usado. Nulo quando o aviso mudou só o limite de números. | | `waba.max_phone_numbers_per_waba` | `number \| null` | yes | Quantos números a Meta permite nesta conta. Nulo quando o aviso mudou só o limite de conversas. | ```json { "version": "2026-11-10", "event_id": "a3bddf693de91539edaebb432d0d4f936b40822085cafa5c7864ae149756dbff", "event_type": "account.limit_changed", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "daily_conversation_limit": "TIER_2K", "max_phone_numbers_per_waba": null } } ``` ### Number disconnected `number.disconnected` The number is no longer connected to Luna: the customer removed the app, Luna was removed as the account’s partner, the account’s link to Luna was ended, or you disconnected it with DELETE /v1/numbers/{id} (reason requested_by_tenant). It is the pair of number.connected. To come back, your customer connects again with a new connect link. The reason is in the reason field. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object` | yes | O número deixou de estar conectado à Luna. É o par de number.connected. Os envios deste número não funcionam mais; para voltar, o seu cliente precisa conectar de novo, com um novo link de conexão. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `number.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `number.reason` | `string` | yes | O motivo da desconexão: requested_by_tenant (você desconectou o número com DELETE /v1/numbers/{id}), ou o aviso da Meta que a causou, PARTNER_APP_UNINSTALLED (o cliente removeu o aplicativo), PARTNER_REMOVED (a Luna foi removida como parceira da conta) ou ACCOUNT_OFFBOARDED (o vínculo da conta com a Luna foi encerrado). Novos valores podem aparecer. | | `number.disconnection_reason` | `string \| null` | yes | O motivo que a Meta informou em disconnection_info, quando informa. | | `number.initiated_by` | `string \| null` | yes | Quem iniciou a desconexão, como a Meta informou. | | `event_type` | `"number.disconnected"` | yes | | ```json { "version": "2026-11-10", "event_id": "0dfe4e31d4e40e4a5da6d3f42f0d44b660f67ce551b2a43966e5fb0390fcd741", "event_type": "number.disconnected", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "reason": "PARTNER_APP_UNINSTALLED", "disconnection_reason": null, "initiated_by": null } } ``` ### Number quality changed `number.quality_changed` The number’s quality rating changed (GREEN, YELLOW, RED). Meta has no webhook for this: Luna checks quality periodically, so the event arrives with a delay of up to about an hour. The history is in GET /v1/numbers/{id}/health. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object` | yes | A avaliação de qualidade do número mudou. A Meta não tem webhook para isso: a Luna confere a qualidade de cada número periodicamente, então o evento chega com atraso de até a cadência da conferência (cerca de uma hora). O histórico está em GET /v1/numbers/{id}/health. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `number.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `number.previous_quality_rating` | `string` | yes | A avaliação de qualidade anterior, no vocabulário da Meta: GREEN, YELLOW, RED. | | `number.quality_rating` | `string` | yes | A avaliação de qualidade atual, no vocabulário da Meta. | | `event_type` | `"number.quality_changed"` | yes | | ```json { "version": "2026-11-10", "event_id": "cc81de4eb28ad6a80e39c6cca13eb4b6db12f223f3c1346552cbc24795bcdbbe", "event_type": "number.quality_changed", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "previous_quality_rating": "GREEN", "quality_rating": "YELLOW" } } ``` ### Display name reviewed `number.display_name_reviewed` The review state of the number’s display name changed (status: approved, pending_review, declined, expired or none), for example from pending_review to approved or declined. name is the name the state refers to. Meta does not report the reason for a refusal in this query. Luna checks the name periodically, so the event arrives with a delay of up to about an hour. An approved name only takes effect after the number is registered again. The current state is in displayNameStatus, in GET /v1/numbers/{id}. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object` | yes | O estado da revisão do nome de exibição do número mudou, por exemplo de pending_review para approved ou declined. A Luna confere o nome de cada número periodicamente, então o evento chega com atraso de até cerca de uma hora. Um nome aprovado só passa a valer depois que o número é registrado de novo; o estado corrente está em displayNameStatus, em GET /v1/numbers/{id}. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `number.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `number.status` | `string` | yes | O estado da revisão do nome de exibição, o mesmo de displayNameStatus em GET /v1/numbers/{id}: approved, pending_review, declined, expired ou none. Novos valores podem aparecer. | | `number.name` | `string \| null` | yes | O nome a que o estado se refere: o nome pedido, quando há um pedido, senão o nome em uso. Nulo quando a Meta não informou. | | `event_type` | `"number.display_name_reviewed"` | yes | | ```json { "version": "2026-11-10", "event_id": "23fd01fabc59f4c9ffda20955726e7e3e19c6a05cf609197c8b3c0aef8405e76", "event_type": "number.display_name_reviewed", "occurred_at": "2026-11-04T14:20:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "status": "declined", "name": "Clínica Sorriso Centro" } } ``` ### Customer authorization about to expire `number.credential_expiring` The authorization the customer gave Luna to operate the number expires within 14 days (credential_expires_at). To renew it, the customer reconnects: create a link with POST /v1/onboarding/links passing numberId and it opens the reconnection of this number directly, without counting a new number. It goes out once per expiry and per number of the account. An authorization issued without an expiry never produces this event. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object` | yes | A autorização que o cliente deu à Luna para operar este número vence em até 14 dias. Para renovar, o seu cliente refaz a conexão: abra um link com POST /v1/onboarding/links informando numberId, e ele cai direto na reconexão deste número, sem contar um número novo. O evento sai uma vez por vencimento e por número, e não se repete a cada dia. Se a autorização foi emitida sem prazo, ele não sai nunca. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `number.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `number.credential_expires_at` | `string` | yes | Quando a autorização que o cliente deu à Luna vence, em ISO-8601 UTC. É o mesmo valor que GET /v1/business-accounts devolve em credentialExpiresAt. Depois dessa data a Meta recusa as chamadas da Luna nesta conta, e o número para de enviar e de receber. | | `event_type` | `"number.credential_expiring"` | yes | | ```json { "version": "2026-11-10", "event_id": "33b03111fe7f1f225626ece55b50955389e78742a6b99059f05be056ce2b2260", "event_type": "number.credential_expiring", "occurred_at": "2026-11-21T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398", "credential_expires_at": "2026-12-05T12:00:00.000Z" } } ``` ### Alert from Meta about the account `account.alert` Meta sent an alert about the number’s WhatsApp Business account (the account_alerts field), for example a denied limit increase or a lost profile picture. The fields arrive as Meta sent them, untranslated. The alert belongs to the account: one event goes out per connected number of it, all with the same waba_id. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"account.alert"` | yes | | | `waba` | `object` | yes | A Meta mandou um alerta sobre a conta de WhatsApp Business deste número (o campo account_alerts). Os campos chegam como a Meta mandou, sem tradução. O alerta é da conta: sai um evento por número conectado dela, todos com o mesmo waba_id. Quem resolve é o dono da conta, no WhatsApp Manager da Meta. | | `waba.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o aviso se refere. O aviso é da conta inteira: a Luna entrega um evento por número conectado dela, todos com o mesmo waba_id. | | `waba.number_id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `waba.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `waba.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `waba.entity_type` | `string \| null` | yes | A que o alerta se refere, como a Meta informou (por exemplo a conta, o portfólio ou um número). | | `waba.entity_id` | `string \| null` | yes | O identificador, na Meta, do que o alerta cita. | | `waba.alert_severity` | `string \| null` | yes | A gravidade que a Meta atribuiu ao alerta, no vocabulário dela. | | `waba.alert_status` | `string \| null` | yes | Se o alerta está ativo ou foi resolvido, no vocabulário da Meta. | | `waba.alert_type` | `string \| null` | yes | O tipo do alerta, no vocabulário da Meta: por exemplo INCREASED_CAPABILITIES_ELIGIBILITY_DEFERRED, INCREASED_CAPABILITIES_ELIGIBILITY_FAILED, INCREASED_CAPABILITIES_ELIGIBILITY_NEED_MORE_INFO ou PROFILE_PICTURE_LOST. Novos valores podem aparecer. | | `waba.alert_description` | `string \| null` | yes | A descrição do alerta, em texto, como a Meta mandou. | | `waba.details` | `object` | yes | O restante do alerta, como a Meta mandou, para o que a Luna ainda não nomeia. | ```json { "version": "2026-11-10", "event_id": "fb613a0660724669d9251d4185488ec26409b34345c592b908ce9747b8430f99", "event_type": "account.alert", "occurred_at": "2026-10-19T12:00:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "external_id": "cliente-8841" }, "waba": { "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "entity_type": "WABA", "entity_id": "102290129340398", "alert_severity": "INFORMATIONAL", "alert_status": "ACTIVE", "alert_type": "INCREASED_CAPABILITIES_ELIGIBILITY_DEFERRED", "alert_description": "Messaging limit increase deferred.", "details": {} } } ``` ### Number needs action `number.action_required` This number now needs an action from you or your customer: the customer authorization expiring or expired, no payment method at Meta, a restricted or disabled account, a PIN requested, registration blocked or a suspended plan. It carries status, can_send and reasons, each cause with code, message and solution, ready to show to your customer. It goes out when the list of causes goes from empty to non-empty, and not at every change to it; it is the same calculation as connection in GET /v1/numbers/{id}. When the list empties, number.action_resolved goes out. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object` | yes | Este número passou a precisar de uma ação sua ou do seu cliente: autorização vencendo ou vencida, método de pagamento ausente na Meta, conta restrita ou desativada, PIN pedido, registro bloqueado ou plano suspenso. Sai quando a lista de motivos passa de vazia para não vazia, e não a cada mudança dela. Mostra o motivo ao seu cliente com message e solution. Quando a lista esvazia, sai number.action_resolved. O estado corrente está em connection, em GET /v1/numbers/{id}. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `number.status` | `string` | yes | O estado resumido da conexão, o mesmo de connection.status em GET /v1/numbers/{id}. · Values: connected, connecting, action_required, disconnected | | `number.can_send` | `boolean` | yes | Se o envio por este número vai funcionar agora, o mesmo de connection.canSend. | | `number.reasons` | `array` | yes | Os motivos, os mesmos de connection.reasons em GET /v1/numbers/{id}, no instante do evento. · at least 1 items | | `number.reasons[].code` | `string` | yes | O código do motivo, para o seu código comparar: pin_required, registration_blocked, credential_invalid, credential_expired, credential_expiring, payment_required, payment_method_missing, account_restricted, account_disabled, trial_expired, account_blocked. Novos códigos podem aparecer. | | `number.reasons[].message` | `string` | yes | O que está acontecendo, em português, pronto para repassar ao seu cliente. | | `number.reasons[].solution` | `string` | yes | O que fazer a respeito, em português. | | `event_type` | `"number.action_required"` | yes | | ```json { "version": "2026-11-10", "event_id": "8832cdd12544436fce3b39d709158baa046091d010b5ed144a289c81b807c710", "event_type": "number.action_required", "occurred_at": "2026-10-28T15:02:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "status": "action_required", "can_send": false, "reasons": [ { "code": "payment_required", "message": "A Meta recusou um envio deste número por falta de método de pagamento na conta de WhatsApp Business do negócio.", "solution": "O dono da conta cadastra o método de pagamento no WhatsApp Manager da Meta. A Luna não intermedeia esse pagamento. Quando um envio voltar a ser aceito, o aviso sai do ar." } ] } } ``` ### Number no longer needs action `number.action_resolved` The number no longer needs action: the list of causes in connection emptied, after a number.action_required. It is its pair, as number.payment_resolved is the pair of number.payment_required. status says how the connection ended up. A number you disconnected does not produce this event: number.disconnected already announced it. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object` | yes | Este número não precisa mais de ação: a lista de motivos de connection esvaziou, depois de um number.action_required. É o par dele, como number.payment_resolved é o de number.payment_required. status diz como a conexão ficou (connected, ou connecting se a conexão voltou a estar em curso). | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele ao criar o link de conexão (externalId em POST /v1/onboarding/links). Nulo quando o número foi conectado sem link. | | `number.status` | `string` | yes | O estado resumido da conexão, o mesmo de connection.status em GET /v1/numbers/{id}. · Values: connected, connecting, action_required, disconnected | | `number.can_send` | `boolean` | yes | Se o envio por este número vai funcionar agora, o mesmo de connection.canSend. | | `event_type` | `"number.action_resolved"` | yes | | ```json { "version": "2026-11-10", "event_id": "3279de99ef1bc2ade5d88bde7a2fd878b8faabddc179b8dceebded74d5b7394b", "event_type": "number.action_resolved", "occurred_at": "2026-10-28T15:40:00.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "status": "connected", "can_send": true } } ``` ### Connect link completed `onboarding.link.completed` Your customer completed the connection through a link: the link becomes used. It carries the link externalId and, when Luna has already registered the number, number_id; the number.connected event announces when the number is ready to send. It goes out once per link. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string \| null` | yes | O número do link de reconexão ou o que resultou da conexão, ou null quando o evento não tem número. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número que resultou da conexão, no mesmo formato dos eventos number.*, com waba_id. Nulo quando a conta foi conectada sem número, ou quando a Luna ainda não o registrou: o evento number.connected avisa quando ele fica pronto. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.display_number` | `string \| null` | yes | O número de telefone, como a Meta o exibe. Nulo quando a Meta ainda não o informou. | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `number.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o número pertence, o mesmo id que GET /v1/business-accounts devolve em wabaId. | | `event_type` | `"onboarding.link.completed"` | yes | | | `link` | `object` | yes | O seu cliente concluiu a conexão por um link: ele aceitou os termos da Meta e a Luna recebeu o acesso à conta dele. É o fim do link, que passa a used. O número pode ainda estar sendo registrado: quem avisa que ele ficou pronto para enviar é number.connected. Sai uma vez por link. | | `link.id` | `string (uuid)` | yes | O identificador do link, o mesmo que POST /v1/onboarding/links devolveu. | | `link.external_id` | `string \| null` | yes | O externalId que você deu ao criar o link, sem alteração. Nulo quando o link foi criado sem ele. | | `link.used_at` | `string` | yes | Quando a conexão por este link concluiu, o mesmo usedAt de GET /v1/onboarding/links/{id}. | | `link.waba_id` | `string \| null` | yes | A conta de WhatsApp Business que o seu cliente conectou, o mesmo id que GET /v1/business-accounts devolve em wabaId. Está preenchido mesmo quando a conta foi conectada sem número (number_id nulo). Nulo só se a Luna não a leu. | | `link.number_id` | `string (uuid) \| null` | yes | O número que resultou da conexão, o mesmo id de GET /v1/numbers. Nulo quando a conta foi conectada sem número, ou quando a Luna ainda não o registrou: o evento number.connected avisa quando ele fica pronto. | ```json { "version": "2026-11-10", "event_id": "fd3596b2273541c7a77c69cb8a2ddb0e060052ddc84f251b5a76961053b578b1", "event_type": "onboarding.link.completed", "occurred_at": "2026-10-28T15:30:12.000Z", "phone_number_id": "123456789012345", "number": { "id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b", "phone_number_id": "123456789012345", "display_number": "+55 11 90000-0000", "external_id": "cliente-8841", "waba_id": "102290129340398" }, "link": { "id": "7c3e5a19-2b4d-4f60-8a1e-9d0b3c5f7a21", "external_id": "cliente-8841", "used_at": "2026-10-28T15:30:12.000Z", "waba_id": "102290129340398", "number_id": "5b9e2c40-71d3-4f0a-9a8b-2c1d0e3f4a5b" } } ``` ### Connect link opened `onboarding.link.opened` Your customer opened the link for the first time. It goes out once per link, and not again when they come back to the page or try again. It carries the link externalId and opened_at. It is the start of the cycle: onboarding.link.completed, onboarding.link.failed or onboarding.link.expired follow. Whoever opened and never completed shows up here without a completed. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string \| null` | yes | O número do link de reconexão, ou null quando o link é de uma conexão nova. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"onboarding.link.opened"` | yes | | | `link` | `object` | yes | O seu cliente abriu o link pela primeira vez. Sai uma vez por link, na primeira abertura, e não de novo quando ele volta à página ou tenta outra vez. É o começo do ciclo: depois dele vêm onboarding.link.completed, onboarding.link.failed ou onboarding.link.expired. Quem abriu e nunca concluiu aparece aqui sem um completed. | | `link.id` | `string (uuid)` | yes | O identificador do link, o mesmo que POST /v1/onboarding/links devolveu. | | `link.external_id` | `string \| null` | yes | O externalId que você deu ao criar o link, sem alteração. Nulo quando o link foi criado sem ele. | | `link.opened_at` | `string` | yes | Quando o seu cliente abriu o link pela primeira vez. | ```json { "version": "2026-11-10", "event_id": "b8a277c5c9377c213ee4c3b79c3e83829f3bef5f69521db1a0434da05acfbc1d", "event_type": "onboarding.link.opened", "occurred_at": "2026-10-28T15:21:40.000Z", "phone_number_id": null, "number": null, "link": { "id": "7c3e5a19-2b4d-4f60-8a1e-9d0b3c5f7a21", "external_id": "cliente-8841", "opened_at": "2026-10-28T15:21:40.000Z" } } ``` ### A connect link attempt did not work out `onboarding.link.failed` A connection attempt through a link did not work out. reason says why: abandoned (the customer closed Meta’s window, and step carries the screen where they stopped), error (Meta’s window reported an error, in error_code), failed (Luna tried to complete and could not), country_not_supported (the number is not +55) or registration_blocked (Meta blocked registration for 72 hours). The link stays open until it expires. It goes out once per attempt. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string \| null` | yes | O número do link de reconexão, ou null quando o link é de uma conexão nova. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"onboarding.link.failed"` | yes | | | `link` | `object` | yes | Uma tentativa de conexão por um link não deu certo: o cliente desistiu em alguma tela, a janela da Meta relatou um erro, ou a conexão parou. O link continua aberto até vencer, e o cliente pode tentar de novo. Sai uma vez por tentativa. O que o cliente deve fazer para cada reason está no guia Conectar um número. | | `link.id` | `string (uuid)` | yes | O identificador do link, o mesmo que POST /v1/onboarding/links devolveu. | | `link.external_id` | `string \| null` | yes | O externalId que você deu ao criar o link, sem alteração. Nulo quando o link foi criado sem ele. | | `link.session_id` | `string (uuid)` | yes | A tentativa de conexão que não deu certo. Um link aberto admite várias. | | `link.reason` | `string` | yes | Por que a tentativa não deu certo: abandoned (o cliente fechou a janela da Meta e a tela em que parou está em step), error (a janela da Meta relatou um erro, em error_code), failed (a Luna tentou concluir várias vezes e não conseguiu), country_not_supported (o número escolhido não é +55) ou registration_blocked (a Meta bloqueou o registro do número por 72 horas). Novos motivos podem aparecer. · Values: abandoned, error, failed, country_not_supported, registration_blocked | | `link.step` | `string \| null` | yes | O nome da tela da janela da Meta em que o cliente parou, como o navegador relatou. Nulo quando não foi relatado. | | `link.error_code` | `integer \| null` | yes | O código de erro que a janela da Meta relatou. Nulo quando não houve erro relatado. | ```json { "version": "2026-11-10", "event_id": "cabf3f3478bda2efd0e9a3726d503dbcd575bec16cc0ccf5fc65cdcb4c88cea3", "event_type": "onboarding.link.failed", "occurred_at": "2026-10-28T15:12:40.000Z", "phone_number_id": null, "number": null, "link": { "id": "7c3e5a19-2b4d-4f60-8a1e-9d0b3c5f7a21", "external_id": "cliente-8841", "session_id": "2e8f4b60-1a3c-4d57-9b0e-6c7d8e9f0a12", "reason": "abandoned", "step": "phone_number_setup", "error_code": null } } ``` ### Connect link expired `onboarding.link.expired` The link expired with nobody completing the connection. Create another with POST /v1/onboarding/links whenever you want. A used link never produces this event. It goes out once per link. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `string \| null` | yes | O número do link de reconexão, ou null quando o link é de uma conexão nova. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `object \| null` | yes | O número por onde o evento passou: id da Luna, phone_number_id da Meta e external_id, o rótulo que o seu sistema deu ao cliente. Está em todo evento que passa por um número, para você separar os eventos de N clientes com um endpoint só. Nos eventos number.* este mesmo objeto traz também os campos próprios do evento. Nulo nos eventos que não passam por número. | | `number.id` | `string (uuid)` | yes | O identificador do número na Luna, o mesmo que GET /v1/numbers devolve. | | `number.phone_number_id` | `string` | yes | O identificador do número na Meta, o mesmo que a listagem de números devolve. · 1 to 64 characters · /^[A-Za-z0-9_-]+$/ | | `number.external_id` | `string \| null` | yes | O rótulo que o seu sistema deu ao cliente dele (externalId no link de conexão ou em PATCH /v1/numbers/{id}). Nulo quando o número não tem rótulo. É com ele que um endpoint só separa os eventos de todos os seus clientes. | | `event_type` | `"onboarding.link.expired"` | yes | | | `link` | `object` | yes | O link venceu sem ninguém concluir a conexão. Gere outro com POST /v1/onboarding/links quando quiser. Um link que foi usado nunca gera este evento. Sai uma vez por link. | | `link.id` | `string (uuid)` | yes | O identificador do link, o mesmo que POST /v1/onboarding/links devolveu. | | `link.external_id` | `string \| null` | yes | O externalId que você deu ao criar o link, sem alteração. Nulo quando o link foi criado sem ele. | | `link.expired_at` | `string` | yes | Quando o link venceu, o mesmo expiresAt de GET /v1/onboarding/links/{id}. | ```json { "version": "2026-11-10", "event_id": "1df73af80cf86f74267290bc13fcd1f82551997dd79845170b35c78f40b563ad", "event_type": "onboarding.link.expired", "occurred_at": "2026-10-31T15:00:00.000Z", "phone_number_id": null, "number": null, "link": { "id": "7c3e5a19-2b4d-4f60-8a1e-9d0b3c5f7a21", "external_id": "cliente-8841", "expired_at": "2026-10-31T15:00:00.000Z" } } ``` ### A template category changed `template.category` Meta changed, or announced it will change, a template category. The category sets the price Meta charges the business: from UTILITY to MARKETING, the price goes up. It arrives as an advance notice (correct_category and scheduled_for) and as a change made (previous_category and new_category). It has no number and no message. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `null` | yes | Sempre null neste tipo: o template pertence à conta de negócio, e não a um número. | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `null` | yes | Sempre null neste tipo: o evento não passa por um número. | | `event_type` | `"template.category"` | yes | | | `template` | `object` | yes | A Meta mudou, ou vai mudar, a categoria de um template. Chega de duas formas: o aviso prévio (correct_category e scheduled_for preenchidos) e a mudança feita (previous_category e new_category preenchidos). A categoria define o preço que a Meta cobra do negócio por mensagem: de UTILITY para MARKETING, o preço sobe. Quem paga é o dono da conta, direto à Meta. | | `template.id` | `string (uuid)` | yes | O identificador do template na Luna, o mesmo que POST /v1/templates e GET /v1/templates devolvem. | | `template.name` | `string` | yes | O nome do template. | | `template.language` | `string` | yes | O idioma do template, no código da Meta. | | `template.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o template pertence, o mesmo id que GET /v1/business-accounts devolve em wabaId. | | `template.external_id` | `string \| null` | yes | O rótulo do cliente dono do template (o externalId que o seu sistema deu ao conectar o número). É o rótulo dos números da conta quando todos eles têm o mesmo. Nulo quando a conta tem números de clientes diferentes, quando algum número dela não tem rótulo e quando ela não tem número conectado: nesses casos, ligue o evento ao cliente por waba_id (GET /v1/business-accounts). | | `template.category` | `string` | yes | A categoria do template, no vocabulário da Meta. | | `template.previous_category` | `string \| null` | yes | A categoria de antes, quando a mudança já foi feita. Nulo no aviso prévio. | | `template.new_category` | `string \| null` | yes | A categoria de agora, quando a mudança já foi feita. Nulo no aviso prévio. | | `template.correct_category` | `string \| null` | yes | No aviso prévio, a categoria para a qual a Meta vai mudar o template. Nulo quando a mudança já foi feita. | | `template.scheduled_for` | `string \| null` | yes | No aviso prévio, quando a Meta aplica a mudança. Nulo quando a mudança já foi feita. | ```json { "version": "2026-11-10", "event_id": "67e825cdeb1f139ea3f76761c2e087a272352caca49dea9ab471383293a8ca07", "event_type": "template.category", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": null, "number": null, "template": { "id": "3f6a1c52-9d4e-4b87-a1f0-5e2c7b9d8a14", "name": "pedido_confirmado", "language": "pt_BR", "waba_id": "102290129340398", "external_id": "cliente-8841", "category": "UTILITY", "previous_category": null, "new_category": null, "correct_category": "MARKETING", "scheduled_for": "2026-10-14T17:46:40.000Z" } } ``` ```json { "version": "2026-11-10", "event_id": "a088e870f11e399bc1d40266c5d07e18d0b13da6d1cf4d2021cbb232451ed86d", "event_type": "template.category", "occurred_at": "2026-10-14T17:46:40.000Z", "phone_number_id": null, "number": null, "template": { "id": "3f6a1c52-9d4e-4b87-a1f0-5e2c7b9d8a14", "name": "pedido_confirmado", "language": "pt_BR", "waba_id": "102290129340398", "external_id": "cliente-8841", "category": "MARKETING", "previous_category": "UTILITY", "new_category": "MARKETING", "correct_category": null, "scheduled_for": null } } ``` ### A template quality changed `template.quality` A template quality score changed (GREEN, YELLOW, RED). A low score comes before Meta pauses the template. It has no number and no message. | Field | Type | Required | Description | | --- | --- | --- | --- | | `version` | `"2026-11-10"` | yes | A versão deste contrato. Ela sobe apenas com aviso e prazo, e um tipo novo de evento não a faz subir. | | `event_id` | `string` | yes | O identificador estável deste evento. Use-o para descartar repetições. · 64 to 64 characters | | `occurred_at` | `string` | yes | Quando o evento ocorreu, em UTC. | | `phone_number_id` | `null` | yes | Sempre null neste tipo: o template pertence à conta de negócio, e não a um número. | | `test` | `true` | no | Presente, e true, só no exemplo que POST /v1/webhooks/endpoints/{id}/test entrega quando você pede um eventType, e nos eventos simulados do modo de teste (chave com mode test e POST /v1/test-mode/inbound-messages): o corpo é de mentira, com identificadores que não existem. Ausente em todo evento de verdade. Se o seu código age sobre o evento, confira este campo antes. | | `number` | `null` | yes | Sempre null neste tipo: o evento não passa por um número. | | `event_type` | `"template.quality"` | yes | | | `template` | `object` | yes | A nota de qualidade de um template mudou. Nota baixa antecede a pausa do template pela Meta: é o momento de revisar o conteúdo ou o público. | | `template.id` | `string (uuid)` | yes | O identificador do template na Luna, o mesmo que POST /v1/templates e GET /v1/templates devolvem. | | `template.name` | `string` | yes | O nome do template. | | `template.language` | `string` | yes | O idioma do template, no código da Meta. | | `template.waba_id` | `string` | yes | A conta de WhatsApp Business na Meta (WABA) a que o template pertence, o mesmo id que GET /v1/business-accounts devolve em wabaId. | | `template.external_id` | `string \| null` | yes | O rótulo do cliente dono do template (o externalId que o seu sistema deu ao conectar o número). É o rótulo dos números da conta quando todos eles têm o mesmo. Nulo quando a conta tem números de clientes diferentes, quando algum número dela não tem rótulo e quando ela não tem número conectado: nesses casos, ligue o evento ao cliente por waba_id (GET /v1/business-accounts). | | `template.previous_quality_score` | `string \| null` | yes | A nota de qualidade de antes, no vocabulário da Meta: GREEN, YELLOW, RED, UNKNOWN. | | `template.new_quality_score` | `string \| null` | yes | A nota de qualidade de agora, no vocabulário da Meta. | ```json { "version": "2026-11-10", "event_id": "8624296410fe8b7631164b57d667847f22145595d3bac4ae644e32930aab9321", "event_type": "template.quality", "occurred_at": "2026-10-13T12:00:00.000Z", "phone_number_id": null, "number": null, "template": { "id": "3f6a1c52-9d4e-4b87-a1f0-5e2c7b9d8a14", "name": "pedido_confirmado", "language": "pt_BR", "waba_id": "102290129340398", "external_id": "cliente-8841", "previous_quality_score": "GREEN", "new_quality_score": "YELLOW" } } ``` ## Errors | HTTP status | Description | | --- | --- | | `400` | The body, query or identifier does not match the contract. Each item of campos gives the field and the reason, and the value you sent never comes back. Repeating the same request repeats the refusal. | | `401` | The key is missing, malformed, nonexistent, expired or revoked. The body is always the same, without saying which. | | `403` | The key lacks the scope the route requires. On a route that opens a number connection, also when the account cannot connect yet (connection_not_released). On the routes that write or send, also when the account is suspended: trial_expired (the free trial ended) or account_blocked (Helsen blocked the account). Suspension does not touch receiving: what arrives is still delivered to your webhook. A test key (mode test) only uses POST /v1/messages and POST /v1/test-mode/inbound-messages; on every other route it receives test_key_not_allowed. | | `404` | The resource does not exist, or is not yours. The two answers are identical, byte for byte. | | `409` | The request is well formed, but the resource state does not allow it. The error field says which case it is. | | `410` | The connect link expired or was already used. The error field says which of the two. | | `413` | The file is over the size ceiling, which is the same for every customer. | | `415` | The body came with a content-type the route does not read. Send application/json, or multipart/form-data on the file routes. | | `422` | The request is well formed and Luna passed it on, and Meta refused it. The meta field carries what happened, what to do and its original error. Repeating the same request repeats the refusal. | | `429` | Too many requests, or a full queue. Wait the time in the Retry-After header and repeat. For POST /v1/messages, repeat with the same Idempotency-Key. | | `503` | The platform cannot serve right now. Repeat after a few moments, with the same Idempotency-Key when there is one. | | Error code (error) | HTTP status | When it happens | | --- | --- | --- | | `invalid_request` | 400 | Field refused, with the reason | | `invalid_reset_token` | 400 | Invalid reset link | | `unauthorized` | 401 | Key refused | | `account_blocked` | 403 | Account blocked by Helsen | | `connection_not_released` | 403 | Account not yet released to connect | | `forbidden` | 403 | Insufficient scope | | `test_key_not_allowed` | 403 | Test key on a route outside test mode | | `trial_expired` | 403 | Free trial ended | | `not_found` | 404 | Does not exist, or is not yours | | `account_at_capacity` | 409 | The account that requested the link reached its maximum of numbers | | `already_requeued` | 409 | Item already requeued | | `idempotency_key_reused` | 409 | Idempotency-Key used with another body | | `link_not_open` | 409 | Link that is not open | | `media_not_ready` | 409 | Media not fetched yet | | `message_not_cancelable` | 409 | Message that already left the queue | | `no_webhook_endpoint` | 409 | No active webhook endpoint | | `not_available_in_coexistence` | 409 | Unavailable in coexistence | | `number_capacity_reached` | 409 | The account is already at its number capacity | | `number_disconnected` | 409 | Number disconnected from Luna | | `pin_not_applicable` | 409 | The number does not ask for a PIN | | `reconnect_not_applicable` | 409 | The authorization does not allow reconnection | | `register_budget_reserved` | 409 | Registration attempts reserved | | `template_content_unknown` | 409 | Luna does not know the template content | | `template_not_approved` | 409 | Template that is not approved yet | | `webhook_endpoint_limit` | 409 | Endpoint limit | | `window_closed` | 409 | Service window closed | | `link_expired` | 410 | Link expired | | `link_used` | 410 | Link already used | | `file_too_large` | 413 | File over the ceiling | | `unsupported_media_type` | 415 | Content type not read | | `meta_rejected` | 422 | Meta refused the operation | | `management_busy` | 429 | Account management busy | | `number_rate_limited` | 429 | Number pace | | `queue_full` | 429 | Send queue full | | `rate_limited` | 429 | Request limit | | `unavailable` | 503 | Unavailable |