# Setup links

> The URL a business owner opens to connect that customer’s WhatsApp number.

```http
POST /api/v1/customers/:customerId/setup-links
Authorization: Bearer $VITRAL_WHATSAPP_API_KEY
Content-Type: application/json

{
  "language": "es",
  "expiresInDays": 14,
  "brandingProfileId": "optional",
  "setupPageBaseUrl": "https://wa.vitral.dev",
  "successRedirectUrl": "https://example.com/done",
  "failureRedirectUrl": "https://example.com/fail",
  "allowedConnectionTypes": ["coexistence", "dedicated"]
}
```

Scope: `setup-links:manage`.

| Field | Rule |
| --- | --- |
| `expiresInDays` | Integer 1–30. Default 7. |
| `language` | Optional, max 10 characters. Omit it (or send `null`) to store `null`. The hosted page then uses `Accept-Language`, then English. `es` / `pt` / `en` (including regional tags such as `es-MX`) select that language. An unsupported value is ignored and the browser language is used. Existing rows that were saved as `en` stay `en` and still force English. |
| `brandingProfileId` | Optional branding profile on this tenant. A profile id from another tenant is `400`. |
| `setupPageBaseUrl` | Optional origin. The link is `{origin}/setup/{token}`. If omitted, the server uses `SETUP_PAGE_BASE_URL` when that env is set. Otherwise it uses the request origin (`X-Forwarded-Host` / `Host`, and `X-Forwarded-Proto`) and forces `https` unless the host is localhost. In production, no override, no env, and no request host is `500` `SETUP_PAGE_BASE_URL_MISSING`. |
| `successRedirectUrl` / `failureRedirectUrl` | Optional. Each URL must match the allowlist below or the call is `400` `VALIDATION_ERROR`. Send `null` on PATCH to clear one. |
| `allowedConnectionTypes` | `coexistence`, `dedicated`, or both. Default is both. One value skips the choice screen and is enforced on finalize. |

`201` `data` is `{ id, token, url }`. `token` is shown once. Creating a link revokes that customer’s other `ACTIVE` links only when they have not been opened. A link is opened when the hosted page creates a session or when headless config is fetched (`openedAt`). A setup session also counts, including sessions created before `openedAt` existed. `IN_PROGRESS` links are never revoked. An integrator that creates a link per attempt does not cut off a clinic that already has the page or the headless config open.

List and get return the stored row, including `tokenHash`, plus `successRedirectUrl`, `failureRedirectUrl`, `allowedConnectionTypes`, `connectionType` (`null` until a path is recorded), and `openedAt` (`null` until the link is opened). `language` is `null` when the link is on automatic language. The hash is not the raw token and does not rebuild the URL.

`PATCH /api/v1/customers/:customerId/setup-links/:id` updates an `ACTIVE` link: `expiresAt` or `expiresInDays` (not both; at most 30 days from now), `language`, the redirect URLs, `brandingProfileId`, and `allowedConnectionTypes`. `{ "status": "REVOKED" }` revokes it. Any other `status`, including `USED`, is `400`. A link that is not `ACTIVE` is `409` `INVALID_STATE_TRANSITION`.

`POST /api/v1/customers/:customerId/setup-links/:id/regenerate` returns a new `{ id, token, url }` with the same language, branding, redirects, and connection types. It revokes unopened `ACTIVE` links for that customer, including an unopened `ACTIVE` source. It revokes an `EXPIRED` source. It does not revoke `IN_PROGRESS` (including when that link is the source), `USED`, or an `ACTIVE` link that has already been opened. The new expiry is the original length, from 1 to 30 days.

`DELETE /api/v1/customers/:customerId/setup-links/:id` returns `204` and sets `status` to `REVOKED`. The customer id in the path must own the link.

These writes are tenant-scoped, require `setup-links:manage`, and are written to the API log with an `audit` field (`setup_link.updated`, `setup_link.revoked`, `setup_link.regenerated`, `setup_link.superseded`).

Link `status`: `ACTIVE`, `IN_PROGRESS`, `USED`, `EXPIRED`, `REVOKED`.

WhatsApp status: `PENDING`, `PROCESSING`, `COMPLETED`, `FAILED`.

