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