MCBridge — Documentação

Middleware de orquestração para Salesforce Marketing Cloud. Integre qualquer sistema ao SFMC com uma chamada simples de API.

MCBridge — Documentation

Orchestration middleware for Salesforce Marketing Cloud. Integrate any system with SFMC using a simple API call.

Última atualização: 28/06/2026 20:29 BRT (v0.6.0)

Last updated: 2026-06-28 20:29 BRT (v0.6.0)

Python Node.js REST API SFMC Multi-BU

O que é o MCBridge?

O MCBridge é uma API REST que abstrai toda a complexidade do Salesforce Marketing Cloud. Em vez de lidar com autenticação OAuth, subdomínios, BUs e formatos de payload, seu sistema só precisa saber a key da DE ou do Triggered Send.

Como funciona

O MCBridge recebe a chamada, descobre automaticamente em qual BU a key pertence, autentica no SFMC com token cacheado e executa a operação.

What is MCBridge?

MCBridge is a REST API that abstracts all the complexity of Salesforce Marketing Cloud. Instead of dealing with OAuth authentication, subdomains, BUs and payload formats, your system only needs to know the key of the DE or Triggered Send.

How it works

MCBridge receives the call, automatically discovers which BU the key belongs to, authenticates with SFMC using a cached token and executes the operation.

flow
# Seu sistema
POST /v1/de/upsert
  externalKey: "DE_CLIENTES_VIP"
  records: [{...}]
  X-API-Key: "sua-api-key"

↓ MCBridge faz tudo automaticamente

# Autentica no SFMC
# Descobre a BU correta
# Grava os dados
# Retorna confirmação

→ { "status": "success", "records_processed": 1 }
🔗
Base URL: https://api.mcbridge.com.br
Base URL: https://api.mcbridge.com.br

Quick Start

Quick Start

1

Receba sua API Key

Get your API Key

Solicite sua API Key ao administrador do MCBridge. Ela será usada em todas as chamadas.

Request your API Key from the MCBridge administrator. It will be used in all calls.

2

Obtenha a External Key da DE

Get the DE External Key

No SFMC, acesse a DE e copie a Chave Externa. O administrador do MCBridge precisa cadastrá-la no painel.

In SFMC, access the DE and copy the External Key. The MCBridge administrator needs to register it in the panel.

3

Faça sua primeira chamada

Make your first call

curl
curl -s -X POST "https://api.mcbridge.com.br/v1/de/upsert" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: SUA_API_KEY" \
  -d '{
    "externalKey": "SUA_EXTERNAL_KEY",
    "records": [
      {
        "email": "cliente@empresa.com",
        "nome": "João Silva"
      }
    ]
  }'

1. Cadastrar Cliente

No painel admin, acesse a aba Clientes e clique em + Novo Cliente.

Informe o nome da empresa (ex: Empresa ABC, Grupo XYZ). O cliente é o topo da hierarquia — BUs e keys são organizadas por cliente.

1. Register Client

In the admin panel, go to the Clients tab and click + New Client.

Enter the company name (e.g.: Company ABC, XYZ Group). The client is the top of the hierarchy — BUs and keys are organized by client.

2. Cadastrar Business Unit

Na aba BUs, clique em + Nova BU e preencha as credenciais do Installed Package do SFMC.

2. Register Business Unit

In the BUs tab, click + New BU and fill in the SFMC Installed Package credentials.

Campo / Field Descrição Description Onde encontrar Where to find
BU ID (MID) ID numérico da Business Unit Numeric Business Unit ID Setup → Business Units Setup → Business Units
REST Subdomain Prefixo do REST Base URI REST Base URI prefix Setup → Installed Packages → API Integration → REST Base URI Setup → Installed Packages → API Integration → REST Base URI
Auth Subdomain Prefixo do Authentication Base URI Authentication Base URI prefix Setup → Installed Packages → API Integration → Authentication Base URI Setup → Installed Packages → API Integration → Authentication Base URI
Client ID ID do Installed Package Installed Package ID Setup → Installed Packages → API Integration Setup → Installed Packages → API Integration
Client Secret Secret do Installed Package Installed Package Secret Setup → Installed Packages → API Integration Setup → Installed Packages → API Integration
DE de Consentimento (External Key) External Key da DE que armazena o consentimento desta BU (endpoints /v1/consent). Opcional — habilite o checkbox para ativar. External Key of the DE that stores this BU's consent (/v1/consent endpoints). Optional — enable the checkbox to activate. Email Studio → Data Extensions → Propriedades → Chave Externa Email Studio → Data Extensions → Properties → External Key
Campo PK do Consentimento Chave do assinante na DE (ex: Subscriberkey, Email, CPF). Obrigatório quando a DE de Consentimento estiver habilitada. Subscriber key field in the DE (e.g.: Subscriberkey, Email, CPF). Required when the Consent DE is enabled. Definido na estrutura da DE no SFMC Defined in the DE structure in SFMC
⚠️