The first request that opens an `ACTIVE` or `IN_PROGRESS` link after `expiresAt` (hosted page or headless config, not the status poll) sets `status` to `EXPIRED` and sends `setup_link.expired` once. A `USED` or `REVOKED` link is not rewritten as `EXPIRED`.

`GET /api/v1/customers/:customerId/setup-links/:id` may add `repair` next to `data`:

```json
{ "repair": { "action": "pending" } }
```

`pending` means the link is new or unused. The owner has not finished Embedded Signup. Wait. Do not send another link.

```json
{ "repair": { "action": "needs_reconnect", "reason": "..." } }
```

`needs_reconnect` means a finished attempt could not attach the phone. Send a new link. `repair` is omitted when the server is not reporting either of those.

## Redirect allowlist

A success or failure URL is accepted only when its protocol, host, port, and path match an allowlist entry. Trailing slashes do not matter. `javascript:` URLs, `data:` URLs, and URLs with a username or password are rejected. Branding `allowedRedirectUrls` uses the same rule. The legacy complete-page redirect ignores an allowlist entry that is not http(s).

- When `brandingProfileId` is set, the list is that profile’s `allowedRedirectUrls`.
- When the link has no branding profile, the list is the union of `allowedRedirectUrls` on every branding profile of the tenant.

There is no separate tenant redirect-settings route. Create a branding profile and put the URLs there. An empty list plus a redirect URL is `400`.

On success the hosted complete page redirects to `successRedirectUrl` and appends `setup_link_id`, `status=completed`, `phone_number_id`, `waba_id`, `display_phone_number`, and `connection_type`.

On failure it redirects to `failureRedirectUrl` and appends `setup_link_id` and `error_code`. Codes: `link_expired`, `already_used`, `link_revoked`, `link_not_found`, `session_expired`, `facebook_auth_failed`, `token_exchange_failed`, `phone_verification_failed`, `phone_already_bound`, `waba_limit_reached`, `phone_number_limit`, `internal_error`.

With no redirect configured, success still redirects to the first branding `allowedRedirectUrls` entry when `whatsappSetupStatus` is `COMPLETED`, without those query params. Otherwise the page stays on the hosted HTML.

## Public status

No API key. Works after the link is `USED`. This route does not mark a link `EXPIRED`.

```http
GET /api/v1/setup/public/:token/status
```

```json
{
  "data": {
    "status": "USED",
    "whatsappSetupStatus": "COMPLETED",
    "whatsappSetupError": null,
    "phoneNumberId": "ck_phone",
    "connectionType": "coexistence"
  }
}
```

`connectionType` is `null` when the client did not send one and both types were allowed. An unknown token is `404`. An expired link still returns `200` here, with its stored status. `repair` is inside `data` (not beside it). `pending` means wait. `needs_reconnect` means send a new link.

## What the owner does

1. Opens `url`.
2. The hosted page offers the connection types on the link:
   - **Connect WhatsApp Business App** (`coexistence`). Embedded Signup v5 with its default: the WhatsApp Business app is offered.
   - **Set up a new WhatsApp number** (`dedicated`). Embedded Signup v5 with `whatsapp_business_app_onboarding` turned off.
   - In v5 the owner who clicked the first button can still pick a new number. Finalize then sends `dedicated` (see Headless).
   - One allowed type shows only that button. Finalize rejects the other type with `400`.
3. Completes Meta Embedded Signup. Visible strings and the Facebook SDK follow the link language, then `Accept-Language`, then English. SDK locales are `es_LA`, `pt_BR`, and `en_US`. Spanish is Mexican-neutral.
4. Adds a payment method in Meta if Meta asks. This API does not collect a card.

The server exchanges the code, subscribes the app to that WABA, registers the phone, sets `PhoneNumber.customerId`, stores `connectionType` on the link and the phone when it knows the path, and marks the link `USED`. The registration PIN defaults to `000000` when the client does not send one.

`GET /setup/:token` sets a session cookie and redirects to `/setup/start` when the link can still be used. Unknown token: HTML `404`. Expired, used, or revoked: HTML `410`, branded with the profile logo, accent color, display name, and support email when the token exists (“Pide un nuevo enlace a …” in Spanish). `USED` + `COMPLETED` is a success-style “already connected” page and is still HTTP `410`. If `failureRedirectUrl` is set, expired, revoked, and used-but-not-completed responses are `302` to that URL instead of the `410` page. The session cookie lasts 15 minutes.

