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

> ## Agent Instructions
> Bridge exposes three integration surfaces: the REST Integrations API for pushing data into Bridge, webhooks for receiving events from Bridge, and the public Custom Connections endpoint that a tenant's landing page posts to.
> The Integrations API host is https://api-connect-us.bridge.new and every request to it must be authenticated with the x-api-key header. Bridge does not use bearer tokens or OAuth.
> The Custom Connections endpoint is different and the Integrations API rules do not apply to it: it has its own host, it takes no x-api-key and no authentication header of any kind, and it is called from a visitor's browser. It is identified by a workspace id and a capture key together with a reCAPTCHA token. Never tell a reader to authenticate it with an API key, and never tell them to keep its capture key out of frontend code - it is designed to live in the page.
> REST error catalog keys use BRIDGE_<DOMAIN>_<NNNN>, for example BRIDGE_CONVERSATION_0001. Some reviewed legacy handlers return a recognized code plus a symbolic suffix separated by |; preserve the complete received value and use the compatible catalog lookup on /error-codes. Custom Connections uses separate BRIDGE.CAMPAIGN_LEADS.<NAME> identifiers on its own error reference. Never invent an error code or confuse the two integration surfaces.
> This documentation covers the Integrations API, webhooks and Custom Connections only. It does not describe the Bridge web application or its internal APIs.
> Before generating an API request, read the relevant OpenAPI specification or the individual endpoint Markdown page. llms-full.txt collects guides and endpoint descriptions; it does not embed every request and response schema. The REST and Custom Connections contracts are separate.
> Preserve the published host, method, path, operationId, authentication, headers, parameter and field names, types, formats, required and nullable fields, enums, defaults, limits, and response codes. Do not invent identifiers, fields, retry rules, or delivery guarantees. When published sources conflict, identify the conflicting passages and ask Bridge support to confirm the current behavior before relying on it.
> Custom Connections is the current name of the landing-page feature previously documented as Lead Capture. The existing /lead-capture documentation URLs, captureKey field, campaign-leads endpoint, and BRIDGE.CAMPAIGN_LEADS error identifiers are unchanged. This is a naming change, not a change to authentication or the API contract.
> For a complete workflow, start with the task guides: /guides/first-conversation, /guides/send-attachments, /guides/send-template, /guides/agent-outbound, /guides/pagination, /guides/identifiers and /guides/responses. Read the endpoint contract as well as the recipe. Outbound requires an existing Contact, but does not require creating a separate Conversation first.
> forceSend=true permits reuse of an existing active conversation; it does not create a fresh one by ignoring it and it is not idempotency. Recovery of a released recoverable conversation can occur even with false. The LeadScout and Agents outbound routes have different line-selection and controller checks; use /guides/agent-outbound.
> For webhook HMAC, follow /webhooks/verifying-signatures exactly: the Python JSON serialization with sorted keys is signed; X-Bridge-Timestamp is not included in that signature. Do not claim a signed timestamp, raw-body signing, exactly-once delivery or a global event order. Use /webhooks/receive-events for durable acceptance and duplicates.
> A 201 message response, 202 handoff or 202 Custom Connections response is not a provider delivery receipt. Do not invent a polling endpoint from messageId, trackingId or requestId. REST validation parsing must tolerate the compatibility difference explained in /error-codes.
> The documentation is available in English (existing root URLs), Spanish (/es/) and Brazilian Portuguese (/pt-br/). Prefer the reader's language when a localized page exists, but preserve the API's exact field names, enums, routes, authentication and examples. Translations describe the same API; they do not introduce regional API hosts or behaviors.
> For coding-assistant setup, use /connect-your-agent, /es/connect-your-agent or /pt-br/connect-your-agent. The Bridge documentation MCP server reads published documentation and has a separate optional feedback tool. Connecting it does not connect the coding assistant to a customer workspace or authorize live business requests.
> For direct HTTP access without MCP, start at https://docs.bridge.new/llms.txt. It lists every published page in English, Spanish and Brazilian Portuguese. Choose /llms-en.json, /llms-es.json or /llms-pt-br.json for a language-specific index, and /llms-full-en.json, /llms-full-es.json or /llms-full-pt-br.json for collected content. /llms-full.txt contains the combined collection. Fetch the original OpenAPI specification for exact schemas.
> For HTTP page reads, follow the .md URLs from the index or request Accept: text/markdown at the canonical page URL. The MCP virtual filesystem uses .mdx page paths instead; .mdx is not the public HTTP export extension. With Search MCP, set language to en, es or pt-BR explicitly; its default is en.
> For integration capabilities and source-selection rules, read https://docs.bridge.new/skill.md. Documentation access does not authorize business API actions; use the actual user request, workspace, credentials and target identifiers for any live integration.