REST Subdomain: copie apenas o prefixo da URL. Ex: da URL https://mc411-xxx.rest.marketingcloudapis.com copie apenas mc411-xxx.

REST Subdomain: copy only the URL prefix. Ex: from https://mc411-xxx.rest.marketingcloudapis.com copy only mc411-xxx.

3. Cadastrar Keys

Na aba Keys, cadastre as DEs e Triggered Sends que serão usados. Uma BU pode ter múltiplas keys.

3. Register Keys

In the Keys tab, register the DEs and Triggered Sends that will be used. A BU can have multiple keys.

Campo / Field Descrição Description
Tipo Data Extension ou Triggered Send Data Extension or Triggered Send
Finalidade Audiência (padrão) ou Log de Erros (máx. 1 por BU) Audience (default) or Error Log (max 1 per BU)
External Key Chave Externa da DE no SFMC DE External Key in SFMC
Label Nome amigável para identificar a key Friendly name to identify the key
📍

A External Key da DE está em: Email Studio → Data Extensions → [Nome da DE] → Propriedades → Chave Externa

The DE External Key is at: Email Studio → Data Extensions → [DE Name] → Properties → External Key

⚠️

Consentimento: a Key da DE de consentimento também deve ser cadastrada aqui (além de configurada na BU). Sem a Key cadastrada, o endpoint /v1/consent retorna 404.

Consent: the consent DE's Key must also be registered here (in addition to being configured on the BU). Without the Key registered, the /v1/consent endpoint returns 404.

4. Gerar API Key

Na aba API Keys, clique em + Gerar Nova Key, informe o nome do sistema que vai usar (ex: Sistema ERP, Portal Web) e copie a key gerada.

4. Generate API Key

In the API Keys tab, click + Generate New Key, enter the name of the system that will use it (e.g.: ERP System, Web Portal) and copy the generated key.

⚠️

Atenção: a key é exibida apenas uma vez. Copie e armazene em local seguro imediatamente.

Warning: the key is shown only once. Copy and store it in a safe place immediately.

POST /v1/de/upsert

Grava ou atualiza registros em uma Data Extension do SFMC.

Inserts or updates records in an SFMC Data Extension.

POST /v1/de/upsert

Requer header X-API-Key

Requires X-API-Key header

Request Body

Request Body

json
{
  "externalKey": "SUA_EXTERNAL_KEY",  // External Key da DE no SFMC
  "records": [             // Array de registros (pode ser 1 ou N)
    {
      "campo1": "valor1",
      "campo2": "valor2"
    }
  ]
}

Response de Sucesso

Success Response

json — 200 OK
{
  "status": "success",
  "bu_id": "7237374",
  "external_key": "SUA_EXTERNAL_KEY",
  "records_processed": 1
}

Validacao de schema

Schema validation

Antes de enviar ao SFMC, o payload e validado contra o schema da Data Extension (campos existentes, chaves primarias, obrigatorios e tipos). Se algo estiver invalido, a requisicao retorna 400 e nada e enviado ao SFMC. O erro e registrado nos logs com operation: "validation".

Before sending to SFMC, the payload is validated against the Data Extension schema (existing fields, primary keys, required fields and types). If anything is invalid, the request returns 400 and nothing is sent to SFMC. The error is recorded in the logs with operation: "validation".

json - 400 Bad Request
{
  "detail": {
    "success": false,
    "error": "schema_validation_failed",
    "correlationId": "abc-123",
    "errorCount": 2,
    "details": [
      {
        "row": 0,
        "field": "email",
        "code": "missing_primary_key",
        "message": "primary key 'email' ausente ou vazia",
        "value": null
      },
      {
        "row": 0,
        "field": "campo_x",
        "code": "unknown_field",
        "message": "campo 'campo_x' nao existe na DE",
        "value": "abc"
      }
    ]
  }
}

Codigos por campo: unknown_field, missing_primary_key, required, invalid_text, invalid_emailaddress, invalid_number, invalid_decimal, invalid_boolean, invalid_date.

Per-field codes: unknown_field, missing_primary_key, required, invalid_text, invalid_emailaddress, invalid_number, invalid_decimal, invalid_boolean, invalid_date.

Rate limit

Rate limit

Cada API Key tem um limite de requisicoes por minuto (padrao: 600 req/min, configuravel por key). Ao exceder, a requisicao retorna 429 Too Many Requests e nada e enviado ao SFMC.

Each API Key has a per-minute request limit (default: 600 req/min, configurable per key). When exceeded, the request returns 429 Too Many Requests and nothing is sent to SFMC.

Headers retornados no 429: Retry-After (segundos ate poder tentar de novo), X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset. Ao receber 429, aguarde o tempo indicado em Retry-After antes de repetir a chamada.

Headers returned on 429: Retry-After (seconds until you can retry), X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset. On 429, wait the time indicated in Retry-After before retrying.

IP Whitelist

IP Whitelist

