# 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=<t>,v1=<hmac>`), 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=<status>&numberId=<numberId>&externalId=<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<void>;

const customers = new Map<string, CustomerHandler>([
  ['cliente-1', (event) => console.log('cliente-1', event.event_type)],
  ['cliente-2', (event) => console.log('cliente-2', event.event_type)],
]);

const seen = new Set<string>(); // 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.
