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