Uma API Key pode ter IPs ou faixas (CIDR) autorizados. O recurso e opt-in: se a key nao tiver nenhuma regra cadastrada, aceita qualquer IP (comportamento padrao). Se houver regra cadastrada e a chamada vier de um IP fora da lista, retorna 403 Forbidden.

An API Key can have authorized IPs or ranges (CIDR). This is opt-in: if the key has no rule registered, it accepts any IP (default behavior). If a rule exists and the call comes from an IP outside the list, it returns 403 Forbidden.

Modo Assíncrono (payloads grandes)

Asynchronous Mode (large payloads)

Quando o array records tem mais de 500 itens (limite configurável via MCBRIDGE_ASYNC_THRESHOLD), a requisição é processada de forma assíncrona: o MCBridge cria um job, enfileira o processamento e responde imediatamente com 202 Accepted e um job_id. O upsert no SFMC acontece em segundo plano (worker). Payloads de até 500 itens continuam síncronos (200 OK) como descrito acima.

When the records array has more than 500 items (configurable via MCBRIDGE_ASYNC_THRESHOLD), the request is processed asynchronously: MCBridge creates a job, enqueues it and responds immediately with 202 Accepted plus a job_id. The SFMC upsert runs in the background (worker). Payloads up to 500 items remain synchronous (200 OK) as described above.

json — 202 Accepted
{
  "job_id": "job-272e6a27107e4239b2bbf5d38ddf314a",
  "status": "queued",
  "items_total": 501,
  "correlationId": "bd38d198-c2ef-45ec-a246-1f03e1e4b0b5",
  "reused": false
}

Acompanhe o resultado consultando GET /v1/jobs/{job_id} (abaixo) até o status ficar completed.

Track the result by polling GET /v1/jobs/{job_id} (below) until status becomes completed.

Idempotência (Idempotency-Key)

Idempotency (Idempotency-Key)

Envie o header opcional Idempotency-Key para evitar jobs duplicados em caso de retry. Se uma requisição com a mesma chave já existir, o MCBridge retorna o mesmo job_id com "reused": true, sem criar nem reprocessar nada.

Send the optional Idempotency-Key header to avoid duplicate jobs on retries. If a request with the same key already exists, MCBridge returns the same job_id with "reused": true, without creating or reprocessing anything.

http
Idempotency-Key: minha-chave-unica-001

Dry-Run / Modo Validação

Disponível desde v0.4.1. Valida o payload contra o schema da Data Extension sem enviar nada ao SFMC. Use para testar payloads antes de produtivo — ideal quando não há ambiente de DEV.

Available since v0.4.1. Validates the payload against the Data Extension schema without sending anything to SFMC. Use to test payloads before going live — ideal when no DEV environment exists.

Como ativar

How to activate

Envie qualquer requisição POST /v1/de/upsert com o header:

Send any POST /v1/de/upsert request with the header:

http
X-MCBridge-DryRun: true

Comportamento

Behavior

Payload válido (HTTP 200): retorna confirmação sem chamar o SFMC. Zero side-effects (sem envio, sem log de sucesso, sem fila, sem hook, sem DLQ).

Valid payload (HTTP 200): returns confirmation without calling SFMC. Zero side-effects (no send, no success log, no queue, no hook, no DLQ).

json
{
  "valid": true,
  "records_analyzed": 125,
  "dry_run": true,
  "message": "Schema validation passed. No data was pushed to SFMC."
}

Payload inválido (HTTP 400 schema_validation_failed): mesma resposta do fluxo normal, com lista de erros por linha (row, field, code, message). Log gravado no Postgres com operation = "dry_run_validation" para facilitar análise de suporte.

Invalid payload (HTTP 400 schema_validation_failed): same response as the normal flow, with row-level error list (row, field, code, message). Log persisted in Postgres with operation = "dry_run_validation" for easier support analysis.

Exemplo cURL

cURL Example

bash
curl -X POST "https://api.mcbridge.com.br/v1/de/upsert" \
  -H "X-API-Key: SUA_API_KEY" \
  -H "X-MCBridge-DryRun: true" \
  -H "Content-Type: application/json" \
  -d '{
    "externalKey": "SEU_EXTERNAL_KEY",
    "records": [
      { "email": "teste@exemplo.com", "nome": "Teste" }
    ]
  }'

Limitação importante

Important limitation

O modo Dry-Run valida a estrutura e conformidade do payload sem enviar dados ao Salesforce Marketing Cloud. Ele não simula regras de negócio, automações, journeys ou efeitos colaterais do ambiente SFMC.

Dry-Run mode validates the structure and conformity of the payload without sending data to Salesforce Marketing Cloud. It does not simulate business rules, automations, journeys, or side-effects in the SFMC environment.

GET /v1/jobs/{job_id}

Consulta o status e os contadores de um job assíncrono criado pelo POST /v1/de/upsert (payloads > 500).

Returns the status and counters of an async job created by POST /v1/de/upsert (payloads > 500).

GET /v1/jobs/{job_id}

Requer header X-API-Key

Requires X-API-Key header

Response de Sucesso

Success Response

