LunaDocs

Loading search...

PortuguêsSign in to the console
On this page

Coming from Twilio

Use with AI

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 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.
  • 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.
  • 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#

TwilioLuna
Create a message in the messages APIPOST /v1/messages
Origin in the whatsapp:+5531... formatfrom: the number’s UUID (GET /v1/numbers) or the metaPhoneNumberId.
Destination in the whatsapp:+5511900000001 formatto: "5511900000001": digits only, no + and no prefix.
Text bodytext.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 requestPOST /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.
Status callback of each messageOne endpoint (POST /v1/webhooks/endpoints) receives the message.status event for every message.
States queued, sent, delivered, read, failed, undeliveredqueued (only in the 202), accepted, sent, delivered, read, played and failed. There is no undelivered: a failure is failed. See The message states.
The message’s error codeerror_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 payloadmessage.received event: message.text, wa_id, message.button.payload and message.interactive.
Send idempotency keyIdempotency-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.
Account SID and token, or an API keyAuthorization: Bearer hlsn_..., with scopes (messages:write, messages:read, templates:read...). See Account and keys.
Subaccount per customerA key with externalId, a connect link and an endpoint with externalIds.
List messages by recipient, date and page sizeGET /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 sentcontent of GET /v1/messages: in template, the name, the language and the variables.
Sandbox with joinA key with mode: "test": the send does not go to Meta and your webhook receives the simulated states. See Test mode.
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"
          }
        ]
      }
    ]
  }
}'
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());
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.
  • 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.

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 TwilioOn Luna
21211, invalid destination400 with campos: [{campo: "to"}], at once.
63016, outside the reply window409 window_closed, at once and before going to Meta. Send a template.
Invalid template content or variables409 template_not_approved or 400 with campos, at once, when Luna knows the template.
Number without WhatsApp, payment, account restriction and the other Meta codesmessage.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.

What does not exist here#

On TwilioOn Luna
Code verification over WhatsApp, SMS, voice and e-mailLuna 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.
Automatic fallback to SMSLuna 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 sendingThe official API does not answer that. Treat code 131026 as “number without WhatsApp” and stop retrying that number.
Sender pool and messaging serviceEach Meta number is independent, and from is one number. Choosing the sender is your code’s decision.
Batch sending, scheduling and send validityOne 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 messageThere is no route to delete a message. To request data deletion, see the privacy policy.
List of who asked to stopMeta 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 timersLuna delivers the messaging; the logic is yours. For no-code flows, there is the n8n node in SDK and n8n.