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

# Elige y completa una plantilla de WhatsApp

> Consulta una plantilla por ID o nombre, proporciona sus claves de variables independientes del proveedor y usa el ID devuelto en una solicitud de conversación.

Usa esta guía cuando quieras abrir una conversación con una plantilla específica de WhatsApp. La [referencia detallada de plantillas](https://docs.bridge.new/es/templates-and-parameters.md) explica las reglas de validación y todos los errores de plantilla documentados.

## Antes de comenzar

* Debes conocer el **ID o nombre** de la plantilla. `GET .../templates/{templateId}` acepta ambos.
* Confirma que la plantilla esté aprobada para la cuenta de WhatsApp Business asociada a la línea que usarás.
* Debes tener el ID de un contacto de prueba existente, el `providerChannelId` de la línea autorizada de WhatsApp y el correo de un usuario interno de Bridge. Consulta [Identificadores y conceptos](https://docs.bridge.new/es/guides/identifiers.md).
* Revisa la secuencia de plantillas de inicio del espacio de trabajo: según su configuración, tu reemplazo puede sustituir toda la secuencia o solo la primera plantilla.

> [!WARNING]
>
> La solicitud final inicia una conversación y puede enviar plantillas de inicio. Usa un contacto de prueba autorizado y el contenido previsto.

## 1. Consulta las variables

```http theme={null}
GET /bridge/api/v1/workspaces/{workspaceId}/templates/{templateId}
x-api-key: YOUR_API_KEY
```

Codifica para URL el ID o nombre proporcionado. Lee `id`, `name`, `variables` y `driftWarning` en la respuesta.

| Variable | Qué hacer |
| - | - |
| `callerMustSupply: true` | Proporciona una cadena que no esté en blanco bajo la `key` de esa variable. |
| `callerMustSupply: false`, no personalizada | Omítela para conservar el valor que Bridge obtiene para cada contacto. Un valor enviado reemplaza ese valor para todos los contactos. |
| `isCustom: true` | Proporciona tu valor, omítelo o envíalo en blanco para usar su `default`. |

Usa la `key` independiente del proveedor, nunca el `label` visible, una posición de Meta ni un nombre de variable inventado. `driftWarning` es informativo y por sí solo no bloquea el envío.

## 2. Prepara los valores

Crea en tu servidor un archivo JSON que contenga únicamente claves devueltas por la consulta. Si la plantilla realmente declara `order_number` y `delivery_date`, podría contener lo siguiente:

```json theme={null}
{
  "order_number": "A-10492",
  "delivery_date": "October 3"
}
```

Esos dos nombres son ejemplos, no campos universales de Bridge. Consulta tu propia plantilla antes de usarlos. Respeta las [reglas de valores de WhatsApp](https://docs.bridge.new/es/templates-and-parameters.md#whatsapp-value-rules); omite los valores no personalizados que quieras que Bridge complete, en lugar de enviar cadenas en blanco.

## 3. Consulta, comprueba y crea la conversación

Usa Node.js con `fetch` integrado. Guarda el ejemplo como `send-template.mjs` y configura `BRIDGE_API_KEY`, `BRIDGE_WORKSPACE_ID`, `BRIDGE_TEMPLATE_ID_OR_NAME`, `TEMPLATE_VALUES_PATH`, `BRIDGE_CONTACT_ID`, `BRIDGE_PROVIDER_CHANNEL_ID` y `BRIDGE_USER_EMAIL`.

```javascript theme={null}
import { readFile } from "node:fs/promises";

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 templateRef = required("BRIDGE_TEMPLATE_ID_OR_NAME");
const contactId = required("BRIDGE_CONTACT_ID");
const providerChannelId = required("BRIDGE_PROVIDER_CHANNEL_ID");
const internalEmail = required("BRIDGE_USER_EMAIL");
const parameters = JSON.parse(await readFile(required("TEMPLATE_VALUES_PATH"), "utf8"));
if (parameters === null || Array.isArray(parameters) || typeof parameters !== "object") {
  throw new Error("The template values file must contain a JSON object.");
}
if (Object.entries(parameters).some(([key, value]) =>
  Array.from(key).length > 128 || typeof value !== "string" || Array.from(value).length > 1024
)) {
  throw new Error("Parameter keys and values must respect the published string limits.");
}
if (Object.keys(parameters).length > 50) throw new Error("At most 50 parameters are allowed.");
const workspacePath = `/bridge/api/v1/workspaces/${encodeURIComponent(workspaceId)}`;

async function request(method, path, body, expectedStatus) {
  const response = await fetch(`${BASE}${workspacePath}${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;
}

const template = await request(
  "GET", `/templates/${encodeURIComponent(templateRef)}`, undefined, 200,
);
if (!template?.id) throw new Error("Template discovery returned no id.");
const variables = template.variables ?? [];
const known = new Set(variables.map((variable) => variable.key));
const unknown = Object.keys(parameters).filter((key) => !known.has(key));
const missing = variables.filter((variable) =>
  variable.callerMustSupply &&
  (typeof parameters[variable.key] !== "string" || !parameters[variable.key].trim())
);
if (unknown.length || missing.length) {
  throw new Error(`Check template keys: ${unknown.length} unknown, ${missing.length} missing.`);
}

const conversation = await request("POST", "/conversations", {
  participants: {
    externals: [{
      identifier: contactId,
      identifierType: "ID",
      messageProviderType: "WHATSAPP",
      providerChannelId,
    }],
    internals: [{ identifier: internalEmail, identifierType: "EMAIL" }],
  },
  onboardingTemplates: [{ templateId: template.id, parameters }],
}, 201);
if (!conversation?.id || conversation.workspaceId !== workspaceId) {
  throw new Error("The Conversation response does not identify the intended workspace.");
}
console.log({ templateId: template.id, conversationId: conversation.id });
```

```bash theme={null}
node send-template.mjs
```

El ejemplo usa el ID devuelto por la consulta en `onboardingTemplates[].templateId`. Las dos operaciones de conversaciones salientes también aceptan el ID o nombre de una plantilla; si envías ambos, el ID tiene prioridad. Sus cuerpos de solicitud son distintos de `onboardingTemplates`: lee el contrato de la operación antes de reutilizar este cuerpo en otra.

Las comprobaciones locales detectan claves desconocidas o faltantes. Bridge realiza igualmente su propia validación, incluida la aprobación para la línea elegida y las reglas finales de valores de WhatsApp. La validación local no equivale a aprobación ni garantiza la entrega.

## Cómo corregir una solicitud rechazada

| Error | Qué hacer |
| - | - |
| Consulta `BRIDGE_TEMPLATE_0001` | Comprueba el ID o nombre y el espacio de trabajo. Esta respuesta no revela si el identificador pertenece a otro espacio de trabajo. |
| `BRIDGE_CONVERSATION_0604` | Proporciona valores que no estén en blanco para las variables de `extra.missingVariables`. |
| `BRIDGE_CONVERSATION_0605` | Quita las claves de `extra.unknownKeys`; usa las claves independientes del proveedor devueltas por la consulta. |
| `BRIDGE_CONVERSATION_0607` | Corrige los valores de `extra.invalidVariables` según su `reason`. |
| `BRIDGE_CONVERSATION_0608` | Pídele a un administrador que cambie la secuencia de plantillas de inicio del espacio de trabajo. Cambiar los valores de tu plantilla no resuelve este error de configuración. |

Consulta la [referencia completa de errores de plantillas](https://docs.bridge.new/es/templates-and-parameters.md#errors) para los errores de aprobación, pertenencia, parámetros no admitidos y solicitudes mal formadas. No reintentes automáticamente una solicitud de conversación que agotó el tiempo de espera: primero determina su resultado.


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