json — 200 OK
{
  "job_id": "job-272e6a27107e4239b2bbf5d38ddf314a",
  "status": "completed",  // queued | running | completed | partially_completed | failed | dead_lettered
  "tenant_bu": "7237374",
  "externalKey": "SUA_EXTERNAL_KEY",
  "correlationId": "bd38d198-...",
  "items": {
    "total": 501,
    "ok": 501,
    "failed": 0,
    "dead_lettered": 0
  },
  "attempts": 0,
  "failure_reason_code": null,
  "created_at_utc": "2026-05-31T15:35:45Z",
  "updated_at_utc": "2026-05-31T15:36:02Z",
  "throttled": false,
  "last_throttled_at": null
}

Campos de controle de fluxo:

  • throttled (boolean): indicador de controle de fluxo do lote. Retorna false em condições normais de operação.
  • last_throttled_at (string/null): timestamp UTC da última validação de vazão. Retorna null por padrão.

Flow-control fields:

  • throttled (boolean): batch flow-control indicator. Returns false under normal operating conditions.
  • last_throttled_at (string/null): UTC timestamp of the last flow validation. Returns null by default.

Job não encontrado

Job not found

json — 404 Not Found
{
  "detail": "Job 'job-...' not found"
}

Exemplo cURL

cURL Example

bash
curl "https://api.mcbridge.com.br/v1/jobs/job-272e6a27107e4239b2bbf5d38ddf314a" \
  -H "X-API-Key: SUA_API_KEY"

POST /v1/send/email

Dispara um e-mail transacional via Triggered Send do SFMC.

Fires a transactional email via SFMC Triggered Send.

POST /v1/send/email

Requer header X-API-Key

Requires X-API-Key header

json
{
  "definitionKey": "SUA_DEFINITION_KEY",  // Definition Key do Triggered Send
  "contactKey": "email@cliente.com",    // E-mail do destinatário
  "data": {                             // Atributos para personalização
    "nome": "João Silva",
    "token": "abc-123-xyz"
  }
}
json — 200 OK
{
  "status": "success",
  "bu_id": "7237374",
  "definition_key": "SUA_DEFINITION_KEY",
  "contact_key": "email@cliente.com",
  "message_key": "uuid-gerado-automaticamente"
}

POST /v1/de/query

Lê registros de uma Data Extension do SFMC, com filtros. Modo síncrono (Fase 1): retorna até 5.000 registros por chamada.

Reads records from an SFMC Data Extension, with filters. Synchronous mode (Phase 1): returns up to 5,000 records per call.

POST /v1/de/query

Requer header X-API-Key

Requires X-API-Key header

Request Body

Request Body

json
{
  "externalKey": "SUA_EXTERNAL_KEY",  // External Key da DE no SFMC
  "filters": [                  // 0, 1 ou 2 filtros (máx 2 na Fase 1)
    {
      "field": "OpenEventDate",
      "operator": "between",   // equals | greater_than | less_than | between
      "value": "2026-06-01",
      "value2": "2026-06-02"    // obrigatório só para "between"
    }
  ],
  "logic": "AND",             // só AND na Fase 1
  "columns": ["Subscriberkey", "OpenEventDate"],  // opcional; omitido = todas
  "pageSize": 2500          // opcional; default 2500, máx 2500
}

Response de Sucesso

Success Response

json — 200 OK
{
  "status": "success",
  "bu_id": "7237374",
  "external_key": "SUA_EXTERNAL_KEY",
  "count": 64,
  "records": [
    {
      "Subscriberkey": "cliente@email.com",
      "OpenEventDate": "6/3/2025 8:52:00 AM"
    }
  ],
  "hasMore": false
}

Operadores e filtros

Operators and filters

Operadores suportados: equals, greater_than, less_than, between. Combinação apenas com AND. Na Fase 1, no máximo 2 filtros. O operador between exige value e value2. Os tipos de valor (data vs. número/texto) são detectados automaticamente a partir do schema da DE.

Supported operators: equals, greater_than, less_than, between. Combined only with AND. In Phase 1, a maximum of 2 filters. The between operator requires value and value2. Value types (date vs. number/text) are auto-detected from the DE schema.

Não suportados na Fase 1 (retornam 422): OR, LIKE, NOT, IN, agrupamentos aninhados e 3+ filtros.

Not supported in Phase 1 (return 422): OR, LIKE, NOT, IN, nested groups and 3+ filters.

Limite síncrono

Synchronous limit

O modo síncrono retorna no máximo 5.000 registros. Consultas que ultrapassam esse total retornam 422 indicando o uso do modo de exportação assíncrona (Fase 2). Use filtros para reduzir o resultado.

Synchronous mode returns at most 5,000 records. Queries exceeding this total return 422 pointing to the asynchronous export mode (Phase 2). Use filters to narrow the result.

json — 422 Unprocessable Entity
{
  "detail": {
    "error": "Query exceeds synchronous retrieval limit. Use async export mode.",
    "limit": 5000
  }
}

Campo inexistente

Unknown field