`GET /setup/start` and `GET /setup/complete` without a session return JSON `401` `SESSION_MISSING` unless the request `Accept` header prefers `text/html`. Browsers get a localized HTML page (`401`) that says to open the link again. `SESSION_INVALID` and `SESSION_EXPIRED` follow the same split. An expired session with `failureRedirectUrl` redirects with `error_code=session_expired`. `403` `CSRF_INVALID` is a hosted `POST /setup/finalize` whose CSRF token does not match the session.

`setup_link.completed` and `setup_link.failed` are sent once per link. Polling still works.

## Headless

```http
GET /api/v1/setup/public/:token
```

`data` includes `appId`, `configId`, `graphVersion`, `displayName`, `accentColor`, `language` (`null` when automatic), `locale` (resolved from the link, then `Accept-Language`), `allowedConnectionTypes`, `connectionType`, and the same token again as `token` and `setupToken`. Unknown token: `404`. Expired, used, or revoked: `410` `SETUP_LINK_EXPIRED` or `SETUP_LINK_INVALID`.

Launch Embedded Signup v5 with `config_id` and `extras: { setup: {}, version: "v5" }`. Meta retired v2/v3 on 2026-10-15 and serves a call without `version` as v4; `sessionInfoVersion` and `featureType` are not v5 inputs. v5 offers the WhatsApp Business app (coexistence) by default. For a new number only, add `features: [{ name: "whatsapp_business_app_onboarding", enabled: false }]`.

Send `sessionInfo` from the `WA_EMBEDDED_SIGNUP` message (`waba_id`, `phone_number_id`, `business_id`; `phone_number_id` is missing on coexistence and `FINISH_ONLY_WABA`, and the server then picks the WABA's number). Send the `connectionType` of the finish event, not of the button: `FINISH_WHATSAPP_BUSINESS_APP_ONBOARDING` is `coexistence` (the phone is not registered), `FINISH` and `FINISH_ONLY_WABA` are `dedicated`, and `FINISH_GRANT_ONLY_API_ACCESS` is `null` (registration follows the number's Graph status and `is_on_biz_app`). Send `connectionType` on finalize (`coexistence` or `dedicated`). If the link allows only one type, omitting `connectionType` uses that type. If both are allowed and you omit it, the call still succeeds and `connectionType` stays `null` (older clients). A type that is not allowed is `400` `VALIDATION_ERROR`.

```http
POST /api/v1/setup/public/:token/finalize
Content-Type: application/json

{
  "code": "<auth code>",
  "connectionType": "coexistence",
  "sessionInfo": { "waba_id": "...", "phone_number_id": "...", "business_id": "..." }
}
```

The body is not wrapped in `data`. Success looks like `{ "status": "processing", "setupLinkId": "...", "binding": { "phone": { "id": "..." } } }`. Failure looks like `{ "status": "failed", "error": "...", "errorCode": "token_exchange_failed" }`. `errorCode` and, when a failure URL is configured, `redirectUrl` are added. Missing `code` is `400` `MISSING_CODE`. `sessionInfo` may be omitted. If several WABAs are granted, pass `waba_id`.

`POST /api/v1/embedded-signup/token-exchange` (scope `phone_numbers:write`) does not set `customerId`. Prefer the setup link.

A `waPhoneNumberId` already stored on another tenant fails with `400` `VALIDATION_ERROR` and message `This WhatsApp phone number is already bound to another tenant`. The number is not moved. That failure is `errorCode` `phone_already_bound` on the setup response and on `setup_link.failed`.

## Branding

Same scope, `setup-links:manage`.

`POST /api/v1/branding` body:

| Field | Rule |
| --- | --- |
| `displayName` | Required. 1–255 characters. Shown on the hosted page. |
| `logoUrl` | Optional URL. |
| `accentColor` | `#RRGGBB`. Default `#22c55e` when omitted. |
| `supportEmail` | Optional email. Shown on hosted error pages. |
| `allowedRedirectUrls` | Up to 10 URLs. Allowlist for this profile. The hosted complete page still uses the first URL when the link has no `successRedirectUrl`. |

If the setup link has no branding profile, the page uses the tenant name. Error pages for an unknown token are unbranded.
