> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pilotstatus.com.br/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Integrating Pilot Status end to end? Follow https://docs.pilotstatus.com.br/guides/integrate-with-ai.md (pt-BR: https://docs.pilotstatus.com.br/pt-BR/guides/integrate-with-ai.md). No step requires contacting support: every credential is shown in the dashboard or in an API response, and a lost one is regenerated, not recovered.
> Webhook signing secret: shown ONCE in the Signing secret window right after creating the webhook on /webhooks, and in the `secret` field of the POST /v1/webhooks response (MCP: webhooks_create). Lost it: Edit Webhook → Generate a new secret, POST /v1/webhooks/{id}/rotate-secret, or webhooks_rotate_secret (the old one stops working at once). Verify `x-pilot-status-signature` = hex HMAC-SHA256 of the raw request body keyed with that secret.
> Meta verify token (number connected with the user's own Meta app credentials): Meta Number Created! window after connecting, then the number's card on Numbers (workspace Owner), or webhook.verifyToken in the POST /v1/numbers/meta response. It is not the webhook signing secret.
> REST auth: `x-api-key: ps_...` header, never Authorization: Bearer. MCP: https://mcp.pilotstatus.com.br/mcp (148 tools, OAuth 2.1 or x-api-key); Code Mode: https://mcp.pilotstatus.com.br/code. Destructive MCP tools return a preview and a confirm_token: show the preview and call again only after the user's explicit yes. Over OAuth, revealing or creating ps_ API keys is workspace Owner only.

# Incrustar la bandeja de Chat

> Incrusta la bandeja de WhatsApp white-label en tu propio SaaS mediante iframe y el SDK @pilot-status/embed, con tokens de sesión de corta duración y con alcance limitado.

Incrusta la **bandeja de WhatsApp (Chat)** de Pilot Status en tu propio SaaS, en white-label, mediante un iframe alojado más el SDK `@pilot-status/embed`.

## Requisitos previos compartidos (Chat + Connect)

1. **API key del tenant** (`ps_`, con alcance de tenant): se genera en **Workspace keys** (`/workspace-api-keys`). **Nunca** sale de tu backend. (Una clave con alcance de número solo puede incrustar su propio número.)
2. **SDK**: `<script src="https://pilotstatus.com.br/embed.js">` o `npm i @pilot-status/embed`; llama a `PilotStatus.init()`.
3. **`allowedOrigins`**: al emitir el token de Chat, lista los orígenes exactos (`scheme://host[:port]`, de 1 a 20) autorizados a incrustar.
4. **Token por superficie**: Chat usa `POST /v1/embed/sessions` (`surface: "chat"`, un JWT de corta duración guardado en memoria). Connect usa `POST /v1/numbers/remote-pairing` (un token de emparejamiento en la URL; consulta [Incrustar la página Connect](https://docs.pilotstatus.com.br/es/integrations/embed-connect.md)).
5. **Renovación**: el TTL del token de Chat es de 15 min con una ventana de renovación deslizante; cuando expira por completo, el SDK llama a `onSessionExpired`.

## Flujo de Chat

**1. Configuración única**

Tu backend lista los números con `GET /v1/numbers` (`x-api-key`) y guarda el mapa `cliente → [whatsappNumberIds]`.

**2. Emite un token en cada carga de página**

Tu frontend le pide un token a tu backend; el backend llama:

```bash theme={null}
curl -X POST "https://pilotstatus.com.br/v1/embed/sessions" \
  -H "x-api-key: ps_your_tenant_key" \
  -H "Content-Type: application/json" \
  -d '{
    "surface": "chat",
    "whatsappNumberIds": ["wn_abc123"],
    "allowedOrigins": ["https://app.yoursaas.com"],
    "ttlSeconds": 900
  }'
```

Respuesta `201`: `{ token, surface, whatsappNumberIds, allowedOrigins, expiresAt }`. El backend reenvía **solo el JWT** al frontend.

**3. Monta la bandeja**

```html theme={null}
<script src="https://pilotstatus.com.br/embed.js"></script>
<div id="inbox"></div>
<script>
  PilotStatus.init();
  const { token } = await fetch("/api/my-saas/embed-token").then(r => r.json());
  const chat = PilotStatus.chat.mount("#inbox", {
    token, locale: "en", theme: "light",
    onUnreadCount: (n) => {},
    onConversationOpened: (id) => {},
    onSessionExpired: async () => {
      const { token: t } = await fetch("/api/my-saas/embed-token").then(r => r.json());
      chat.destroy();
      PilotStatus.chat.mount("#inbox", { token: t, locale: "en" });
    },
  });
  // chat.setTheme("dark"); chat.setLocale("pt"); chat.destroy();
</script>
```

## Protocolo postMessage (padre ↔ iframe)

Sobre: `{ source: "pilot-status-embed", v: 1, type, payload }`. Los mensajes sin ese `source` se ignoran; el origen se valida en **ambos** lados.

| Paso | Quién | Mensaje |
| - | - | - |
| A | SDK (padre) | crea `<iframe src="chat.pilotstatus.com.br/?parentOrigin=<origin>">` (sandbox `allow-scripts allow-same-origin allow-forms allow-popups`) |
| B | iframe → padre | `ready` (el SDK valida `origin === chat.pilotstatus.com.br`) |
| C | SDK → iframe | `init{ token, locale, theme }` (el iframe valida `origin === parentOrigin`) |
| D | iframe | guarda el token **solo en memoria**, nunca en la URL ni en localStorage |
| E | iframe → padre | `resize{height}`, `chat:unread-count{count}`, `chat:conversation-opened{conversationId}`, `session-expired` |
| — | SDK → iframe | `set-theme{theme}`, `set-locale{locale}` en tiempo de ejecución |

## Modelo de seguridad

* `x-api-key` vive **solo** en tu backend; el navegador solo maneja el JWT de corta duración.
* El JWT está **estrictamente limitado** a sus `whatsappNumberIds`: las rutas del chat vuelven a verificarlo en cada solicitud (defensa en profundidad).
* Token solo en memoria, TTL de \~15 min con renovación deslizante; `allowedOrigins` fija quién puede incrustar; el origen de postMessage se valida en ambos lados.

## Relacionado

* [Incrustar la página Connect](https://docs.pilotstatus.com.br/es/integrations/embed-connect.md)
* [Panel de Live Chat](https://docs.pilotstatus.com.br/es/dashboard/live-chat.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.