Se um field de filtro ou columns não existir na DE, retorna 422 com a lista de campos disponíveis. Os nomes são case-sensitive (ex.: SubscriberkeySubscriberKey).

If a filter field or a column does not exist in the DE, it returns 422 with the list of available fields. Names are case-sensitive (e.g., SubscriberkeySubscriberKey).

json — 422 Unprocessable Entity
{
  "detail": {
    "error": "unknown field(s) in query",
    "fields": ["CampoQueNaoExiste"],
    "available": ["AccountID", "OpenEventDate", "Subscriberkey"]
  }
}

Nota (Fase 1): datas retornam no formato nativo do SFMC (ex.: 6/3/2025 8:52:00 AM). Exportação de grandes volumes (acima de 5.000) será atendida pela Fase 2 (assíncrona), reusando a esteira de jobs/worker.

Note (Phase 1): dates are returned in SFMC's native format (e.g., 6/3/2025 8:52:00 AM). Large-volume export (above 5,000) will be handled by Phase 2 (asynchronous), reusing the jobs/worker pipeline.

POST /v1/de/export

Exporta registros de uma Data Extension de forma assíncrona. Sem limite de volume. Cria um job e retorna imediatamente com 202 Accepted e um jobId. Acompanhe via GET /v1/jobs/{jobId} e baixe via GET /v1/jobs/{jobId}/download.

Exports records from a Data Extension asynchronously. No volume limit. Creates a job and returns immediately with 202 Accepted and a jobId. Track via GET /v1/jobs/{jobId} and download via GET /v1/jobs/{jobId}/download.

POST /v1/de/export

Requer header X-API-Key

Requires X-API-Key header

Request Body

Request Body

json
{
  "externalKey": "SUA_EXTERNAL_KEY",
  "filters": [
    {
      "field": "OpenEventDate",
      "operator": "between",
      "value": "2026-06-01",
      "value2": "2026-06-30"
    }
  ],
  "columns": ["Subscriberkey", "OpenEventDate"],
  "format": "jsonl"
}

Response — 202 Accepted

Response — 202 Accepted

json — 202 Accepted
{
  "jobId": "exp-9698616881db412384c41ea1dd44a6fa",
  "status": "queued"
}

Fluxo completo

Full flow

1. POST /v1/de/export202 + jobId
2. Polling GET /v1/jobs/{jobId} até status: "completed" e downloadAvailable: true
3. GET /v1/jobs/{jobId}/download → presigned URLs S3

1. POST /v1/de/export202 + jobId
2. Poll GET /v1/jobs/{jobId} until status: "completed" and downloadAvailable: true
3. GET /v1/jobs/{jobId}/download → presigned S3 URLs

ℹ️

O download exige a mesma API Key que criou o export. Chave diferente retorna 403. Arquivos expiram em 6h (410 Gone após isso).

Download requires the same API Key that created the export. A different key returns 403. Files expire after 6h (410 Gone after that).

GET /v1/jobs/{job_id}/download

Retorna as presigned URLs S3 para baixar as partes do export. Disponível apenas quando o job está completed e downloadAvailable: true.

Returns S3 presigned URLs to download the export parts. Only available when the job is completed and downloadAvailable: true.

GET /v1/jobs/{job_id}/download

Requer header X-API-Key — mesma key que criou o export

Requires X-API-Key — must be the same key that created the export

Response de Sucesso

Success Response

json — 200 OK
{
  "jobId": "exp-9698616881db412384c41ea1dd44a6fa",
  "status": "completed",
  "format": "jsonl",
  "totalParts": 1,
  "totalRecords": 395000,
  "expiresAt": "2026-06-23T17:10:01Z",
  "urls": [
    {
      "part": "part-0001.jsonl",
      "url": "https://s3.amazonaws.com/..."
    }
  ]
}

Erros possíveis

Possible errors

HTTPSituaçãoSituation
403API Key diferente da que criou o exportWrong API Key
404Job não existe ou não é exportJob not found or not an export
409Job ainda não completouJob not yet completed
410Export expirado (TTL 6h)Export expired (6h TTL)

Exemplo cURL

cURL Example

bash
# 1. Criar export
curl -X POST "https://api.mcbridge.com.br/v1/de/export" \
  -H "X-API-Key: SUA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"externalKey": "SUA_EXTERNAL_KEY"}'

# 2. Acompanhar
curl "https://api.mcbridge.com.br/v1/jobs/exp-..." \
  -H "X-API-Key: SUA_API_KEY"

# 3. Baixar
curl "https://api.mcbridge.com.br/v1/jobs/exp-.../download" \
  -H "X-API-Key: SUA_API_KEY"

GET /health

Verifica se o serviço está operacional. Não requer autenticação.

Checks if the service is operational. No authentication required.

json — 200 OK
{
  "status": "ok",
  "product": "MCBridge",
  "version": "0.4.1"
}

Python

Gravar em Data Extension

Write to Data Extension

python
import requests

API_URL = "https://api.mcbridge.com.br"
API_KEY = "SUA_API_KEY"

