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

# Escolha e preencha um template de WhatsApp

> Descubra um template por ID ou nome, forneça os valores por suas chaves de variável agnósticas e use o ID retornado em uma requisição de conversa.

Use este guia quando quiser abrir uma conversa com um template específico de WhatsApp. A [referência detalhada de templates](https://docs.bridge.new/pt-br/templates-and-parameters.md) explica as regras de validação e todos os erros de template documentados.

## Antes de começar

* Tenha o **ID ou nome** do template. Ambos são aceitos por `GET .../templates/{templateId}`.
* Confirme que o template foi aprovado para a conta WhatsApp Business associada à linha desejada.
* Tenha o ID de um Contato de teste existente, o `providerChannelId` da linha autorizada de WhatsApp e o e-mail de um usuário interno do Bridge. Veja [conceitos e identificadores](https://docs.bridge.new/pt-br/guides/identifiers.md).
* Revise a sequência inicial do workspace: sua substituição pode trocar toda a sequência ou apenas o primeiro template, conforme a configuração.

> [!WARNING]
>
> A requisição final inicia uma conversa e pode enviar os templates iniciais. Use um Contato de teste autorizado e o conteúdo pretendido.

## 1. Descubra as variáveis

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

Codifique o ID ou nome fornecido para uso na URL. Leia `id`, `name`, `variables` e `driftWarning` na resposta.

| Variável | Ação |
| - | - |
| `callerMustSupply: true` | Forneça uma string não vazia na `key` dessa variável. |
| `callerMustSupply: false`, não personalizada | Omita-a para manter o valor definido pelo Bridge para cada Contato. Um valor informado substitui esse valor para todos os Contatos. |
| `isCustom: true` | Forneça seu valor ou omita-o ou envie-o vazio para usar o `default`. |

Use a `key` agnóstica, nunca o `label` de exibição, uma posição da Meta ou um nome de variável inventado. `driftWarning` é diagnóstico e, por si só, não bloqueia o envio.

## 2. Prepare seus valores

Crie um arquivo JSON no servidor contendo somente as chaves retornadas pela descoberta. Para um template que realmente declare `order_number` e `delivery_date`, ele poderia conter:

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

Esses dois nomes são exemplos, não campos universais do Bridge. Consulte seu próprio template antes de usá-los. Mantenha os valores dentro das [regras de valores do WhatsApp](https://docs.bridge.new/pt-br/templates-and-parameters.md#whatsapp-value-rules). Para valores não personalizados que você quer que o Bridge preencha, omita as chaves em vez de enviar strings vazias.

## 3. Descubra, valide e crie a conversa

Use Node.js com `fetch` nativo. Salve como `send-template.mjs` e defina `BRIDGE_API_KEY`, `BRIDGE_WORKSPACE_ID`, `BRIDGE_TEMPLATE_ID_OR_NAME`, `TEMPLATE_VALUES_PATH`, `BRIDGE_CONTACT_ID`, `BRIDGE_PROVIDER_CHANNEL_ID` e `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
```

O exemplo usa o ID retornado pela descoberta em `onboardingTemplates[].templateId`. As duas operações outbound também aceitam ID ou nome do template, com prioridade para o ID quando ambos são informados. Seus formatos de requisição são diferentes de `onboardingTemplates`; leia o contrato da operação antes de reutilizar esse corpo em outro contexto.

As verificações locais detectam chaves desconhecidas ou obrigatórias ausentes. O Bridge ainda realiza sua própria validação, incluindo a aprovação para a linha selecionada e as regras finais de valores do WhatsApp. Não trate a validação local como aprovação ou garantia de entrega.

## Corrija uma requisição rejeitada

| Erro | O que fazer |
| - | - |
| Descoberta `BRIDGE_TEMPLATE_0001` | Confira o ID ou nome e o workspace. Essa resposta não revela se o identificador pertence a outro workspace. |
| `BRIDGE_CONVERSATION_0604` | Forneça valores não vazios para as variáveis de `extra.missingVariables`. |
| `BRIDGE_CONVERSATION_0605` | Remova as chaves de `extra.unknownKeys`; use as chaves agnósticas da descoberta. |
| `BRIDGE_CONVERSATION_0607` | Corrija os valores de `extra.invalidVariables` conforme o `reason` de cada um. |
| `BRIDGE_CONVERSATION_0608` | Peça a um administrador do workspace para alterar a sequência inicial configurada. Mudar os valores do seu template não corrige esse erro de configuração. |

Leia a [referência completa de erros de templates](https://docs.bridge.new/pt-br/templates-and-parameters.md#errors) para entender aprovação, titularidade, parâmetros não aceitos e requisições malformadas. Não repita automaticamente uma requisição de conversa que expirou: primeiro verifique o resultado.


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