# Crea un contacto y envía un mensaje

> Sigue un flujo completo desde el servidor: contacto, conversación y mensaje, conservando los identificadores devueltos.

Esta guía crea un contacto, inicia una conversación con un usuario interno de Bridge y crea un mensaje. Ejecútala en tu servidor.

> [!WARNING]
>
> Usa un contacto de prueba al que tengas autorización para escribir. Crear una conversación puede ejecutar las plantillas de inicio del espacio de trabajo antes de la solicitud independiente que crea el mensaje. Revisa primero esa configuración: establecer en false el indicador de envío externo del mensaje posterior no desactiva las plantillas de inicio de la conversación.

## Antes de comenzar

* Obtén una clave de API para usar desde el servidor en [Autenticación](https://docs.bridge.new/es/credentials.md).
* Consigue el ID del espacio de trabajo, el `providerChannelId` de una línea activa de WhatsApp y el correo de un usuario interno de Bridge. Consulta [Identificadores y conceptos](https://docs.bridge.new/es/guides/identifiers.md).
* Usa un número nuevo de prueba en formato internacional. Si el contacto ya existe, usa la [consulta de contactos por identificador](https://docs.bridge.new/es/api-reference/contacts-api/obtener-contacto-por-un-identificador.md) en lugar de crearlo otra vez.
* Revisa los atributos personalizados obligatorios y la secuencia de plantillas de inicio del espacio de trabajo. Este ejemplo mínimo no proporciona atributos personalizados ni reemplaza las plantillas.
* Elige `enableExternalBroadcast` explícitamente: `true` solicita el envío externo cuando lo permiten las reglas de la conversación y del destinatario; `false` crea el mensaje, pero omite ese envío externo. Ningún valor confirma la entrega por parte del proveedor. Este indicador no anula reglas de visibilidad ni permisos.

## La secuencia

| Paso | Solicitud | Valor que debes conservar |
| - | - | - |
| Comprueba el acceso | `GET /bridge/api/health` | Respuesta HTTP exitosa |
| Crea el contacto | `POST /bridge/api/v1/workspaces/{workspaceId}/contacts` | `id` del contacto |
| Inicia la conversación | `POST /bridge/api/v1/workspaces/{workspaceId}/conversations` | `id` de la conversación |
| Crea el mensaje | `POST /bridge/api/v1/workspaces/{workspaceId}/messages` | `messageId` |

El `id` del contacto se convierte en el `identifier` del participante externo, con `identifierType: "ID"`. El `id` de la conversación se convierte en el `conversationId` del mensaje.

## Ejecuta el ejemplo

Usa Node.js con `fetch` integrado. Guarda el ejemplo como `first-conversation.mjs`. Proporciona estas variables de entorno mediante la configuración y el sistema de secretos de tu servidor:

| Variable | Valor |
| - | - |
| `BRIDGE_API_KEY` | Tu clave de API secreta |
| `BRIDGE_WORKSPACE_ID` | ID del espacio de trabajo correcto |
| `BRIDGE_PROVIDER_CHANNEL_ID` | ID de la línea de WhatsApp autorizada, no su teléfono |
| `BRIDGE_USER_EMAIL` | Usuario interno de Bridge del mismo espacio de trabajo |
| `TEST_CONTACT_PHONE` | Teléfono de un contacto nuevo de prueba al que tienes autorización para escribir |
| `ENABLE_EXTERNAL_BROADCAST` | Exactamente `true` o `false`; no se asume un valor predeterminado |

Los nombres y el mensaje que aparecen abajo son ejemplos. Reemplázalos con el contenido previsto para tu prueba antes de ejecutarla.

```javascript theme={null}
const BASE = "https://api-connect-us.bridge.new";

function required(name) {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name} before running this example.`);
  return value;
}

const apiKey = required("BRIDGE_API_KEY");
const workspaceId = required("BRIDGE_WORKSPACE_ID");
const providerChannelId = required("BRIDGE_PROVIDER_CHANNEL_ID");
const internalEmail = required("BRIDGE_USER_EMAIL");
const cellphone = required("TEST_CONTACT_PHONE");
const broadcast = required("ENABLE_EXTERNAL_BROADCAST");
if (!["true", "false"].includes(broadcast)) {
  throw new Error("ENABLE_EXTERNAL_BROADCAST must be true or false.");
}
const workspacePath = `/bridge/api/v1/workspaces/${encodeURIComponent(workspaceId)}`;

async function request(method, path, body, expectedStatus) {
  const response = await fetch(`${BASE}${path}`, {
    method,
    headers: {
      "x-api-key": apiKey,
      ...(body === undefined ? {} : { "Content-Type": "application/json" }),
    },
    ...(body === undefined ? {} : { body: JSON.stringify(body) }),
  });
  const result = await response.json().catch(() => null);
  if (response.status !== expectedStatus) {
    const code = result?.code ? ` (${result.code})` : "";
    throw new Error(`${method} ${path}: HTTP ${response.status}${code}`);
  }
  return result;
}

await request("GET", "/bridge/api/health", undefined, 200);

const contact = await request("POST", `${workspacePath}/contacts`, {
  firstName: "Alex",
  lastName: "Example",
  languageCode: "EN",
  cellphone,
}, 201);
if (!contact?.id || contact.workspaceId !== workspaceId) {
  throw new Error("The Contact response does not identify the intended workspace.");
}

const conversation = await request("POST", `${workspacePath}/conversations`, {
  participants: {
    externals: [{
      identifier: contact.id,
      identifierType: "ID",
      messageProviderType: "WHATSAPP",
      providerChannelId,
    }],
    internals: [{ identifier: internalEmail, identifierType: "EMAIL" }],
  },
  name: "Integration test",
  status: "ACTIVE",
}, 201);
if (!conversation?.id || conversation.workspaceId !== workspaceId) {
  throw new Error("The Conversation response does not identify the intended workspace.");
}

const message = await request("POST", `${workspacePath}/messages`, {
  conversationId: conversation.id,
  messageBody: "Hello from our authorized Bridge integration test.",
  enableExternalBroadcast: broadcast === "true",
}, 201);
if (!message?.messageId) throw new Error("The Message response has no messageId.");

console.log({
  contactId: contact.id,
  conversationId: conversation.id,
  messageId: message.messageId,
});
```

```bash theme={null}
node first-conversation.mjs
```

## Entiende el resultado

* Una respuesta `201` al crear el contacto proporciona su identidad y espacio de trabajo. Lee `type` para conocer su clasificación real: `NORMAL` o `PARTIAL`.
* Una respuesta `201` de conversación proporciona el ID que debes usar en el siguiente paso. Cuando no hay líneas libres, Bridge puede recuperar una conversación liberada que tenga exactamente los participantes solicitados. Se conservan su ID e historial; en ese caso de recuperación no se aplican el `name` ni el `status` solicitados.
* Una respuesta `201` de mensaje proporciona `messageId`. Por sí sola, no demuestra que WhatsApp haya entregado el mensaje al contacto.

Esta guía asigna explícitamente un usuario interno de Bridge. Para asignar mediante un equipo, usa la opción documentada `teamId` en lugar de `participants.internals`: son mutuamente excluyentes.

## Si falla un paso

El ejemplo se detiene en la solicitud que falla y nunca reintenta automáticamente una escritura. Un fallo de red puede dejar el resultado incierto. Comprueba el recurso correspondiente antes de repetir una operación de creación o envío.

| Situación | Qué hacer |
| - | - |
| El contacto ya existe | Consúltalo por identificador y usa el `id` devuelto; no sigas intentando crear el mismo contacto. |
| Error de marca o línea | Confirma con el administrador cuál es la línea o marca autorizada; el teléfono de una línea no es su ID. |
| Plantilla `0604`–`0608` | Sigue [Parámetros de plantillas de WhatsApp](https://docs.bridge.new/es/templates-and-parameters.md), incluidos los errores de configuración del espacio de trabajo. |
| El mensaje se rechaza porque la conversación está liberada | Revisa el estado de la conversación y la referencia de errores de la operación antes de actuar. |
| `429` | Sigue [Límites de solicitudes](https://docs.bridge.new/es/rate-limits.md), incluido `Retry-After`. |

Consulta [Respuestas y errores](https://docs.bridge.new/es/guides/responses.md) para conocer los formatos de respuesta y las decisiones de recuperación.

## Próximos pasos

* [Carga y envía un adjunto](https://docs.bridge.new/es/guides/send-attachments.md).
* [Elige y completa una plantilla de WhatsApp](https://docs.bridge.new/es/guides/send-template.md).
* Consulta los contratos completos de solicitud y respuesta de [crear un contacto](https://docs.bridge.new/es/api-reference/contacts-api/crear-contacto.md), [crear una conversación](https://docs.bridge.new/es/api-reference/conversations-api/crear-conversaci%C3%B3n-con-identificaci%C3%B3n-flexible-de-usuarios) y [crear un mensaje](https://docs.bridge.new/es/api-reference/messages-api/crear-mensaje.md).


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