def upsert_de(external_key, records):
    response = requests.post(
        f"{API_URL}/v1/de/upsert",
        headers={
            "Content-Type": "application/json",
            "X-API-Key": API_KEY
        },
        json={
            "externalKey": external_key,
            "records": records
        }
    )
    response.raise_for_status()
    return response.json()

# Exemplo de uso
resultado = upsert_de("DE_CLIENTES", [
    {"email": "joao@empresa.com", "nome": "João Silva"},
    {"email": "maria@empresa.com", "nome": "Maria Santos"}
])
print(resultado)
# {'status': 'success', 'records_processed': 2}

Disparar E-mail Transacional

Send Transactional Email

python
def send_email(definition_key, contact_key, data):
    response = requests.post(
        f"{API_URL}/v1/send/email",
        headers={
            "Content-Type": "application/json",
            "X-API-Key": API_KEY
        },
        json={
            "definitionKey": definition_key,
            "contactKey": contact_key,
            "data": data
        }
    )
    response.raise_for_status()
    return response.json()

# Exemplo: e-mail de boas-vindas
send_email(
    definition_key="TRIGGERED_BOAS_VINDAS",
    contact_key="joao@empresa.com",
    data={"nome": "João Silva", "empresa": "ACME Corp"}
)

Node.js

javascript
const axios = require('axios');

const mcbridge = axios.create({
  baseURL: 'https://api.mcbridge.com.br',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'SUA_API_KEY'
  }
});

// Gravar em Data Extension
async function upsertDE(externalKey, records) {
  const { data } = await mcbridge.post('/v1/de/upsert', {
    externalKey,
    records
  });
  return data;
}

// Disparar e-mail
async function sendEmail(definitionKey, contactKey, attrs) {
  const { data } = await mcbridge.post('/v1/send/email', {
    definitionKey,
    contactKey,
    data: attrs
  });
  return data;
}

// Uso
upsertDE('DE_CLIENTES', [
  { email: 'joao@empresa.com', nome: 'João Silva' }
]).then(console.log);

cURL

Upsert em lote (100 registros)

Batch upsert (100 records)

bash
curl -s -X POST \
  "https://api.mcbridge.com.br/v1/de/upsert" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: SUA_API_KEY" \
  -d '{
    "externalKey": "DE_CLIENTES",
    "records": [
      {"email": "a@empresa.com", "nome": "Alice"},
      {"email": "b@empresa.com", "nome": "Bob"}
    ]
  }'

Log de Erros no SFMC

O MCBridge pode gravar erros automaticamente em uma DE do SFMC, além de armazená-los no banco de dados interno.

Campos obrigatórios da DE de Log

Crie uma DE no SFMC com os seguintes campos:

Error Log in SFMC

MCBridge can automatically write errors to an SFMC DE, in addition to storing them in the internal database.

Required fields for the Log DE

Create a DE in SFMC with the following fields:

Campo / Field Tipo / Type Tamanho / Length PK
log_idText36
timestampText50
external_keyText500
operationText50
status_codeText10
responseText4000
bu_idText50

Como configurar

1

Crie a DE no SFMC

Com os campos acima. Copie a External Key.

2

Cadastre no painel MCBridge

Aba Keys+ Nova Key → Tipo: Data Extension → Finalidade: Log de Erros → cole a External Key.

3

Pronto!

O MCBridge detecta automaticamente e grava os erros nessa DE.

How to configure

1

Create the DE in SFMC

With the fields above. Copy the External Key.

2

Register in MCBridge panel

Keys tab → + New Key → Type: Data Extension → Purpose: Error Log → paste the External Key.

3

Done!

MCBridge automatically detects and writes errors to this DE.

ℹ️

Apenas 1 DE de Log de Erros é permitida por BU. Tentativas de cadastrar uma segunda serão bloqueadas.

Only 1 Error Log DE is allowed per BU. Attempts to register a second one will be blocked.

GET /v1/admin/client/logs

Consulta os logs de erro das suas integrações. Retorna apenas os erros das BUs associadas à sua API Key.

Queries error logs from your integrations. Returns only errors from BUs associated with your API Key.

GET /v1/admin/client/logs

Requer header X-API-Key

Requires X-API-Key header

Parâmetros (opcionais)

Parameters (optional)

Parâmetro Tipo / Type Descrição Description Exemplo
fromdate Data inicialStart date ?from=2026-05-01
todate Data finalEnd date ?to=2026-05-31
status_codeint Filtrar por código HTTPFilter by HTTP code ?status_code=400
limitint Máximo de registros (padrão: 50, máx: 500)Max records (default: 50, max: 500) ?limit=100
curl
# Todos os logs
curl -s "https://api.mcbridge.com.br/v1/admin/client/logs" \
  -H "X-API-Key: SUA_API_KEY"

# Filtrado por status e data
curl -s "https://api.mcbridge.com.br/v1/admin/client/logs?status_code=400&from=2026-05-01&limit=10" \
  -H "X-API-Key: SUA_API_KEY"
