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

# Crie um contato e envie uma mensagem

> Siga um fluxo completo no servidor, do Contato à conversa e à mensagem, preservando os identificadores retornados.

Este guia cria um Contato, inicia uma conversa com um usuário interno do Bridge e cria uma mensagem. Execute o exemplo no seu servidor.

> [!WARNING]
>
> Use um Contato de teste para o qual você tem autorização de envio. A criação da conversa pode executar os templates iniciais do workspace antes da requisição separada de mensagem. Revise essa configuração primeiro: definir como false o sinalizador de envio externo da mensagem posterior não desabilita os templates iniciais da conversa.

## Antes de começar

* Obtenha uma chave de API para uso no servidor no guia de [autenticação](https://docs.bridge.new/pt-br/credentials.md).
* Tenha o ID do workspace, o `providerChannelId` de uma linha ativa 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).
* Use um novo telefone de teste em formato internacional. Se o Contato já existir, use a [consulta de contatos](https://docs.bridge.new/pt-br/api-reference/contacts-api/obter-contato-por-um-identificador.md) em vez de criá-lo novamente.
* Verifique os atributos personalizados obrigatórios e a sequência inicial configurada no workspace. Este exemplo mínimo não envia atributos personalizados nem substitui os templates.
* Escolha `enableExternalBroadcast` explicitamente: `true` solicita o envio externo quando as regras da conversa e do destinatário permitem; `false` ainda cria a mensagem, mas não realiza o envio externo. Nenhum dos valores confirma a entrega pelo provedor. Esse sinalizador não ignora regras de visibilidade ou permissões.

## A sequência

| Etapa | Requisição | Valor a guardar |
| - | - | - |
| Verificar o acesso | `GET /bridge/api/health` | Resposta HTTP bem-sucedida |
| Criar Contato | `POST /bridge/api/v1/workspaces/{workspaceId}/contacts` | `id` do Contato |
| Iniciar conversa | `POST /bridge/api/v1/workspaces/{workspaceId}/conversations` | `id` da conversa |
| Criar mensagem | `POST /bridge/api/v1/workspaces/{workspaceId}/messages` | `messageId` |

O `id` do Contato passa a ser o `identifier` do participante externo, com `identifierType: "ID"`. O `id` da conversa passa a ser o `conversationId` da mensagem.

## Execute o exemplo

Use Node.js com `fetch` nativo. Salve como `first-conversation.mjs`. Configure estas variáveis de ambiente no servidor, usando os recursos de segredos e configuração da sua aplicação:

| Variável | Valor |
| - | - |
| `BRIDGE_API_KEY` | Sua chave de API secreta |
| `BRIDGE_WORKSPACE_ID` | O ID do workspace desejado |
| `BRIDGE_PROVIDER_CHANNEL_ID` | O ID da linha de WhatsApp autorizada, não seu telefone |
| `BRIDGE_USER_EMAIL` | Um usuário interno do Bridge no mesmo workspace |
| `TEST_CONTACT_PHONE` | O telefone de um novo Contato de teste autorizado |
| `ENABLE_EXTERNAL_BROADCAST` | Exatamente `true` ou `false`; nenhum valor padrão é presumido |

Os nomes e a mensagem abaixo são exemplos. Substitua-os pelo conteúdo de teste desejado antes de executar.

```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
```

## Entenda o resultado

* Uma resposta `201` de Contato informa sua identidade e workspace. Leia `type` para verificar a classificação real: `NORMAL` ou `PARTIAL`.
* Uma resposta `201` de conversa fornece o ID a usar na próxima etapa. Quando nenhuma linha está livre, o Bridge pode recuperar uma conversa liberada com exatamente os participantes solicitados. Nesse caso, o ID e o histórico são mantidos, e os valores solicitados de `name` e `status` não são aplicados.
* Uma resposta `201` de mensagem fornece `messageId`. Isso, por si só, não comprova que o WhatsApp entregou a mensagem ao Contato.

Este guia atribui explicitamente um usuário interno do Bridge. Para atribuir uma equipe, use a opção documentada `teamId` em vez de `participants.internals`: as duas opções são mutuamente exclusivas.

## Se uma etapa falhar

O exemplo para na requisição que falhou e nunca repete uma operação de escrita automaticamente. Uma falha de rede pode deixar o resultado incerto. Consulte o recurso correspondente antes de repetir uma criação ou um envio.

| Situação | Próxima ação |
| - | - |
| O Contato já existe | Use a consulta de contatos e o `id` retornado; não continue criando o mesmo Contato. |
| Erro de marca ou linha | Confirme a linha ou marca autorizada com o administrador; o telefone de uma linha não é seu ID. |
| Erro de template `0604`–`0608` | Consulte [parâmetros de templates de WhatsApp](https://docs.bridge.new/pt-br/templates-and-parameters.md), incluindo os erros de configuração do workspace. |
| Mensagem rejeitada porque a conversa está liberada | Verifique o estado da conversa e a referência de erros da operação antes de realizar outra ação. |
| `429` | Siga o guia de [limites de requisições](https://docs.bridge.new/pt-br/rate-limits.md), incluindo `Retry-After`. |

Veja [respostas e erros](https://docs.bridge.new/pt-br/guides/responses.md) para conhecer os formatos de resposta e decidir como recuperar a operação.

## Próximos passos

* [Faça upload e envie um anexo](https://docs.bridge.new/pt-br/guides/send-attachments.md).
* [Escolha e preencha um template de WhatsApp](https://docs.bridge.new/pt-br/guides/send-template.md).
* Consulte os contratos completos de requisição e resposta para [criar um Contato](https://docs.bridge.new/pt-br/api-reference/contacts-api/criar-contato.md), [criar uma conversa](https://docs.bridge.new/pt-br/api-reference/conversations-api/criar-conversa-com-identifica%C3%A7%C3%A3o-flex%C3%ADvel-de-usu%C3%A1rios) e [criar uma mensagem](https://docs.bridge.new/pt-br/api-reference/messages-api/criar-mensagem.md).


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