json — 200 OK
[
  {
    "log_id": "bf7d4860-8b91-4c9f-882d-b7102214549b",
    "bu_id": "7237374",
    "external_key": "SUA_EXTERNAL_KEY",
    "operation": "upsert",
    "status_code": 400,
    "response": "{ mensagem de erro do SFMC }",
    "created_at": "2026-05-24T16:44:09.420331"
  }
]

Guia do Painel Admin

O Painel Admin é a interface web onde o cliente gerencia tudo do MCBridge: cadastro de clientes (multi-tenant), Business Units do SFMC, External Keys de Data Extensions e Triggered Sends, geração e revogação de API Keys, e consulta de logs operacionais. Acesso restrito por Admin Key.

The Admin Panel is the web interface where you manage everything in MCBridge: client registration (multi-tenant), SFMC Business Units, DE External Keys and Triggered Send Definition Keys, API Key generation and revocation, and operational logs. Access is restricted by Admin Key.

Acesso

Access

URL: https://admin.mcbridge.com.br. Login com a Admin Key fornecida pelo time MCBridge. A chave fica salva no navegador (localStorage) até você clicar em "Sair". Use navegação privada em dispositivos compartilhados.

URL: https://admin.mcbridge.com.br. Sign in with the Admin Key provided by the MCBridge team. The key is stored in the browser (localStorage) until you click "Sair" (Sign out). Use private browsing on shared devices.

Atalhos do header (após login): 📖 Docs abre esta documentação · 📄 Termo de Uso baixa o termo em .docx · + Gerar API Key é atalho para a aba API Keys · Sair encerra a sessão.

Header shortcuts (after sign-in): 📖 Docs opens this documentation · 📄 Termo de Uso downloads terms-of-use (.docx) · + Gerar API Key jumps to the API Keys tab · Sair signs out.

1. Aba Clientes

1. Clients Tab

Raiz da hierarquia. Cada cliente pode ter várias Business Units (BUs) e Keys. Em um setup multi-tenant, cada cliente é uma empresa cliente final do MCBridge.

Top of the hierarchy. Each client may have multiple Business Units (BUs) and Keys. In a multi-tenant setup, each client is an end-customer organization.

Cadastrar novo: clique em "+ Novo Cliente", informe Nome da empresa (ex.: "Banco ABC", "Edenred", "Sky") e salve. Deletar: botão "Deletar" na linha. Atenção: deletar um cliente apaga em cascata suas BUs, Keys e API Keys.

Add new: click "+ Novo Cliente", enter Nome da empresa (e.g., "Banco ABC", "Edenred", "Sky") and save. Delete: "Deletar" button on the row. Warning: deleting a client cascades — its BUs, Keys, and API Keys are removed too.

2. Aba BUs (Business Units)

2. BUs Tab (Business Units)

Cada BU representa uma Business Unit do SFMC do cliente. É aqui que ficam as credenciais OAuth do Installed Package.

Each BU represents an SFMC Business Unit of the client. Stores the OAuth credentials of the Installed Package.

Campos: Cliente (dropdown) · Nome da BU (ex.: "BU Brasil", "BU RH") · BU ID (MID) (ex.: 7237374) · REST Subdomain e Auth Subdomain (do tenant SFMC; geralmente iguais, formato mcXXX-...) · Client ID e Client Secret (do Installed Package criado no Setup do SFMC) · External Key da DE de Log de Erros (opcional — DE no SFMC onde o MCBridge espelha os erros).

Fields: Cliente (dropdown) · Nome da BU (e.g., "BU Brazil", "BU HR") · BU ID (MID) (e.g., 7237374) · REST Subdomain and Auth Subdomain (from the SFMC tenant; usually identical, format mcXXX-...) · Client ID and Client Secret (from the Installed Package created in SFMC Setup) · External Key of Error Log DE (optional — DE in SFMC where MCBridge mirrors errors).

Onde encontrar no SFMC: Setup → Apps → Installed Packages → seu pacote → API Integration. Os subdomínios aparecem nas URLs de Authentication Base URI e REST Base URI.

Where to find in SFMC: Setup → Apps → Installed Packages → your package → API Integration. Subdomains appear in the Authentication Base URI and REST Base URI.

Editar / Deletar: botões na linha. Edição preserva o histórico.

Edit / Delete: buttons on the row. Editing preserves history.

3. Aba Keys (DEs e Triggered Sends)

3. Keys Tab (DEs and Triggered Sends)

Aqui você cadastra cada External Key de Data Extension e cada Definition Key de Triggered Send que será usada na API. O MCBridge resolve essas chaves para a BU correta automaticamente.

Register each External Key of a Data Extension and each Definition Key of a Triggered Send that will be used by the API. MCBridge resolves these keys to the right BU automatically.

Campos: Business Unit · Tipo (Data Extension ou Triggered Send) · Finalidade (audience, error_log, etc.) · Label (nome amigável, ex.: "DE Clientes VIP") · External Key / Definition Key (cole o valor do SFMC).

Fields: Business Unit · Type (Data Extension or Triggered Send) · Purpose (audience, error_log, etc.) · Label (friendly name, e.g., "VIP Clients DE") · External Key / Definition Key (paste the value from SFMC).

A tabela mostra o badge DE ou TS ao lado de cada key. Keys com finalidade "error_log" recebem badge adicional LOG.

The table shows a DE or TS badge next to each key. Keys with "error_log" purpose get an extra LOG badge.

4. Aba API Keys

4. API Keys Tab

API Keys são as credenciais que seus sistemas usam para chamar o MCBridge (header X-API-Key). Cada key pode ser associada a um cliente específico.

API Keys are the credentials your systems use to call MCBridge (X-API-Key header). Each key can be tied to a specific client.

Gerar nova key: clique em "+ Gerar Nova Key". A key completa é exibida uma única vez, com botão "Copiar". Guarde em cofre de senhas. Após fechar essa tela, só o prefixo (primeiros caracteres) fica visível.

Generate new key: click "+ Gerar Nova Key". The full key is shown only once, with a "Copy" button. Store it in a password vault. After closing the screen, only the prefix (first characters) remains visible.

Revogar: botão "Revogar" desativa a key sem apagá-la (auditoria preservada). Deletar: remove permanentemente. Recomendação: revogue antes de deletar.

Revoke: "Revogar" button disables the key without deleting it (audit preserved). Delete: permanently removes. Recommendation: revoke before deleting.

Cada linha exibe: nome (label), status (Ativa / Revogada), cliente associado, data de criação e prefixo da key.

Each row shows: name (label), status (Active / Revoked), associated client, creation date, and key prefix.

5. Aba Logs

5. Logs Tab

Histórico de operações da API: chamadas com sucesso e erros do SFMC. Mesmo conteúdo do endpoint GET /v1/admin/logs, com filtros visuais.

History of API operations: successful calls and SFMC errors. Same content as the GET /v1/admin/logs endpoint, with visual filters.

Filtros: dropdown Todos / ✅ Sucesso / ❌ Erro. Botão ↻ Atualizar recarrega.

Filters: dropdown All / ✅ Success / ❌ Error. ↻ Refresh button reloads.

Limpeza: botão Limpar logs antigos (+90 dias) remove permanentemente entradas com mais de 90 dias. Use para manter o banco enxuto.

Cleanup: Limpar logs antigos (+90 dias) permanently removes entries older than 90 days. Use to keep the database lean.

Colunas: Data · BU · Key · Operação (upsert, validation, dry_run_validation, etc.) · Status (HTTP + ✅/❌) · Tentativas (retry count) · Registros (qtd processada) · Response (resumo).

Columns: Date · BU · Key · Operation (upsert, validation, dry_run_validation, etc.) · Status (HTTP + ✅/❌) · Attempts (retry count) · Records (processed count) · Response (summary).

Boas práticas

Best practices

• Use Labels descritivas em Keys e API Keys — facilita auditoria. • Revogue API Keys quando colaboradores saem ou trocam de função. • Cadastre uma DE de Log de Erros em cada BU para ver os erros direto no SFMC. • Limpe logs antigos periodicamente. • Não compartilhe a Admin Key — ela tem acesso total ao painel.

• Use descriptive Labels on Keys and API Keys — eases audit. • Revoke API Keys when staff leaves or changes role. • Register an Error Log DE per BU to inspect errors directly in SFMC. • Clean old logs periodically. • Don't share the Admin Key — it grants full panel access.

Códigos de Erro

Error Codes

HTTP Status Descrição Description Causa comum Common cause
200 Sucesso Success Operação executada com sucesso Operation executed successfully
401 Não autorizado Unauthorized API Key ausente, inválida ou revogada Missing, invalid or revoked API Key
403 IP não autorizado Forbidden IP de origem fora da whitelist da API Key (quando há whitelist cadastrada) Source IP outside the API Key whitelist (when a whitelist is registered)
404 Key não encontrada Key not found External Key não cadastrada no MCBridge External Key not registered in MCBridge
400 Validacao de schema Schema validation Payload invalido (campo inexistente, PK/obrigatorio ausente, tipo errado) - veja detail.details. Nao chama o SFMC. Invalid payload (unknown field, missing PK/required, wrong type) - see detail.details. Does not call SFMC.
400 Tipo incorreto Wrong type Chamou /v1/de/upsert com uma key de Triggered Send Called /v1/de/upsert with a Triggered Send key
500 Erro do SFMC SFMC error SFMC retornou erro — verifique os logs SFMC returned an error — check the logs
429 Limite excedido Too Many Requests Limite de requisições por minuto da API Key excedido — veja o header Retry-After. Nao chama o SFMC. API Key per-minute request limit exceeded — see the Retry-After header. Does not call SFMC.

Erros do SFMC são logados automaticamente — acesse a aba Logs no painel admin para ver detalhes.

SFMC errors are logged automatically — access the Logs tab in the admin panel for details.