# API do Preflow > Integre o sistema da sua empresa ao Preflow — WhatsApp, leads, contas, cadências, reuniões e webhooks. Com a API você manda WhatsApp pelas linhas que já estão no Preflow, cria leads, inscreve leads em cadências e recebe avisos do que acontece: mensagem recebida, entregue ou lida, lead qualificado, conta que mudou de etapa, reunião marcada. ## API ou webhook? - **API: o seu sistema pergunta ou manda.** Enviar WhatsApp, subir arquivo, criar lead, inscrever ou parar cadência, consultar. - **Webhook: o Preflow avisa.** Mensagem recebida, entregue, lida ou com falha; template aprovado; lead criado ou perdido; conta mudou de etapa; reunião marcada. - Todo aviso traz os ids para buscar o recurso completo pela API. Você nunca precisa ficar consultando para saber se algo mudou. ## Comece por aqui - [Primeiros passos](https://developers.preflow.sale/pt/quickstart/): Crie a chave e faça a primeira chamada em 5 minutos. - [WhatsApp](https://developers.preflow.sale/pt/guides/whatsapp/): Texto, template aprovado e mídia, com status de entrega. - [Leads, contas e cadências](https://developers.preflow.sale/pt/guides/leads/): Crie leads, sincronize e inscreva em cadências. - [Webhooks](https://developers.preflow.sale/pt/guides/webhooks/): Receba avisos assinados e confira a assinatura. ## O que está disponível | Módulo | Situação | |---|---| | Conta (`/v1/me`, `/v1/openapi.json`) | Disponível | | WhatsApp: linhas, templates, janela de 24 h, envio, status, histórico, mídia | Disponível | | Webhooks: cadastro, assinatura, entregas; eventos de WhatsApp, leads, contas e reuniões | Disponível | | Leads, contas e funis, cadências, reuniões | Disponível | | Conversões inbound do seu site ou app | Disponível | Tudo o que está nesta documentação já funciona. As novidades ficam em [Mudanças](https://developers.preflow.sale/pt/changelog/). ## Para assistentes de IA - [`/llms.txt`](https://developers.preflow.sale/llms.txt): índice desta documentação para modelos de linguagem. - [`/llms-full.txt`](https://developers.preflow.sale/llms-full.txt): toda a documentação em um arquivo Markdown. - [`/openapi.json`](https://developers.preflow.sale/openapi.json): a especificação OpenAPI 3.1. - Em cada página, **Copiar como Markdown** copia a página para colar no seu assistente. --- # Primeiros passos em 5 minutos > Crie uma chave de API no Preflow e faça a primeira chamada com GET /v1/me. Você precisa ser **administrador ou dono do workspace** e estar num plano pago (ou ser cliente financiado pela agência). 1. **Crie a chave.** No Preflow, abra **Configurações → Integrações → API e webhooks**, clique em criar chave, dê um nome (por exemplo `ERP`) e marque os acessos de que a integração precisa. Para este teste nenhum acesso é necessário. 2. **Guarde a chave.** Ela aparece **uma vez só**. Copie e guarde no cofre de segredos do servidor que vai chamar a API. No terminal, para o teste: ```bash export PREFLOW_API_KEY="pf_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` 3. **Faça a primeira chamada.** `GET /v1/me` diz de qual workspace é a chave, quais acessos ela tem e o limite de pedidos: ```bash curl https://api.preflow.sale/v1/me -H "Authorization: Bearer $PREFLOW_API_KEY" ``` ```json { "api_version": "v1", "workspace": { "id": "6c1f…", "name": "Minha Empresa" }, "api_key": { "id": "0b9e…", "name": "ERP", "environment": "live", "scopes": [] }, "limits": { "requests_per_minute": 600 } } ``` 4. **Escolha o próximo passo.** Marque na chave os acessos do que você vai fazer e siga o guia: [WhatsApp](https://developers.preflow.sale/pt/guides/whatsapp/), [Leads, contas e cadências](https://developers.preflow.sale/pt/guides/leads/) ou [Webhooks](https://developers.preflow.sale/pt/guides/webhooks/). > **Atenção:** A chave é de servidor para servidor. Nunca coloque a chave no site, no app do celular ou em qualquer código que rode na máquina do seu cliente. ## Deu erro? | Resposta | O que fazer | |---|---| | `401 authentication_required` | Faltou o cabeçalho `Authorization: Bearer …` | | `401 invalid_api_key` | Confira se copiou a chave inteira e se o ambiente é o certo ([Ambientes](https://developers.preflow.sale/pt/concepts/environments/)) | | `403 plan_upgrade_required` | O plano do workspace não tem API; ao assinar, a mesma chave volta a funcionar | Todos os códigos estão em [Erros](https://developers.preflow.sale/pt/concepts/errors/). --- # WhatsApp > Mande WhatsApp pelas linhas do workspace: texto, template aprovado e mídia, com status de entrega e histórico. Mande WhatsApp pelas linhas que o seu workspace já tem no Preflow: avisos de pedido, boletos, lembretes, confirmações. Antes, veja [Autenticação e acessos](https://developers.preflow.sale/pt/concepts/authentication/), [Idempotência](https://developers.preflow.sale/pt/concepts/idempotency/) e [Erros](https://developers.preflow.sale/pt/concepts/errors/). Acessos: `whatsapp:read` para consultar e `whatsapp:send` para enviar e subir arquivo. ## 1. Escolha a linha ```bash curl https://api.preflow.sale/v1/whatsapp/senders -H "Authorization: Bearer $PREFLOW_API_KEY" ``` ```json { "data": [ { "id": "8c5d…", "kind": "person", "phone": "+5511988887777", "owner": { "id": "1f2e…", "name": "Ana Souza" }, "is_default": true, "status": "online" }, { "id": "b71a…", "kind": "ai_agent", "phone": "+5511977776666", "owner": { "id": "b71a…", "name": "Clara" }, "is_default": false, "status": "online" } ] } ``` - `person`: o número de uma pessoa ativa do workspace. `ai_agent`: o número próprio de um agente de IA. - Use o `id` em `from`. Sem `from`, vale a **linha padrão da chave**, que o administrador escolhe em Configurações → Integrações → API e webhooks. - O WhatsApp Business do celular de uma pessoa é o telefone pessoal dela e não aparece aqui: a API só usa números da empresa e dos agentes de IA. - As respostas do contato chegam nessa mesma linha. ## 2. A janela de 24 h O WhatsApp só aceita texto livre e mídia até 24 h depois da última mensagem do contato **para aquela linha**. Fora disso, só **template aprovado**. ```bash curl "https://api.preflow.sale/v1/whatsapp/window?to=%2B5511999998888&from=8c5d…" \ -H "Authorization: Bearer $PREFLOW_API_KEY" ``` ```json { "to": "+5511999998888", "from": { "id": "8c5d…", "phone": "+5511988887777" }, "open": false, "last_inbound_at": null, "expires_at": null } ``` Mandar texto com a janela fechada responde `422 whatsapp_window_closed`, sem custo. A API recusa antes de chamar o WhatsApp. ## 3. Templates ```bash curl https://api.preflow.sale/v1/whatsapp/templates -H "Authorization: Bearer $PREFLOW_API_KEY" ``` ```json { "data": [ { "id": "c0a1…", "name": "pedido_enviado", "display_name": "Pedido enviado", "language": "pt_BR", "category": "utility", "status": "approved", "body": "Oi {{nome}}, o pedido {{pedido}} saiu para entrega.", "variables": ["nome", "pedido"], "header": null } ] } ``` Por padrão a lista traz só os aprovados para o provedor do workspace (`?status=all` traz todos). Templates são criados e aprovados na tela do Preflow. ## 4. Mandar Informe o destino (`to` em E.164 ou `lead_id`) e **um** conteúdo: `text`, `template` ou `media`. `Idempotency-Key` é obrigatório. Com `lead_id` e `to` juntos, `to` tem que ser um telefone desse lead. **Texto** (janela aberta): ```bash curl -X POST https://api.preflow.sale/v1/whatsapp/messages \ -H "Authorization: Bearer $PREFLOW_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: pedido-1234-saiu" \ -d '{"to":"+5511999998888","from":"8c5d…","text":"Seu pedido 1234 saiu para entrega.","client_reference":"pedido-1234"}' ``` **Template** (qualquer momento). As variáveis vão pelo nome ou pela posição (`"1"`, `"2"`…), e todas são obrigatórias: ```json { "lead_id": "3f0c…", "template": { "name": "pedido_enviado", "language": "pt_BR", "variables": { "nome": "Ana", "pedido": "1234" } } } ``` **Mídia**: primeiro suba o arquivo (seção 5), depois: ```json { "to": "+5511999998888", "media": { "file_id": "7d1e…", "caption": "Segue o boleto." } } ``` Resposta `201`: ```json { "id": "e4b2…", "to": "+5511999998888", "from": { "id": "8c5d…", "kind": "person", "phone": "+5511988887777" }, "lead_id": null, "contact_id": "a9d3…", "conversation_id": "0f6e…", "type": "text", "template": null, "client_reference": "pedido-1234", "status": "sent", "error": null, "message_id": "5c7b…", "created_at": "2026-11-16T15:04:05Z", "updated_at": "2026-11-16T15:04:06Z" } ``` O que acontece no Preflow: - **Número que ainda não é lead vira contato** (não lead). Telefone de um lead vai para o lead. Use `contact_name` para nomear o contato novo. - A mensagem aparece na conversa e na linha do tempo com o rótulo "Integração". - **Não tira a conversa de quem conduz.** Se a IA conduzia o lead, ela continua conduzindo; se o contato responder, segue o atendimento de sempre. - **Não conta como toque** nos painéis do time (Sala de Guerra, esforço por canal, metas). - Passa pelas mesmas regras de qualquer envio do Preflow: quem pediu para não receber mensagens (`privacy_suppressed`), contato pausado até uma data (`contact_paused`), contato encerrado ou perdido (`contact_blocked`), plano e créditos (`insufficient_credits`), linha pausada por qualidade (`sender_unavailable`). ### Status e incerteza `GET /v1/whatsapp/messages/{id}` devolve o status da entrega: `sent`, `delivered`, `read` ou `failed`. Se o WhatsApp não confirmar a tempo, o envio responde `202` com `"status": "unknown"` e **nada é reenviado**, nem repetindo a mesma `Idempotency-Key` (que passa a responder `409 request_outcome_unknown`). Consulte `GET /v1/whatsapp/messages/{id}`: quando a mensagem tiver saído, o status passa para `sent` e depois `delivered`/`read`. Não mande de novo com outra chave antes de conferir, ou o contato recebe duas vezes. ## 5. Arquivos ```bash curl -X POST https://api.preflow.sale/v1/files \ -H "Authorization: Bearer $PREFLOW_API_KEY" -H "Content-Type: application/json" \ -H "Idempotency-Key: boleto-1234" \ -d '{"filename":"boleto-1234.pdf","content_type":"application/pdf","size":48211}' ``` ```json { "id": "7d1e…", "filename": "boleto-1234.pdf", "content_type": "application/pdf", "size": 48211, "upload": { "method": "PUT", "url": "https://api.preflow.sale/storage/v1/object/upload/sign/…", "headers": { "content-type": "application/pdf" }, "expires_at": "2026-11-16T17:04:05Z" } } ``` Envie os bytes para `upload.url` com `PUT` e os cabeçalhos indicados, dentro de 2 h. Depois use o `id` em `media.file_id`. O arquivo enviado tem que ter o tamanho (`size`) e o tipo (`content_type`) declarados, ou o envio responde `file_not_uploaded` / `media_type_not_allowed`. Limite de 60 arquivos por minuto e 1.000 por dia por chave; o arquivo é apagado 30 dias depois do upload. Tipos aceitos: imagens JPEG, PNG e WebP; PDF; áudio OGG, MP3, M4A e AAC; vídeo MP4 e 3GP; texto; Word, Excel e PowerPoint. Até 16 MB. ## 6. Histórico e mídia recebida ```bash curl "https://api.preflow.sale/v1/whatsapp/messages?to=%2B5511999998888&limit=50" \ -H "Authorization: Bearer $PREFLOW_API_KEY" ``` Traz todas as mensagens com o telefone, recebidas e enviadas, da mais nova para a mais antiga. `origin` diz quem mandou: `api`, `cadence`, `ai`, `human` ou `whatsapp_app` (pelo app do celular). Mensagens da API trazem `api_message_id` e `client_reference`. Para baixar a mídia de uma mensagem: `GET /v1/whatsapp/messages/{id}/media`. A resposta é o arquivo, com o `Content-Type` original e `Content-Disposition: attachment`. Trate como arquivo enviado por terceiros. ## Limites e custo - 60 envios por minuto por chave, e 60 por minuto por linha (somando todas as chaves do workspace). - O custo é a tabela de WhatsApp do Preflow (a mesma da tela). Recusa do WhatsApp devolve o crédito. - Mensagens em massa para listas frias prejudicam a qualidade da linha e podem pausar o número. Para prospecção, use as cadências do Preflow. --- # Leads, contas e cadências > Crie leads, busque e sincronize, leia contas e funis, inscreva em cadências e consulte reuniões. Guia das rotas de CRM da API pública. Convenções gerais em [Autenticação](https://developers.preflow.sale/pt/concepts/authentication/), [Idempotência](https://developers.preflow.sale/pt/concepts/idempotency/), [Paginação](https://developers.preflow.sale/pt/concepts/pagination/) e [Erros](https://developers.preflow.sale/pt/concepts/errors/). | Rota | Acesso | Para quê | |---|---|---| | `POST /v1/inbound-submissions` | `leads:write` | Uma pessoa pediu contato no seu site, app ou sistema ([guia](https://developers.preflow.sale/pt/guides/website-leads/)) | | `GET /v1/inbound-submissions/{id}` | `leads:read` | Ler uma conversão | | `POST /v1/leads` | `leads:write` | Mandar um lead novo do seu sistema | | `GET /v1/leads`, `GET /v1/leads/{id}` | `leads:read` | Buscar por e-mail, telefone ou `external_id`, ou sincronizar | | `GET /v1/leads/{id}/activities` | `leads:read` | Linha do tempo do lead | | `GET /v1/accounts`, `GET /v1/accounts/{id}` | `accounts:read` | Etapa por funil, donos, qualificação, Cliente/Churn | | `GET /v1/funnels` | `accounts:read` | Funis e etapas | | `GET /v1/cadences` | `cadences:read` | Cadências que podem receber leads | | `POST /v1/leads/{id}/cadence-enrollments` | `cadences:write` | Inscrever o lead numa cadência | | `POST /v1/leads/{id}/cadence-stop` | `cadences:write` | Parar a cadência do lead | | `GET /v1/meetings`, `GET /v1/meetings/{id}` | `meetings:read` | Reuniões marcadas | ## Criar lead O lead entra como **inbound**: a configuração de Inbound do workspace decide a cadência, quem atende e quem é avisado, como num formulário do site. ```bash curl https://api.preflow.sale/v1/leads \ -H "Authorization: Bearer $PREFLOW_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"name":"Ana Souza","phone":"+5511999998888","email":"ana@empresa.com.br","company":"Empresa","external_id":"erp-12345"}' ``` ```json { "lead_id": "9b2c…", "lead": { "id": "9b2c…", "object": "lead", "name": "Ana Souza", "status": "new", "origin": "inbound", "external_ids": ["erp-12345"], "…": "…" }, "created": true, "matched_by": null, "inbound_cadence": { "started": true, "reason": "distribution", "cadence_id": "4f1e…" } } ``` - Informe `email` ou `phone` (E.164, `+5511999998888`). Lead só com telefone é aceito. - **O lead já existe?** Se o e-mail ou o telefone já é de um lead do workspace, a resposta é `200` com `created: false` e esse lead, sem alterar nada nele. Lead que já está sendo trabalhado (em cadência, perdido, ganho ou que entrou por prospecção) nunca é reaberto, e `inbound_cadence` vem `null`. - A foto do lead (`lead`) só vem para chave que também tem `leads:read`. Uma chave só de escrita (um formulário, por exemplo) recebe só `lead_id`. - Limite próprio: 60 leads por minuto por chave. - **`external_id`** é o id do lead no seu sistema, único no workspace. Mandar o mesmo `external_id` de novo devolve o mesmo lead, sem alterar nada (`matched_by: "external_id"`). Dois pedidos ao mesmo tempo com o mesmo `external_id` nunca criam dois leads: o segundo recebe `409 external_id_in_progress` e, tentando de novo, o lead do primeiro. Busque por ele com `GET /v1/leads?external_id=erp-12345`. - Contato que pediu para não ser contatado responde `422 lead_suppressed`. - `source` é um rótulo livre do seu sistema (ex.: `erp`), guardado na entrada. ## Buscar e sincronizar ```bash # por e-mail, telefone ou id do seu sistema curl "https://api.preflow.sale/v1/leads?email=ana@empresa.com.br" -H "Authorization: Bearer $PREFLOW_API_KEY" # sincronizar: tudo que mudou desde a última vez, página a página curl "https://api.preflow.sale/v1/leads?updated_since=2026-11-16T00:00:00Z&limit=100" -H "Authorization: Bearer $PREFLOW_API_KEY" ``` A lista vem em ordem de atualização (a mais antiga primeiro). Guarde o `updated_at` do último item e use como `updated_since` na próxima rodada; o `next_cursor` leva à página seguinte da mesma rodada. Contas funcionam igual (`GET /v1/accounts?updated_since=`). Para saber de mudança sem consultar, use os webhooks (seção [Eventos](https://developers.preflow.sale/pt/events/#leads-contas-e-reuniões) abaixo). ## Linha do tempo `GET /v1/leads/{id}/activities` traz, do mais recente para o mais antigo, os toques e marcos do lead com um tipo público estável: | Tipo | O que é | |---|---| | `email.sent`, `email.received` | E-mail enviado ou recebido | | `whatsapp.sent`, `whatsapp.received` | WhatsApp enviado ou recebido | | `call.made`, `call.received` | Ligação feita ou recebida (`call.connection_status`) | | `linkedin.invitation_sent`, `linkedin.invitation_accepted`, `linkedin.sent`, `linkedin.received` | LinkedIn | | `meeting.scheduled`, `meeting.confirmed`, `meeting.completed` | Reunião | | `lead.lost`, `lead.reactivated`, `lead.status_changed` | Mudança de situação do lead | | `lead.received_from_api` | O lead chegou pela API | | `note` | Anotação | `actor.type` diz quem agiu: `human`, `ai`, `lead`, `integration` ou `system`. Registros internos do Preflow não aparecem. ## Contas e funis A conta é a dona do lead. `GET /v1/accounts/{id}` traz: - `funnels`: uma entrada por funil, com a etapa fixa (`new`, `qualified`, `scheduled`, `completed`, `no_show`, `negotiation`, `won`, `lost`) e a etapa intermediária criada pelo workspace, quando houver. - `owners.pre_sales` e `owners.sales`: quem cuida da conta antes e depois da reunião. - `qualification`, `is_customer` (Cliente) e `is_churn` (Churn). Conta Churn sai do quadro (`on_board: false` em todos os funis); conta Cliente só fica em Vendas. `GET /v1/funnels` lista os funis, as etapas fixas com o nome que aparece no Preflow e as etapas intermediárias de cada uma. ## Cadências ```bash curl https://api.preflow.sale/v1/leads/9b2c…/cadence-enrollments \ -H "Authorization: Bearer $PREFLOW_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"cadence_id":"4f1e…"}' ``` - A inscrição é a mesma da tela, com as mesmas recusas: lead já na cadência, pausa de engajamento, lead que passou por reunião, cooldown de perdido, cadência que nasceria toda cancelada. Cada uma tem um código em [Erros](https://developers.preflow.sale/pt/concepts/errors/#catálogo). - Quem executa as etapas é o dono de pré-vendas da conta do lead. Na linha do tempo a inscrição aparece como feita pela integração, com a chave, e não conta como toque. A chave só inscreve enquanto quem a criou continua administrador ou dono do workspace. - `POST /v1/leads/{id}/cadence-stop` para a cadência **deste lead**: as outras pessoas da mesma conta seguem nas cadências delas, e conversa em andamento e follow-up marcado à mão continuam. O que estava na fila de envio é cancelado; o que o provedor já recebeu não volta. Sem cadência aberta, responde `stopped: false`. ## Reuniões ```bash curl "https://api.preflow.sale/v1/meetings?from=2026-11-01T00:00:00Z&to=2026-12-01T00:00:00Z&status=scheduled" \ -H "Authorization: Bearer $PREFLOW_API_KEY" ``` - `status`: `scheduled`, `confirmed`, `tentative`, `rescheduled`, `completed`, `no_show` ou `cancelled`. - Bloqueios copiados da agenda do Outlook ou do Google não são reuniões e nunca aparecem. - `closer` é quem conduz a reunião; `scheduled_by`, quem marcou. ## Eventos Para saber de mudança sem consultar, assine os eventos `lead.*`, `account.*` e `meeting.*` por [webhook](https://developers.preflow.sale/pt/guides/webhooks/). O formato de cada um está em [Eventos](https://developers.preflow.sale/pt/events/#leads-contas-e-reuniões). --- # Webhooks > Receba avisos assinados do Preflow: cadastro, conferência da assinatura (Node.js, Python, PHP), entrega e novas tentativas. O Preflow avisa o seu sistema quando algo acontece: mensagem de WhatsApp recebida, enviada, entregue, lida ou com falha; template aprovado ou recusado. Você cadastra uma URL `https://` (o **endpoint**), escolhe os eventos e o Preflow faz um `POST` assinado para ela a cada evento. - Cadastro pela tela (**Configurações → Integrações → API e webhooks**) ou pela API (acesso `webhooks:manage`). Até **10 endpoints** por workspace. - Cada aviso leva o recurso (texto da mensagem, telefone, lead). Pela API, a chave só assina ou lê (`GET /v1/events/{id}`) um tipo com o acesso de leitura do módulo dele: `whatsapp.*` → `whatsapp:read`, `lead.*` → `leads:read`, `account.*` → `accounts:read`, `meeting.*` → `meetings:read`. Mudar a URL ou os eventos, ou religar, também exige esses acessos. Se a chave que criou o endpoint perder um deles, as entregas desse tipo são canceladas (`last_error: event_scope_missing`). - Cada aviso traz os ids para buscar o recurso completo pela API. - Formato de cada evento: [Eventos](https://developers.preflow.sale/pt/events/). Rotas: [Referência da API](https://developers.preflow.sale/pt/referencia/). ## Cadastro ```http POST /v1/webhook-endpoints Authorization: Bearer pf_live_… Idempotency-Key: 5f0c1d2e-3a4b-4c5d-8e6f-7a8b9c0d1e2f Content-Type: application/json { "url": "https://erp.suaempresa.com.br/webhooks/preflow", "events": ["whatsapp.message.received", "whatsapp.message.status_updated"] } ``` Resposta `201`: ```json { "id": "3f1d2c4b-5a6e-4f70-8a9b-0c1d2e3f4a5b", "url": "https://erp.suaempresa.com.br/webhooks/preflow", "status": "active", "events": ["whatsapp.message.received", "whatsapp.message.status_updated"], "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSwfQmfVNQhnkZ=" } ``` O `secret` aparece **uma vez só** na API. Guarde no cofre de segredos do servidor que recebe os webhooks. Repetir o pedido com a mesma `Idempotency-Key` devolve o endpoint com `secret: null` e `secret_redacted: true`; perdeu o segredo, gire-o. Na tela, um administrador pode ver o segredo de novo ("Ver segredo"); cada consulta fica registrada. A URL precisa ser `https://`, sem usuário e senha. Endereço interno, privado, de loopback, link-local, de metadados de nuvem ou do próprio Preflow é recusado (`webhook_url_not_allowed`), no cadastro e de novo **a cada entrega** (o DNS é resolvido toda vez e todos os endereços precisam ser públicos). | Rota | O que faz | |---|---| | `GET /v1/event-types` | Eventos que um endpoint pode assinar | | `GET /v1/webhook-endpoints` | Endpoints do workspace (sem o segredo) | | `POST /v1/webhook-endpoints` | Cadastra (devolve o segredo) | | `GET /v1/webhook-endpoints/{id}` | Um endpoint | | `PATCH /v1/webhook-endpoints/{id}` | Muda `url`, `events`, `description` ou `status` (`active`/`disabled`) | | `DELETE /v1/webhook-endpoints/{id}` | Exclui (segredo e log de entregas juntos) | | `POST /v1/webhook-endpoints/{id}/rotate-secret` | Segredo novo; o anterior vale mais 24 h | | `POST /v1/webhook-endpoints/{id}/test` | Manda um evento `webhook.test` | | `GET /v1/webhook-endpoints/{id}/deliveries` | Log de entregas (30 dias): status, código HTTP e tempo | | `POST /v1/webhook-deliveries/{id}/retry` | Reenvia uma entrega agora (não a que já deu certo; até 10 por minuto por endpoint) | | `GET /v1/events/{id}` | Um evento dos últimos 30 dias, com as entregas | ## O que chega Todo webhook é um `POST` com `Content-Type: application/json` e este envelope: ```json { "id": "evt_9b2f0c1d4e5a46b7a8c9d0e1f2a3b4c5", "type": "whatsapp.message.received", "created_at": "2026-11-16T15:04:05.123Z", "workspace_id": "6e0b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d", "data": { } } ``` Cabeçalhos (padrão [Standard Webhooks](https://www.standardwebhooks.com)): | Cabeçalho | Valor | |---|---| | `webhook-id` | O `id` do evento. É o **mesmo** em todas as tentativas: use para deduplicar. | | `webhook-timestamp` | Segundos Unix desta tentativa. | | `webhook-signature` | `v1,`; durante 24 h depois de girar o segredo, duas, separadas por espaço. | Os eventos e o `data` de cada um estão em [Eventos](https://developers.preflow.sale/pt/events/). ## Conferir a assinatura 1. Leia o corpo **cru** (os bytes como chegaram; não reformate o JSON). 2. Monte `"{webhook-id}.{webhook-timestamp}.{corpo}"`. 3. A chave é o segredo **sem** o prefixo `whsec_`, decodificado de base64. 4. Calcule HMAC-SHA256, codifique em base64 e compare (em tempo constante) com cada valor `v1,…` do cabeçalho `webhook-signature`. Basta um bater. 5. Recuse `webhook-timestamp` com mais de 5 minutos de diferença do seu relógio. ### Node.js ```js const secret = process.env.PREFLOW_WEBHOOK_SECRET; // whsec_… const app = express(); app.post('/webhooks/preflow', express.raw({ type: 'application/json' }), (req, res) => { const id = req.header('webhook-id'); const timestamp = req.header('webhook-timestamp'); const signatures = (req.header('webhook-signature') ?? '').split(' '); if (!id || !timestamp || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return res.sendStatus(400); const key = Buffer.from(secret.slice('whsec_'.length), 'base64'); const expected = crypto.createHmac('sha256', key).update(`${id}.${timestamp}.${req.body}`).digest(); const valid = signatures.some((entry) => { const [version, value] = entry.split(','); const given = Buffer.from(value ?? '', 'base64'); return version === 'v1' && given.length === expected.length && crypto.timingSafeEqual(given, expected); }); if (!valid) return res.sendStatus(401); const event = JSON.parse(req.body); // Deduplique por event.id e responda rápido; processe em segundo plano. res.sendStatus(204); }); ``` ### Python ```python from flask import Flask, request, abort SECRET = os.environ["PREFLOW_WEBHOOK_SECRET"] # whsec_… app = Flask(__name__) @app.post("/webhooks/preflow") def preflow_webhook(): msg_id = request.headers.get("webhook-id", "") timestamp = request.headers.get("webhook-timestamp", "") signatures = request.headers.get("webhook-signature", "").split(" ") body = request.get_data() # bytes, sem reformatar if not msg_id or not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300: abort(400) key = base64.b64decode(SECRET.removeprefix("whsec_")) digest = hmac.new(key, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256).digest() expected = base64.b64encode(digest).decode() if not any( part.startswith("v1,") and hmac.compare_digest(part[3:], expected) for part in signatures ): abort(401) event = json.loads(body) # Deduplique por event["id"] e responda rápido. return "", 204 ``` ### PHP ```php 300) { http_response_code(400); exit; } $key = base64_decode(substr($secret, strlen('whsec_'))); $expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$body}", $key, true)); $valid = false; foreach ($signatures as $part) { [$version, $value] = array_pad(explode(',', $part, 2), 2, ''); if ($version === 'v1' && hash_equals($expected, $value)) { $valid = true; } } if (!$valid) { http_response_code(401); exit; } $event = json_decode($body, true); // Deduplique por $event['id'] e responda rápido. http_response_code(204); ``` As bibliotecas oficiais do Standard Webhooks (Node, Python, PHP, Go, Java, Ruby, C#, Rust) também conferem a assinatura do Preflow. ## Entrega - **Pelo menos uma vez, sem ordem garantida.** O mesmo evento pode chegar mais de uma vez (ex.: a sua resposta se perdeu): deduplique pelo `id`. Para ordenar status de uma mensagem, use `status_at`. - **Sucesso é qualquer 2xx em até 10 s.** 3xx (o Preflow não segue redirecionamento), 4xx, 5xx, erro de rede ou demora é falha. O corpo da sua resposta não é lido nem guardado. - **Novas tentativas** depois de 30 s, 2 min, 10 min, 30 min, 1 h, 3 h, 6 h, 12 h e 24 h (10 tentativas em cerca de 2 dias). Depois disso a entrega fica como `failed`; reenvie pela tela ou por `POST /v1/webhook-deliveries/{id}/retry`. - **No máximo 5 entregas ao mesmo tempo** para cada endpoint; enquanto ele está falhando, uma por vez. As vagas do Preflow são repartidas entre os endpoints: um servidor fora do ar não atrasa os outros. - **Endpoint falhando há 3 dias seguidos** (sem nenhum sucesso no meio e sem intervalo de mais de 25 h entre as falhas) é desligado (`status: "disabled"`, `disabled_reason: "failing"`) e os administradores do workspace recebem um aviso. Corrija e religue com `PATCH … { "status": "active" }`. - **Endpoint desligado não recebe nada**: as entregas pendentes são canceladas e os eventos novos não geram entrega para ele. - **O endpoint é de quem o criou.** Se essa pessoa deixa de administrar o workspace, ou a chave que o criou é revogada, ele é desligado (`disabled_reason: "creator_lost_access"`) e os administradores são avisados. Quem religa passa a responder por ele. - **Plano sem API** (Gratuito): os endpoints ficam `paused_plan` e nada sai. As entregas ficam guardadas por até 30 dias e saem quando o plano volta; depois disso são apagadas junto com o evento e não saem mais. - **Log de 30 dias** em `GET /v1/webhook-endpoints/{id}/deliveries`: status, código HTTP, tempo e as últimas tentativas. Eventos e entregas com mais de 30 dias são apagados. `last_error`: `dns_or_address_refused` (a conexão não chegou a ser estabelecida: o nome não resolveu, resolveu para um endereço interno, privado ou do Preflow, a porta recusou ou não respondeu, ou o TLS falhou; o Preflow não diz qual, para o log não revelar nomes e portas da rede), `timeout` ou `connection_failed` (depois de conectar, a resposta demorou mais de 10 s ou a conexão caiu), `redirect_not_followed`, `http_error`, `invalid_response` ou `event_scope_missing`. ## Girar o segredo `POST /v1/webhook-endpoints/{id}/rotate-secret` devolve o segredo novo. Durante 24 h cada aviso leva as duas assinaturas (a do segredo novo e a do anterior): troque o segredo no seu servidor nesse período e nada se perde. Uma nova rotação nessas 24 h é recusada (`webhook_rotation_in_progress`). ## Testar 1. Cadastre o endpoint e guarde o segredo. 2. "Testar" na tela, ou `POST /v1/webhook-endpoints/{id}/test` (até 5 por minuto por endpoint). 3. Em até ~10 s chega um `webhook.test` assinado. Confira em `GET /v1/webhook-endpoints/{id}/deliveries` (ou em "Entregas" na tela) o status e o código HTTP que o seu servidor respondeu. --- # Receber leads do seu site > Mande para o Preflow as conversões do formulário do seu site, landing ou app com POST /v1/inbound-submissions: MQL, atribuição e cadência de Inbound. Acesso: `leads:write` para registrar e `leads:read` para ler a conversão. Quando uma **pessoa pede contato** (formulário do seu site, landing, app, chat próprio), mande a conversão para `POST /v1/inbound-submissions`. Ela segue o mesmo caminho de um formulário do Preflow: - vira **MQL** e a conta vai para Qualificadas; - as respostas ficam no lead e a origem (UTM, campanha, página) entra na atribuição e nos painéis de marketing; - a configuração de Inbound do workspace decide a cadência, quem atende e quem é avisado, e as regras de roteamento recebem a `campaign` e o `utm_campaign`. ```bash curl https://api.preflow.sale/v1/inbound-submissions \ -H "Authorization: Bearer $PREFLOW_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "submission_id": "site-form-8812", "contact": { "name": "Ana Souza", "email": "ana@empresa.com.br", "phone": "+5511999998888", "company": "Empresa" }, "answers": [ { "key": "tamanho_time", "label": "Quantas pessoas no time comercial?", "value": "11-50" } ], "campaign": "black-friday-2026", "attribution": { "utm_source": "google", "utm_medium": "cpc", "utm_campaign": "black-friday-2026", "landing_url": "https://empresa.com.br/contato" }, "consent": { "granted": true, "text": "Aceito receber contato da Empresa." } }' ``` ```json { "id": "6e0b…", "object": "inbound_submission", "submission_id": "site-form-8812", "status": "completed", "result": "lead_created", "lead_id": "9b2c…", "contact_id": null, "qualified": true, "mql_applied": true, "matched_by": null, "inbound_cadence": { "started": true, "reason": "distribution", "cadence_id": "4f1e…" }, "form_id": null, "occurred_at": "2026-11-18T13:05:00.000Z", "created_at": "2026-11-18T13:05:01.204Z", "completed_at": "2026-11-18T13:05:02.118Z" } ``` ## O que acontece em cada caso | `result` | Quando | O que o Preflow faz | |---|---|---| | `lead_created` (`201`) | Ninguém com esse e-mail, telefone ou LinkedIn | Cria o lead inbound, MQL, e começa a cadência de Inbound | | `lead_updated` | O lead já existia e não está em atendimento | Preenche os dados que faltavam, grava o MQL e começa a cadência | | `lead_unchanged` | O lead está perdido, ganho, arquivado, já em cadência ou foi qualificado por uma pessoa | Só registra a conversão no histórico e na atribuição; nada é reaberto | | `contact_only` | `"qualified": false`, ou o formulário de `form_id` não deu MQL | Guarda só como contato, sem lead, dono ou cadência | - **MQL por padrão.** Toda conversão é MQL de marketing, como um formulário com perguntas. Mande `"qualified": false` para quem ainda não deve ser abordado. - **Usar as regras de um formulário do Preflow.** Com `form_id` (de um formulário publicado em Marketing), as respostas usam os ids dos campos dele, as regras de MQL dele decidem e o funil e a campanha dele valem. - **`funnel_id`** escolhe o funil do lead; **`campaign`** é o slug de uma campanha do Preflow. - **`submission_id`** é o id da conversão no seu sistema. Mandar o mesmo `submission_id` de novo devolve a mesma conversão (`200`), com qualquer `Idempotency-Key`. Se a resposta for `202` (resultado incerto), repita com o mesmo `submission_id`: a conversão é retomada sem duplicar. - **`occurred_at`** é quando a pessoa converteu (até 30 dias atrás). Uma conversão antiga não passa por cima do que uma pessoa decidiu depois dela. - **`attribution.fbc` / `fbp` / `fbclid`**: com a Meta conectada, a conversão também vai para a API de Conversões da Meta. - A chave do formulário pode ter só `leads:write`: a resposta não traz os dados do lead nem `matched_by`. Com `leads:read`, vem também `lead`. - Limite próprio: 120 conversões por minuto por chave. As respostas somam até 64 KB, e texto com caractere de controle (fora tab e quebra de linha) é recusado com `400`. - Contato que pediu para não ser contatado (supressão global, da agência ou do workspace) é recusado com `422 lead_suppressed` antes de qualquer registro. - Ao terminar, sai o webhook `inbound.submission_received` (veja [Eventos](https://developers.preflow.sale/pt/events/#leads-contas-e-reuniões)). ## API de conversão ou `POST /v1/leads`? | Use | Quando | |---|---| | `POST /v1/inbound-submissions` | Uma pessoa pediu contato agora (formulário, landing, app). Conta como entrada do lead, vira MQL e entra na atribuição | | [`POST /v1/leads`](https://developers.preflow.sale/pt/guides/leads/#criar-lead) | Seu sistema tem um cadastro para levar ao Preflow (ERP, CRM, importação). O lead entra sem MQL e o que já existe não muda | ## Do formulário do seu site até a API A chave é secreta: o formulário do site manda os dados para o **seu** servidor, e o servidor chama o Preflow. Exemplo em Node (Express): ```js app.post('/contato', express.json(), async (req, res) => { const response = await fetch('https://api.preflow.sale/v1/inbound-submissions', { method: 'POST', headers: { Authorization: `Bearer ${process.env.PREFLOW_API_KEY}`, 'Idempotency-Key': crypto.randomUUID(), 'Content-Type': 'application/json', }, body: JSON.stringify({ submission_id: req.body.form_submission_id, contact: { name: req.body.name, email: req.body.email, phone: req.body.phone }, answers: [{ key: 'mensagem', label: 'Mensagem', value: req.body.message }], attribution: { utm_source: req.body.utm_source, utm_campaign: req.body.utm_campaign, landing_url: req.get('referer') }, }), }); res.status(response.ok ? 200 : 502).end(); }); ``` Mande `utm_*` só quando houver valor: campo vazio é ignorado, campo desconhecido é recusado (`400`). --- # Autenticação e acessos > Chave secreta por workspace, cabeçalho Authorization e os acessos (escopos) de cada rota. 1. Em **Configurações → Integrações → API e webhooks**, um administrador ou o dono do workspace cria uma chave, dá um nome e marca os acessos. 2. A chave aparece **uma vez só**. Guarde no cofre de segredos do servidor que chama a API. 3. Envie em todo pedido: ```http Authorization: Bearer pf_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` ## Regras da chave - Vale para **um** workspace. Toda chamada age nesse workspace; nada no corpo ou na URL troca isso. - Faz só o que os **acessos** dela permitem (tabela abaixo). - Revogada, para de funcionar na hora. Também cai sozinha quando quem a criou deixa de ser administrador do workspace. - Disponível nos **planos pagos** (e para cliente financiado pela agência). No Gratuito e no Try a chave responde `plan_upgrade_required`; ao assinar, a mesma chave volta a funcionar. - É de servidor para servidor. Nunca coloque a chave no site, no app do celular ou em qualquer código que rode na máquina do seu cliente. Confira a chave com `GET /v1/me` ([Primeiros passos](https://developers.preflow.sale/pt/quickstart/)). ## Acessos (escopos) | Escopo | Permite | |---|---| | `whatsapp:read` | Ler linhas, templates, janela de 24h, mensagens e mídia | | `whatsapp:send` | Enviar WhatsApp e subir arquivos | | `leads:read` | Buscar leads e ler a linha do tempo | | `leads:write` | Criar leads | | `accounts:read` | Ler contas, etapas, donos e funis | | `meetings:read` | Ler reuniões | | `cadences:read` | Listar cadências | | `cadences:write` | Inscrever lead em cadência e parar a cadência dele | | `webhooks:manage` | Cadastrar e gerenciar webhooks | Rota fora dos acessos da chave responde `403 insufficient_scope`, com o escopo que falta em `details.required_scope`, antes de qualquer efeito. Na [Referência da API](https://developers.preflow.sale/pt/referencia/), cada rota mostra o escopo que exige (`x-required-scope`). ## Convenções - JSON em UTF-8. Envie `Content-Type: application/json` nos pedidos com corpo. - Ids são UUID. Datas em ISO-8601, em UTC. Telefones em E.164 (`+5511999998888`). - Toda resposta traz `X-Request-Id`. Informe esse valor ao suporte. - Corpo até 1 MB. --- # Idempotência > Toda escrita exige Idempotency-Key; repetir o mesmo pedido nunca executa duas vezes. Todo `POST`, `PATCH` e `DELETE` exige o cabeçalho `Idempotency-Key`: um valor único por operação, por exemplo um UUID gerado pelo seu sistema. ```http Idempotency-Key: 2f1d9a52-0b6c-4c3e-9d8e-7a1b2c3d4e5f ``` - Repetir o **mesmo pedido** com a mesma chave em até 24 h devolve a mesma resposta, sem executar de novo (cabeçalho `Idempotent-Replayed: true`). Use isso para tentar de novo com segurança depois de um erro de rede. - A mesma chave com **outro corpo** responde `409 idempotency_conflict`. - Enquanto o primeiro pedido ainda executa, responde `409 request_in_progress`. - Recusa passageira (`retryable: true`, como `503`) libera a chave: a repetição executa de novo. - Se o resultado ficou incerto (por exemplo, o provedor não respondeu), a resposta é `202` com `"status": "unknown"` e a repetição com a mesma chave responde `409 request_outcome_unknown`. Nada é executado duas vezes. Consulte o recurso antes de tentar com outra chave. ## Boa prática Gere a chave a partir do que a operação é no seu sistema (por exemplo `pedido-1234-saiu`): assim um reenvio do seu próprio processo nunca manda a mesma mensagem duas vezes. --- # Paginação > Listas paginadas por cursor, com limit e next_cursor. Listas usam cursor: `?limit=` (1 a 100, padrão 50) e `&cursor=` com o `next_cursor` da página anterior. ```json { "data": [ … ], "next_cursor": "eyJ…" } ``` - `next_cursor: null` indica a última página. - Use o cursor como veio, sem alterar. Cursor mexido ou de outra lista responde `400 invalid_cursor`. - Para sincronizar leads e contas, combine `updated_since` com o cursor (veja [Leads, contas e cadências](https://developers.preflow.sale/pt/guides/leads/#buscar-e-sincronizar)). --- # Limites > Limites de pedidos por chave e por linha, cabeçalhos RateLimit e o erro 429. | Limite | Valor | |---|---| | Pedidos por chave | 600 por minuto | | Envios de WhatsApp | 60 por minuto por chave e 60 por minuto por linha | | Leads criados (`POST /v1/leads`) | 60 por minuto por chave | | Conversões (`POST /v1/inbound-submissions`) | 120 por minuto por chave | | Inscrições em cadência | 60 por minuto por chave | | Arquivos (`POST /v1/files`) | 60 por minuto e 1.000 por dia por chave | | Teste de webhook | 5 por minuto por endpoint (20 no workspace) | | Reenvio de webhook | 10 por minuto por endpoint | | Cadastro de webhook | 30 por hora | Toda resposta traz `RateLimit-Limit`, `RateLimit-Remaining` e `RateLimit-Reset` (segundos até a janela recomeçar). Passou do limite: `429 rate_limited` com `Retry-After`. Espere esse tempo e repita com a mesma `Idempotency-Key`. Corpo até 1 MB; arquivo de mídia até 16 MB. --- # Ambientes > Produção e homologação, cada um com o próprio endereço e as próprias chaves. | Ambiente | Endereço | Chave | |---|---|---| | Produção | `https://api.preflow.sale/v1` | `pf_live_…` | | Homologação | `https://api-hml.preflow.sale/v1` | `pf_test_…` | - A chave só funciona no ambiente em que foi criada. Chave de um ambiente no outro responde `401 invalid_api_key`. - Em produção as mensagens saem de verdade e custam créditos. Para testar a integração sem falar com clientes, use um workspace de teste. - O botão **Testar** da [Referência da API](https://developers.preflow.sale/pt/referencia/) chama a produção pelo proxy deste site. Para homologação, use o seu terminal. --- # Versionamento > Versão na URL, mudanças compatíveis a qualquer momento e /v2 para o que quebra. - A versão está na URL (`/v1`). - Campos e rotas novos podem aparecer a qualquer momento. Ignore campos que não conhece, e trate valores novos de enum (status, tipos de evento) sem quebrar. - Mudança que quebra integração vira `/v2`, e a `/v1` continua funcionando por pelo menos 6 meses depois do anúncio. - Tudo o que mudou fica em [Mudanças](https://developers.preflow.sale/pt/changelog/). --- # Erros > Formato único de erro, quando tentar de novo e o catálogo completo de códigos. Todo erro tem o mesmo formato: ```json { "error": { "code": "insufficient_scope", "message": "A chave não tem o escopo necessário para esta rota.", "request_id": "req_6f1c2b0e8a7d4c3b9e2f1a0d5c4b3a29", "retryable": false, "details": { "required_scope": "whatsapp:send" } } } ``` - Decida pelo `code`, que é estável. A `message` é para pessoas e pode mudar. - Tente de novo só quando `retryable` for `true`, e com a mesma `Idempotency-Key`. - Informe o `request_id` ao suporte. ## Catálogo Esta tabela é gerada do código da API a cada publicação, então todo código que a API pode devolver está aqui. ### Gerais | HTTP | `code` | Quando | O que fazer | Tentar de novo | |---|---|---|---|---| | 400 | `idempotency_key_required` | POST, PATCH ou DELETE sem `Idempotency-Key` | Envie o cabeçalho | Não | | 400 | `invalid_cursor` | O `cursor` foi alterado ou é de outra lista | Use o `next_cursor` da página anterior, sem mexer | Não | | 400 | `invalid_idempotency_key` | Chave com mais de 255 caracteres ou com caracteres fora do ASCII visível | Use um UUID | Não | | 400 | `invalid_json` | O corpo não é JSON | Corrija o pedido | Não | | 400 | `invalid_request` | Campo inválido ou faltando (`details.fields`) | Corrija o pedido | Não | | 401 | `api_key_revoked` | Chave revogada | Crie outra chave | Não | | 401 | `authentication_required` | Sem `Authorization: Bearer` | Envie a chave | Não | | 401 | `invalid_api_key` | Chave malformada ou desconhecida | Confira a chave e o ambiente (`pf_live_` em produção) | Não | | 403 | `insufficient_scope` | A chave não tem o acesso da rota (`details.required_scope`). Em webhooks, assinar ou ler um tipo de evento exige também o acesso de leitura do módulo dele | Crie uma chave com o acesso | Não | | 403 | `plan_upgrade_required` | O plano do workspace não tem API (Gratuito, Try) | Assine um plano pago; a mesma chave volta a funcionar | Não | | 403 | `workspace_archived` | O workspace da chave foi arquivado | Use uma chave de outro workspace | Não | | 404 | `lead_not_found` | O `lead_id` não é lead deste workspace | Confira o id | Não | | 404 | `not_found` | O recurso não existe neste workspace | Confira o id | Não | | 404 | `route_not_found` | Rota inexistente | Confira o caminho e a versão | Não | | 405 | `method_not_allowed` | Método não aceito (cabeçalho `Allow`) | Use o método certo | Não | | 409 | `idempotency_conflict` | A `Idempotency-Key` já foi usada com outro corpo | Gere uma chave nova para a nova operação | Não | | 409 | `request_in_progress` | O pedido com essa chave ainda está executando | Tente de novo em instantes | Às vezes (veja `retryable`) | | 409 | `request_outcome_unknown` | O pedido com essa chave terminou sem resultado confirmado | Consulte o recurso antes de tentar com outra chave | Não | | 413 | `payload_too_large` | Corpo acima de 1 MB, ou arquivo acima de 16 MB | Reduza o tamanho | Não | | 415 | `unsupported_media_type` | Corpo sem `Content-Type: application/json` | Envie o cabeçalho | Não | | 429 | `rate_limited` | Limite atingido (`Retry-After`). Inclui os limites de teste, reenvio e cadastro de webhooks (`details.bucket`) | Espere o tempo em `Retry-After` | Sim | | 500 | `internal_error` | Erro inesperado | Em escrita, consulte o recurso antes de repetir | Sim | | 503 | `temporarily_unavailable` | Indisponível no momento | Tente de novo com a mesma `Idempotency-Key` | Sim | ### WhatsApp e arquivos | HTTP | `code` | Quando | O que fazer | Tentar de novo | |---|---|---|---|---| | 402 | `insufficient_credits` | Créditos insuficientes para enviar | Recarregue os créditos | Não | | 404 | `file_not_found` | O `media.file_id` não é arquivo deste workspace | Suba de novo em `POST /v1/files` | Não | | 404 | `sender_not_found` | O `from` não é linha deste workspace | Use um id de `GET /v1/whatsapp/senders` | Não | | 404 | `template_not_found` | Não existe template com esse nome | Confira `GET /v1/whatsapp/templates` | Não | | 409 | `contact_blocked` | Contato encerrado, perdido, que saiu da empresa ou da própria empresa | Fale com o time no Preflow | Não | | 409 | `contact_paused` | O contato está pausado até uma data (`details.until`) | Tente depois da data | Não | | 409 | `privacy_suppressed` | O contato pediu para não receber mensagens | Não envie | Não | | 409 | `sender_unavailable` | A linha não está pronta (desconectada, pausada por qualidade ou em configuração) | Use outra linha ou resolva a linha no Preflow | Não | | 422 | `file_not_uploaded` | Os bytes não foram enviados para a URL de upload | Envie com `PUT` antes de mandar a mensagem | Não | | 422 | `invalid_phone` | Telefone fora do E.164 | Use `+5511999998888` | Não | | 422 | `media_type_not_allowed` | Tipo de arquivo não aceito (`details.allowed`) | Converta o arquivo | Não | | 422 | `provider_rejected` | O WhatsApp recusou a mensagem; nada foi cobrado | Confira o número e o conteúdo | Não | | 422 | `send_refused` | O Preflow recusou o envio por outro motivo | Fale com o suporte com o `request_id` | Não | | 422 | `sender_required` | Sem `from` e sem linha padrão na chave | Informe `from` ou defina a linha padrão | Não | | 422 | `template_not_approved` | O template não está aprovado para o provedor da linha | Aguarde a aprovação | Não | | 422 | `template_unavailable_on_sender` | Linha do WhatsApp Business do celular não manda template | Use outra linha | Não | | 422 | `template_variables_invalid` | Faltam variáveis (`details.missing`) | Preencha todas | Não | | 422 | `whatsapp_window_closed` | Texto ou mídia fora da janela de 24 h (`details.last_inbound_at`) | Use um template aprovado | Não | ### Leads, contas, cadências e reuniões | HTTP | `code` | Quando | O que fazer | Tentar de novo | |---|---|---|---|---| | 403 | `integration_actor_unavailable` | Quem criou a chave não pode mais inscrever leads no workspace | Peça a um administrador uma chave nova | Não | | 404 | `cadence_not_found` | A cadência não é deste workspace ou foi arquivada | Use um id de `GET /v1/cadences` | Não | | 404 | `lead_merged` | O lead foi mesclado em outro (`details.merged_into`) | Passe a usar o lead de `details.merged_into` | Não | | 409 | `cadence_born_cancelled` | Todas as etapas nasceriam canceladas (`details.reason`) | Veja o motivo; nada foi inscrito | Não | | 409 | `cadence_enrollment_refused` | Outra recusa da inscrição | Consulte o lead e tente de novo com outra `Idempotency-Key` | Não | | 409 | `cadence_no_tasks_created` | Nenhuma etapa pode ser criada (`details.skipped_channels`) | Complete o contato do lead (e-mail, telefone) ou use outra cadência | Não | | 409 | `cadence_operator_unavailable` | A conta do lead não tem quem execute a cadência (`details.reason`: `missing_cadence_operator`, `cadence_operator_conflicts_with_account_owner`, `cadence_operator_not_eligible`, `human_account_owner_not_eligible` ou `ai_cadence_requires_human_account_owner`) | Defina o dono de pré-vendas da conta | Não | | 409 | `external_id_in_progress` | Outro pedido está criando agora o lead deste `external_id` | Tente de novo em instantes; a resposta traz o lead criado pelo outro pedido | Às vezes (veja `retryable`) | | 409 | `lead_already_in_cadence` | O lead já está nesta cadência | Nada a fazer | Não | | 409 | `lead_archived` | O lead está arquivado | Reabra o lead no Preflow | Não | | 409 | `lead_engagement_paused` | O lead respondeu há pouco (`details.until`) | Tente depois de `details.until` | Não | | 409 | `lead_in_active_conversation` | O lead está numa conversa em andamento | Tente depois que a conversa terminar | Não | | 409 | `lead_not_eligible_for_cadence` | O lead não pode entrar em cadência agora (`details.reason`: `lead_do_not_contact_until`, `lead_passed_meeting_stage`, `lost_cooldown`, `lost_reprospect_not_eligible`, `status_not_appendable`, `meeting_reprospect_not_eligible`, `not_eligible`) | Veja o motivo; `lost_cooldown` traz `details.cooldown_until` | Não | | 422 | `cadence_has_no_steps` | A cadência não tem etapas | Use outra cadência | Não | | 422 | `lead_suppressed` | O contato pediu para não ser contatado (privacidade). Também recusa a conversão de `POST /v1/inbound-submissions`, antes de qualquer registro | Não crie o lead de novo | Não | ### Conversões (POST /v1/inbound-submissions) | HTTP | `code` | Quando | O que fazer | Tentar de novo | |---|---|---|---|---| | 409 | `submission_id_conflict` | O `submission_id` já foi usado com outro conteúdo | Use um `submission_id` novo para uma conversão nova | Não | | 409 | `submission_in_progress` | Outro pedido está registrando a mesma conversão agora | Tente de novo em instantes | Às vezes (veja `retryable`) | | 422 | `answers_invalid` | Com `form_id`: resposta para campo que não existe, fora das opções ou campo obrigatório vazio (`details.fields`) | Ajuste as respostas ao formulário | Não | | 422 | `campaign_not_found` | O `campaign` não é o slug de uma campanha deste workspace (ou está arquivada) | Confira o slug da campanha | Não | | 422 | `form_not_found` | O `form_id` não é de um formulário publicado deste workspace | Confira o id do formulário | Não | | 422 | `funnel_not_found` | O `funnel_id` não é de um funil ativo deste workspace | Use um id de `GET /v1/funnels` | Não | ### Webhooks | HTTP | `code` | Quando | O que fazer | Tentar de novo | |---|---|---|---|---| | 400 | `invalid_webhook_url` | URL que não é `https://`, com usuário e senha ou com mais de 2048 caracteres | Corrija a URL | Não | | 400 | `unknown_event_type` | Evento fora do catálogo | Consulte `GET /v1/event-types` | Não | | 400 | `webhook_url_not_allowed` | Endereço interno, privado, de metadados ou do Preflow | Use uma URL pública do seu sistema | Não | | 409 | `webhook_delivery_already_succeeded` | Reenvio de uma entrega que já deu certo | Nada a fazer: o evento já chegou | Não | | 409 | `webhook_delivery_in_progress` | A entrega está sendo enviada agora | Tente de novo em instantes | Não | | 409 | `webhook_endpoint_limit_reached` | O workspace já tem 10 endpoints | Exclua um endpoint | Não | | 409 | `webhook_endpoint_not_active` | Teste ou reenvio em endpoint desligado ou pausado pelo plano | Religue o endpoint | Não | | 409 | `webhook_rotation_in_progress` | O segredo foi girado há menos de 24 h | Espere o anterior expirar | Não | --- # Eventos > Catálogo de eventos de webhook do Preflow e o formato do data de cada um. Todo evento chega por [webhook](https://developers.preflow.sale/pt/guides/webhooks/) com o mesmo envelope e pode ser consultado por 30 dias em `GET /v1/events/{id}`. A lista do que um endpoint pode assinar no seu workspace está em `GET /v1/event-types`. ## Envelope Todo webhook é um `POST` com `Content-Type: application/json` e este envelope: ```json { "id": "evt_9b2f0c1d4e5a46b7a8c9d0e1f2a3b4c5", "type": "whatsapp.message.received", "created_at": "2026-11-16T15:04:05.123Z", "workspace_id": "6e0b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d", "data": { } } ``` Cabeçalhos (padrão [Standard Webhooks](https://www.standardwebhooks.com)): | Cabeçalho | Valor | |---|---| | `webhook-id` | O `id` do evento. É o **mesmo** em todas as tentativas: use para deduplicar. | | `webhook-timestamp` | Segundos Unix desta tentativa. | | `webhook-signature` | `v1,`; durante 24 h depois de girar o segredo, duas, separadas por espaço. | ## WhatsApp ### `whatsapp.message.received` Mensagem recebida numa linha do workspace (do lead ou de um contato). ```json { "id": "evt_…", "type": "whatsapp.message.received", "created_at": "2026-11-16T15:04:05.123Z", "workspace_id": "6e0b1c2d-…", "data": { "id": "0d9c8b7a-6f5e-4d3c-8b2a-1f0e9d8c7b6a", "conversation_id": "5a4b3c2d-1e0f-4a9b-8c7d-6e5f4a3b2c1d", "direction": "inbound", "status": "received", "type": "text", "text": "Oi, quero saber o preço", "from": "+5511999990000", "to": "+5511888880000", "media": null, "template": null, "lead_id": "7c6b5a49-3827-4615-9a8b-7c6d5e4f3a2b", "contact_id": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "created_at": "2026-11-16T15:04:05.001Z" } } ``` `from` é o contato e `to` é a linha (E.164). Com arquivo, `type` é `image`, `audio`, `video`, `document` ou `sticker` e `media` traz `{ id, type, mime_type, file_name }` para baixar pela API de WhatsApp. ### `whatsapp.message.sent` Mensagem enviada (aceita pelo provedor), de qualquer origem. Os mesmos campos, com `direction: "outbound"`, `from` = linha, `to` = contato, e: | Campo | Valor | |---|---| | `origin` | `api` (sua integração), `cadence` (passo de cadência), `ai` (resposta da IA), `human` (pessoa no Preflow) ou `whatsapp_app` (app do WhatsApp Business do celular). O mesmo valor do histórico de mensagens da API. | | `client_reference` | Só com `origin: "api"`: o valor que você mandou no envio | | `api_message_id` | Só com `origin: "api"` | Mensagem que o provedor recusou na hora não gera `sent` (o envio pela API já responde com o erro). ### `whatsapp.message.status_updated` Mensagem enviada foi entregue, lida ou falhou. Os mesmos campos da mensagem e: ```json { "status": "failed", "previous_status": "sent", "status_at": "2026-11-16T15:05:00Z", "failure": { "reason": "window_closed" } } ``` `status`: `delivered`, `read` ou `failed`. Cada status chega uma vez por mensagem. `failure.reason` (só em `failed`): `window_closed` (fora da janela de 24 h, precisa de template), `invalid_recipient`, `recipient_opted_out`, `not_delivered_by_whatsapp` (o WhatsApp decidiu não entregar), `rate_limited`, `template_error`, `media_error` ou `delivery_failed`. ### `whatsapp.template.status_updated` ```json { "id": "2b3c4d5e-6f70-4a8b-9c0d-1e2f3a4b5c6d", "name": "boas_vindas", "language": "pt_BR", "category": "UTILITY", "provider": "meta", "status": "approved", "previous_status": "pending", "reason": null } ``` `status`: `approved`, `pending`, `rejected` ou `archived`. ### `webhook.test` Mandado por "Testar" na tela ou por `POST /v1/webhook-endpoints/{id}/test`, só para aquele endpoint: `data` = `{ "endpoint_id": "…", "message": "Evento de teste do Preflow." }`. ## Leads, contas e reuniões O `data` de cada evento é a foto do recurso no momento do evento, no mesmo formato das rotas `GET` acima; use o `id` para buscar o estado atual. | Evento | Quando | `data` | |---|---|---| | `lead.created` | Lead novo no workspace (por qualquer entrada, não só a API) | `{ lead }` | | `inbound.submission_received` | Conversão registrada por `POST /v1/inbound-submissions` (lead novo, lead que já existia ou só contato) | `{ inbound_submission }` | | `lead.lost` | Lead marcado como perdido | `{ lead, reason, reason_label, scope, lost_at }` | | `account.stage_changed` | A conta mudou de etapa num funil | `{ account, funnel_id, product_id, from_stage, to_stage, intermediate_stage, changed_at }` | | `account.qualification_changed` | A qualificação da conta mudou (ex.: virou Cliente ou Churn) | `{ account, from, to, changed_at }` | | `meeting.scheduled` | Reunião marcada | `{ meeting }` | | `meeting.rescheduled` | Reunião mudou de horário | `{ meeting, previous_starts_at }` | | `meeting.cancelled`, `meeting.completed`, `meeting.no_show` | Reunião cancelada, realizada ou sem comparecimento | `{ meeting }` | - `scope` do `lead.lost`: `lead` (só esta pessoa) ou `funnel` (a conta sai daquele funil). - A entrada da conta no primeiro funil não gera `account.stage_changed`: o `lead.created` já avisa. - Bloqueios copiados da agenda do Outlook ou do Google não geram evento de reunião, e lead de teste do onboarding não gera `lead.created`. ```json { "id": "evt_…", "type": "account.stage_changed", "created_at": "2026-11-16T15:00:00.000Z", "workspace_id": "6c1f…", "data": { "account": { "id": "4007…", "object": "account", "name": "Empresa", "qualification": "sql", "…": "…" }, "funnel_id": "0aff…", "product_id": null, "from_stage": "qualified", "to_stage": "scheduled", "intermediate_stage": null, "changed_at": "2026-11-16T14:59:58.120Z" } } ``` --- # Mudanças > O que mudou na API pública do Preflow, por entrega. ## v1 — conversões inbound - `POST /v1/inbound-submissions`: registra a conversão de uma pessoa que pediu contato (formulário do site, landing, app). Segue o caminho de um formulário do Preflow: MQL por padrão (`"qualified": false` para só contato), respostas no lead, atribuição (UTM, campanha, página, cookies da Meta), cadência de Inbound. Lead perdido, ganho, arquivado ou já em atendimento só ganha o registro. `form_id` aplica as regras de MQL de um formulário do Preflow. `submission_id` único no workspace. Limite de 120 por minuto por chave. Guia em [Receber leads do seu site](https://developers.preflow.sale/pt/guides/website-leads/). - `GET /v1/inbound-submissions/{id}`. - Webhook `inbound.submission_received`. - O catálogo de tipos de evento no OpenAPI (`WebhookEventTypeName`) passa a listar os eventos de lead, conta e reunião, que já existiam. ## v1 — WhatsApp (16/11/2026) - `GET /v1/whatsapp/senders`, `GET /v1/whatsapp/templates`, `GET /v1/whatsapp/window`. - `POST /v1/files` (upload por URL assinada, até 16 MB). - `POST /v1/whatsapp/messages` (texto, template aprovado ou mídia, para telefone ou lead), `GET /v1/whatsapp/messages/{id}` (status de entrega), `GET /v1/whatsapp/messages?to=` (histórico) e `GET /v1/whatsapp/messages/{id}/media`. - Linha padrão por chave, escolhida na tela de chaves. ## v1 — webhooks (16/11/2026) - Endpoints de webhook (até 10 por workspace) com acesso `webhooks:manage`: cadastro, edição, desligar/religar, exclusão, segredo novo (o anterior vale mais 24 h), teste, log de entregas de 30 dias e reenvio. - Eventos `whatsapp.message.received`, `whatsapp.message.sent`, `whatsapp.message.status_updated` e `whatsapp.template.status_updated`, assinados no padrão Standard Webhooks, entregues pelo menos uma vez com novas tentativas por cerca de 2 dias. Guia em [Webhooks](https://developers.preflow.sale/pt/guides/webhooks/). - `GET /v1/event-types` e `GET /v1/events/{id}`. - Assinar ou ler um tipo de evento exige também o acesso de leitura do módulo dele (`whatsapp:read`, `leads:read`, `accounts:read`, `meetings:read`). - Reenvio recusa a entrega que já deu certo e aceita até 10 por minuto por endpoint; falha antes da conexão TLS aparece só como `dns_or_address_refused`. ## v1 — fundação (16/11/2026) - Chaves secretas por workspace (`pf_live_` / `pf_test_`), com acessos (escopos), criadas e revogadas em Configurações → Integrações → API e webhooks. - Só administrador ou dono do workspace cria e revoga chave; a chave cai quando quem a criou deixa de ser administrador. - `GET /v1/me` e `GET /v1/openapi.json`. - Idempotência em toda escrita, limite de 600 pedidos por minuto por chave e formato único de erro. ## v1 — leads, contas, funis, cadências e reuniões - `POST /v1/leads`: cria lead que entra como inbound e segue a configuração de Inbound do workspace. Aceita lead só com telefone; `external_id` único por workspace. - `GET /v1/leads`, `GET /v1/leads/{id}` e `GET /v1/leads/{id}/activities`. - `GET /v1/accounts`, `GET /v1/accounts/{id}` e `GET /v1/funnels`. - `GET /v1/cadences`, `POST /v1/leads/{id}/cadence-enrollments` e `POST /v1/leads/{id}/cadence-stop`. - `GET /v1/meetings` e `GET /v1/meetings/{id}`. --- # Preflow API > Connect your company's systems to Preflow — WhatsApp, leads, accounts, cadences, meetings and webhooks. With the API you send WhatsApp messages from the lines already in Preflow, create leads, enroll leads in cadences and get notified when things happen: a message is received, delivered or read, a lead is qualified, an account changes stage, a meeting is booked. ## API or webhook? - **API: your system asks or sends.** Send WhatsApp messages, upload files, create leads, enroll in or stop cadences, look things up. - **Webhook: Preflow tells you.** A message is received, delivered, read or fails; a template is approved; a lead is created or lost; an account changes stage; a meeting is booked. - Every notification carries the ids to fetch the full resource from the API. You never need to poll to find out whether something changed. ## Start here - [Quickstart](https://developers.preflow.sale/en/quickstart/): Create a key and make your first call in 5 minutes. - [WhatsApp](https://developers.preflow.sale/en/guides/whatsapp/): Text, approved templates and media, with delivery status. - [Leads, accounts and cadences](https://developers.preflow.sale/en/guides/leads/): Create leads, sync them and enroll them in cadences. - [Webhooks](https://developers.preflow.sale/en/guides/webhooks/): Receive signed notifications and verify the signature. ## What's available | Module | Status | |---|---| | Account (`/v1/me`, `/v1/openapi.json`) | Available | | WhatsApp: lines, templates, 24-hour window, sending, status, history, media | Available | | Webhooks: setup, signing, deliveries; WhatsApp, lead, account and meeting events | Available | | Leads, accounts and funnels, cadences, meetings | Available | | Inbound conversions from your website or app | Available | Everything in this documentation already works. What's new is listed in the [Changelog](https://developers.preflow.sale/en/changelog/). ## For AI assistants - [`/llms.txt`](https://developers.preflow.sale/llms.txt): an index of this documentation for language models. - [`/llms-full.txt`](https://developers.preflow.sale/llms-full.txt): the whole documentation in one Markdown file. - [`/openapi.en.json`](https://developers.preflow.sale/openapi.en.json): the OpenAPI 3.1 specification. - On every page, **Copy as Markdown** copies the page so you can paste it into your assistant. --- # Quickstart in 5 minutes > Create an API key in Preflow and make your first call with GET /v1/me. You need to be a **workspace admin or owner** and be on a paid plan (or be a client funded by your agency). 1. **Create the key.** In Preflow, open **Settings → Integrations → API & webhooks**, click to create a key, give it a name (for example `ERP`) and select the scopes your integration needs. No scope is required for this test. 2. **Store the key.** It is shown **only once**. Copy it and store it in the secret vault of the server that will call the API. In your terminal, for the test: ```bash export PREFLOW_API_KEY="pf_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` 3. **Make your first call.** `GET /v1/me` tells you which workspace the key belongs to, which scopes it has and its request limit: ```bash curl https://api.preflow.sale/v1/me -H "Authorization: Bearer $PREFLOW_API_KEY" ``` ```json { "api_version": "v1", "workspace": { "id": "6c1f…", "name": "My Company" }, "api_key": { "id": "0b9e…", "name": "ERP", "environment": "live", "scopes": [] }, "limits": { "requests_per_minute": 600 } } ``` 4. **Pick your next step.** Add the scopes for what you're going to build and follow the guide: [WhatsApp](https://developers.preflow.sale/en/guides/whatsapp/), [Leads, accounts and cadences](https://developers.preflow.sale/en/guides/leads/) or [Webhooks](https://developers.preflow.sale/en/guides/webhooks/). > **Caution:** The key is for server-to-server use. Never put it in your website, your mobile app or any code that runs on your customer's machine. ## Got an error? | Response | What to do | |---|---| | `401 authentication_required` | The `Authorization: Bearer …` header is missing | | `401 invalid_api_key` | Check that you copied the whole key and that you're using the right environment ([Environments](https://developers.preflow.sale/en/concepts/environments/)) | | `403 plan_upgrade_required` | The workspace's plan doesn't include the API; once you subscribe, the same key works again | Every code is listed in [Errors](https://developers.preflow.sale/en/concepts/errors/). --- # WhatsApp > Send WhatsApp messages from the workspace's lines: text, approved templates and media, with delivery status and history. Send WhatsApp messages from the lines your workspace already has in Preflow: order updates, invoices, reminders, confirmations. First, read [Authentication and scopes](https://developers.preflow.sale/en/concepts/authentication/), [Idempotency](https://developers.preflow.sale/en/concepts/idempotency/) and [Errors](https://developers.preflow.sale/en/concepts/errors/). Scopes: `whatsapp:read` to query and `whatsapp:send` to send and upload files. ## 1. Pick the line ```bash curl https://api.preflow.sale/v1/whatsapp/senders -H "Authorization: Bearer $PREFLOW_API_KEY" ``` ```json { "data": [ { "id": "8c5d…", "kind": "person", "phone": "+5511988887777", "owner": { "id": "1f2e…", "name": "Ana Souza" }, "is_default": true, "status": "online" }, { "id": "b71a…", "kind": "ai_agent", "phone": "+5511977776666", "owner": { "id": "b71a…", "name": "Clara" }, "is_default": false, "status": "online" } ] } ``` - `person`: the number of an active person in the workspace. `ai_agent`: an AI agent's own number. - Use the `id` in `from`. Without `from`, the **key's default line** applies; the admin chooses it in Settings → Integrations → API & webhooks. - A person's WhatsApp Business app on their phone is their personal phone and doesn't show up here: the API only uses company and AI agent numbers. - The contact's replies come in on that same line. ## 2. The 24-hour window WhatsApp only accepts free-form text and media up to 24 h after the contact's last message **to that line**. Outside the window, only an **approved template** works. ```bash curl "https://api.preflow.sale/v1/whatsapp/window?to=%2B5511999998888&from=8c5d…" \ -H "Authorization: Bearer $PREFLOW_API_KEY" ``` ```json { "to": "+5511999998888", "from": { "id": "8c5d…", "phone": "+5511988887777" }, "open": false, "last_inbound_at": null, "expires_at": null } ``` Sending text with the window closed responds `422 whatsapp_window_closed`, at no cost. The API refuses before calling WhatsApp. ## 3. Templates ```bash curl https://api.preflow.sale/v1/whatsapp/templates -H "Authorization: Bearer $PREFLOW_API_KEY" ``` ```json { "data": [ { "id": "c0a1…", "name": "pedido_enviado", "display_name": "Pedido enviado", "language": "pt_BR", "category": "utility", "status": "approved", "body": "Oi {{nome}}, o pedido {{pedido}} saiu para entrega.", "variables": ["nome", "pedido"], "header": null } ] } ``` By default the list only includes templates approved for the workspace's provider (`?status=all` returns all of them). Templates are created and approved on the Preflow screen. ## 4. Send Provide the destination (`to` in E.164 or `lead_id`) and **one** content type: `text`, `template` or `media`. `Idempotency-Key` is required. With both `lead_id` and `to`, `to` must be one of that lead's phone numbers. **Text** (window open): ```bash curl -X POST https://api.preflow.sale/v1/whatsapp/messages \ -H "Authorization: Bearer $PREFLOW_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: order-1234-shipped" \ -d '{"to":"+5511999998888","from":"8c5d…","text":"Your order 1234 is out for delivery.","client_reference":"order-1234"}' ``` **Template** (any time). Variables go by name or by position (`"1"`, `"2"`…), and all of them are required: ```json { "lead_id": "3f0c…", "template": { "name": "pedido_enviado", "language": "pt_BR", "variables": { "nome": "Ana", "pedido": "1234" } } } ``` **Media**: first upload the file (section 5), then: ```json { "to": "+5511999998888", "media": { "file_id": "7d1e…", "caption": "Here's your invoice." } } ``` `201` response: ```json { "id": "e4b2…", "to": "+5511999998888", "from": { "id": "8c5d…", "kind": "person", "phone": "+5511988887777" }, "lead_id": null, "contact_id": "a9d3…", "conversation_id": "0f6e…", "type": "text", "template": null, "client_reference": "order-1234", "status": "sent", "error": null, "message_id": "5c7b…", "created_at": "2026-11-16T15:04:05Z", "updated_at": "2026-11-16T15:04:06Z" } ``` What happens in Preflow: - **A number that isn't a lead yet becomes a contact** (not a lead). A lead's phone number goes to that lead. Use `contact_name` to name the new contact. - The message shows up in the conversation and on the timeline with the "Integration" label. - **It doesn't take the conversation away from whoever is handling it.** If the AI was handling the lead, it keeps handling it; if the contact replies, the usual flow continues. - **It doesn't count as a touch** on the team's dashboards (War Room, effort per channel, goals). - It goes through the same rules as any send in Preflow: people who asked not to receive messages (`privacy_suppressed`), contacts paused until a date (`contact_paused`), closed or lost contacts (`contact_blocked`), plan and credits (`insufficient_credits`), lines paused for quality (`sender_unavailable`). ### Status and uncertainty `GET /v1/whatsapp/messages/{id}` returns the delivery status: `sent`, `delivered`, `read` or `failed`. If WhatsApp doesn't confirm in time, the send responds `202` with `"status": "unknown"` and **nothing is resent**, not even when you repeat the same `Idempotency-Key` (which then responds `409 request_outcome_unknown`). Check `GET /v1/whatsapp/messages/{id}`: once the message goes out, the status moves to `sent` and then `delivered`/`read`. Don't send again with a different key before checking, or the contact gets it twice. ## 5. Files ```bash curl -X POST https://api.preflow.sale/v1/files \ -H "Authorization: Bearer $PREFLOW_API_KEY" -H "Content-Type: application/json" \ -H "Idempotency-Key: invoice-1234" \ -d '{"filename":"invoice-1234.pdf","content_type":"application/pdf","size":48211}' ``` ```json { "id": "7d1e…", "filename": "invoice-1234.pdf", "content_type": "application/pdf", "size": 48211, "upload": { "method": "PUT", "url": "https://api.preflow.sale/storage/v1/object/upload/sign/…", "headers": { "content-type": "application/pdf" }, "expires_at": "2026-11-16T17:04:05Z" } } ``` Send the bytes to `upload.url` with `PUT` and the headers listed, within 2 h. Then use the `id` in `media.file_id`. The uploaded file must match the declared size (`size`) and type (`content_type`), or the send responds `file_not_uploaded` / `media_type_not_allowed`. Limit of 60 files per minute and 1,000 per day per key; the file is deleted 30 days after upload. Accepted types: JPEG, PNG and WebP images; PDF; OGG, MP3, M4A and AAC audio; MP4 and 3GP video; text; Word, Excel and PowerPoint. Up to 16 MB. ## 6. History and received media ```bash curl "https://api.preflow.sale/v1/whatsapp/messages?to=%2B5511999998888&limit=50" \ -H "Authorization: Bearer $PREFLOW_API_KEY" ``` Returns every message with that phone number, received and sent, newest first. `origin` says who sent it: `api`, `cadence`, `ai`, `human` or `whatsapp_app` (from the phone app). Messages sent through the API include `api_message_id` and `client_reference`. To download a message's media: `GET /v1/whatsapp/messages/{id}/media`. The response is the file, with its original `Content-Type` and `Content-Disposition: attachment`. Treat it as a file sent by a third party. ## Limits and cost - 60 sends per minute per key, and 60 per minute per line (across all of the workspace's keys). - The cost follows Preflow's WhatsApp price table (the same as in the app). A refusal from WhatsApp refunds the credit. - Bulk messages to cold lists hurt the line's quality and can get the number paused. For prospecting, use Preflow's cadences. --- # Leads, accounts and cadences > Create leads, look them up and sync them, read accounts and funnels, enroll in cadences and query meetings. A guide to the public API's CRM routes. General conventions are in [Authentication](https://developers.preflow.sale/en/concepts/authentication/), [Idempotency](https://developers.preflow.sale/en/concepts/idempotency/), [Pagination](https://developers.preflow.sale/en/concepts/pagination/) and [Errors](https://developers.preflow.sale/en/concepts/errors/). | Route | Scope | What it's for | |---|---|---| | `POST /v1/inbound-submissions` | `leads:write` | A person asked to be contacted on your website, app or system ([guide](https://developers.preflow.sale/en/guides/website-leads/)) | | `GET /v1/inbound-submissions/{id}` | `leads:read` | Retrieve a conversion | | `POST /v1/leads` | `leads:write` | Send a new lead from your system | | `GET /v1/leads`, `GET /v1/leads/{id}` | `leads:read` | Look up by email, phone or `external_id`, or sync | | `GET /v1/leads/{id}/activities` | `leads:read` | The lead's timeline | | `GET /v1/accounts`, `GET /v1/accounts/{id}` | `accounts:read` | Stage per funnel, owners, qualification, Customer/Churn | | `GET /v1/funnels` | `accounts:read` | Funnels and stages | | `GET /v1/cadences` | `cadences:read` | Cadences that can take leads | | `POST /v1/leads/{id}/cadence-enrollments` | `cadences:write` | Enroll the lead in a cadence | | `POST /v1/leads/{id}/cadence-stop` | `cadences:write` | Stop the lead's cadence | | `GET /v1/meetings`, `GET /v1/meetings/{id}` | `meetings:read` | Booked meetings | ## Create a lead The lead comes in as **inbound**: the workspace's Inbound settings decide the cadence, who handles it and who gets notified, just like a website form. ```bash curl https://api.preflow.sale/v1/leads \ -H "Authorization: Bearer $PREFLOW_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"name":"Ana Souza","phone":"+5511999998888","email":"ana@empresa.com.br","company":"Acme","external_id":"erp-12345"}' ``` ```json { "lead_id": "9b2c…", "lead": { "id": "9b2c…", "object": "lead", "name": "Ana Souza", "status": "new", "origin": "inbound", "external_ids": ["erp-12345"], "…": "…" }, "created": true, "matched_by": null, "inbound_cadence": { "started": true, "reason": "distribution", "cadence_id": "4f1e…" } } ``` - Provide `email` or `phone` (E.164, `+5511999998888`). Phone-only leads are accepted. - **Does the lead already exist?** If the email or phone already belongs to a lead in the workspace, the response is `200` with `created: false` and that lead, unchanged. A lead that is already being worked (in a cadence, lost, won or that came in through prospecting) is never reopened, and `inbound_cadence` is `null`. - The lead snapshot (`lead`) is only returned to keys that also have `leads:read`. A write-only key (a form, for example) gets only `lead_id`. - Its own limit: 60 leads per minute per key. - **`external_id`** is the lead's id in your system, unique within the workspace. Sending the same `external_id` again returns the same lead, unchanged (`matched_by: "external_id"`). Two simultaneous requests with the same `external_id` never create two leads: the second gets `409 external_id_in_progress` and, when retried, the lead created by the first. Look it up with `GET /v1/leads?external_id=erp-12345`. - A contact who asked not to be contacted responds `422 lead_suppressed`. - `source` is a free-form label from your system (e.g. `erp`), stored with the entry. ## Search and sync ```bash # by email, phone or your system's id curl "https://api.preflow.sale/v1/leads?email=ana@empresa.com.br" -H "Authorization: Bearer $PREFLOW_API_KEY" # sync: everything that changed since last time, page by page curl "https://api.preflow.sale/v1/leads?updated_since=2026-11-16T00:00:00Z&limit=100" -H "Authorization: Bearer $PREFLOW_API_KEY" ``` The list is ordered by update time (oldest first). Store the `updated_at` of the last item and use it as `updated_since` in the next run; `next_cursor` takes you to the next page of the same run. Accounts work the same way (`GET /v1/accounts?updated_since=`). To learn about changes without polling, use webhooks (see [Events](https://developers.preflow.sale/en/events/#leads-accounts-and-meetings) below). ## Timeline `GET /v1/leads/{id}/activities` returns the lead's touches and milestones, newest first, each with a stable public type: | Type | What it is | |---|---| | `email.sent`, `email.received` | Email sent or received | | `whatsapp.sent`, `whatsapp.received` | WhatsApp message sent or received | | `call.made`, `call.received` | Call made or received (`call.connection_status`) | | `linkedin.invitation_sent`, `linkedin.invitation_accepted`, `linkedin.sent`, `linkedin.received` | LinkedIn | | `meeting.scheduled`, `meeting.confirmed`, `meeting.completed` | Meeting | | `lead.lost`, `lead.reactivated`, `lead.status_changed` | Change in the lead's status | | `lead.received_from_api` | The lead came in through the API | | `note` | Note | `actor.type` says who acted: `human`, `ai`, `lead`, `integration` or `system`. Internal Preflow records are not shown. ## Accounts and funnels The account owns the lead. `GET /v1/accounts/{id}` returns: - `funnels`: one entry per funnel, with the fixed stage (`new`, `qualified`, `scheduled`, `completed`, `no_show`, `negotiation`, `won`, `lost`) and the intermediate stage created by the workspace, if any. - `owners.pre_sales` and `owners.sales`: who handles the account before and after the meeting. - `qualification`, `is_customer` (Customer) and `is_churn` (Churn). A Churn account leaves the board (`on_board: false` in every funnel); a Customer account only stays in Sales. `GET /v1/funnels` lists the funnels, the fixed stages with the name shown in Preflow and each stage's intermediate stages. ## Cadences ```bash curl https://api.preflow.sale/v1/leads/9b2c…/cadence-enrollments \ -H "Authorization: Bearer $PREFLOW_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"cadence_id":"4f1e…"}' ``` - Enrollment works exactly like it does on the screen, with the same refusals: the lead is already in the cadence, engagement pause, the lead has already had a meeting, lost-lead cooldown, a cadence whose steps would all be born cancelled. Each one has a code in [Errors](https://developers.preflow.sale/en/concepts/errors/#catalog). - The steps are carried out by the pre-sales owner of the lead's account. On the timeline the enrollment shows up as made by the integration, with the key, and doesn't count as a touch. The key can only enroll while the person who created it is still a workspace admin or owner. - `POST /v1/leads/{id}/cadence-stop` stops the cadence **of this lead**: other people in the same account stay in their cadences, and ongoing conversations and manually scheduled follow-ups continue. Whatever was queued for sending is cancelled; what the provider already received can't be pulled back. With no open cadence, it responds `stopped: false`. ## Meetings ```bash curl "https://api.preflow.sale/v1/meetings?from=2026-11-01T00:00:00Z&to=2026-12-01T00:00:00Z&status=scheduled" \ -H "Authorization: Bearer $PREFLOW_API_KEY" ``` - `status`: `scheduled`, `confirmed`, `tentative`, `rescheduled`, `completed`, `no_show` or `cancelled`. - Blocks copied from Outlook or Google calendars are not meetings and never show up. - `closer` is who runs the meeting; `scheduled_by` is who booked it. ## Events To learn about changes without polling, subscribe to the `lead.*`, `account.*` and `meeting.*` events by [webhook](https://developers.preflow.sale/en/guides/webhooks/). The format of each one is in [Events](https://developers.preflow.sale/en/events/#leads-accounts-and-meetings). --- # Webhooks > Receive signed notifications from Preflow: setup, signature verification (Node.js, Python, PHP), delivery and retries. Preflow notifies your system when something happens: a WhatsApp message is received, sent, delivered, read or fails; a template is approved or rejected. You register an `https://` URL (the **endpoint**), choose the events, and Preflow sends a signed `POST` to it for each event. - Set it up on the screen (**Settings → Integrations → API & webhooks**) or through the API (scope `webhooks:manage`). Up to **10 endpoints** per workspace. - Each notification carries the resource (message text, phone number, lead). Through the API, a key can only subscribe to or read (`GET /v1/events/{id}`) an event type if it has the read scope of that type's module: `whatsapp.*` → `whatsapp:read`, `lead.*` → `leads:read`, `account.*` → `accounts:read`, `meeting.*` → `meetings:read`. Changing the URL or the events, or re-enabling, also requires those scopes. If the key that created the endpoint loses one of them, deliveries of that type are cancelled (`last_error: event_scope_missing`). - Each notification carries the ids to fetch the full resource from the API. - Format of each event: [Events](https://developers.preflow.sale/en/events/). Routes: [API reference](https://developers.preflow.sale/en/reference/). ## Setup ```http POST /v1/webhook-endpoints Authorization: Bearer pf_live_… Idempotency-Key: 5f0c1d2e-3a4b-4c5d-8e6f-7a8b9c0d1e2f Content-Type: application/json { "url": "https://erp.suaempresa.com.br/webhooks/preflow", "events": ["whatsapp.message.received", "whatsapp.message.status_updated"] } ``` `201` response: ```json { "id": "3f1d2c4b-5a6e-4f70-8a9b-0c1d2e3f4a5b", "url": "https://erp.suaempresa.com.br/webhooks/preflow", "status": "active", "events": ["whatsapp.message.received", "whatsapp.message.status_updated"], "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSwfQmfVNQhnkZ=" } ``` The `secret` is shown **only once** in the API. Store it in the secret vault of the server that receives the webhooks. Repeating the request with the same `Idempotency-Key` returns the endpoint with `secret: null` and `secret_redacted: true`; if you lose the secret, rotate it. On the screen, an admin can view the secret again ("Show secret"); every view is logged. The URL must be `https://`, with no username or password. Internal, private, loopback, link-local, cloud-metadata or Preflow's own addresses are refused (`webhook_url_not_allowed`), at setup and again **on every delivery** (DNS is resolved every time and every address must be public). | Route | What it does | |---|---| | `GET /v1/event-types` | Events an endpoint can subscribe to | | `GET /v1/webhook-endpoints` | The workspace's endpoints (without the secret) | | `POST /v1/webhook-endpoints` | Creates one (returns the secret) | | `GET /v1/webhook-endpoints/{id}` | One endpoint | | `PATCH /v1/webhook-endpoints/{id}` | Changes `url`, `events`, `description` or `status` (`active`/`disabled`) | | `DELETE /v1/webhook-endpoints/{id}` | Deletes it (along with its secret and delivery log) | | `POST /v1/webhook-endpoints/{id}/rotate-secret` | New secret; the previous one stays valid for 24 more hours | | `POST /v1/webhook-endpoints/{id}/test` | Sends a `webhook.test` event | | `GET /v1/webhook-endpoints/{id}/deliveries` | Delivery log (30 days): status, HTTP code and duration | | `POST /v1/webhook-deliveries/{id}/retry` | Redelivers now (not one that already succeeded; up to 10 per minute per endpoint) | | `GET /v1/events/{id}` | An event from the last 30 days, with its deliveries | ## What you receive Every webhook is a `POST` with `Content-Type: application/json` and this envelope: ```json { "id": "evt_9b2f0c1d4e5a46b7a8c9d0e1f2a3b4c5", "type": "whatsapp.message.received", "created_at": "2026-11-16T15:04:05.123Z", "workspace_id": "6e0b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d", "data": { } } ``` Headers ([Standard Webhooks](https://www.standardwebhooks.com) spec): | Header | Value | |---|---| | `webhook-id` | The event `id`. It is the **same** on every attempt: use it to deduplicate. | | `webhook-timestamp` | Unix seconds of this attempt. | | `webhook-signature` | `v1,`; for 24 h after a secret rotation, two of them, separated by a space. | The events and the `data` of each one are in [Events](https://developers.preflow.sale/en/events/). ## Verify the signature 1. Read the **raw** body (the bytes as they arrived; don't reformat the JSON). 2. Build `"{webhook-id}.{webhook-timestamp}.{body}"`. 3. The key is the secret **without** the `whsec_` prefix, base64-decoded. 4. Compute HMAC-SHA256, base64-encode it and compare it (in constant time) with each `v1,…` value in the `webhook-signature` header. One match is enough. 5. Reject a `webhook-timestamp` more than 5 minutes off from your clock. ### Node.js ```js const secret = process.env.PREFLOW_WEBHOOK_SECRET; // whsec_… const app = express(); app.post('/webhooks/preflow', express.raw({ type: 'application/json' }), (req, res) => { const id = req.header('webhook-id'); const timestamp = req.header('webhook-timestamp'); const signatures = (req.header('webhook-signature') ?? '').split(' '); if (!id || !timestamp || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return res.sendStatus(400); const key = Buffer.from(secret.slice('whsec_'.length), 'base64'); const expected = crypto.createHmac('sha256', key).update(`${id}.${timestamp}.${req.body}`).digest(); const valid = signatures.some((entry) => { const [version, value] = entry.split(','); const given = Buffer.from(value ?? '', 'base64'); return version === 'v1' && given.length === expected.length && crypto.timingSafeEqual(given, expected); }); if (!valid) return res.sendStatus(401); const event = JSON.parse(req.body); // Deduplicate by event.id and respond quickly; process in the background. res.sendStatus(204); }); ``` ### Python ```python from flask import Flask, request, abort SECRET = os.environ["PREFLOW_WEBHOOK_SECRET"] # whsec_… app = Flask(__name__) @app.post("/webhooks/preflow") def preflow_webhook(): msg_id = request.headers.get("webhook-id", "") timestamp = request.headers.get("webhook-timestamp", "") signatures = request.headers.get("webhook-signature", "").split(" ") body = request.get_data() # bytes, not reformatted if not msg_id or not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300: abort(400) key = base64.b64decode(SECRET.removeprefix("whsec_")) digest = hmac.new(key, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256).digest() expected = base64.b64encode(digest).decode() if not any( part.startswith("v1,") and hmac.compare_digest(part[3:], expected) for part in signatures ): abort(401) event = json.loads(body) # Deduplicate by event["id"] and respond quickly. return "", 204 ``` ### PHP ```php 300) { http_response_code(400); exit; } $key = base64_decode(substr($secret, strlen('whsec_'))); $expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$body}", $key, true)); $valid = false; foreach ($signatures as $part) { [$version, $value] = array_pad(explode(',', $part, 2), 2, ''); if ($version === 'v1' && hash_equals($expected, $value)) { $valid = true; } } if (!$valid) { http_response_code(401); exit; } $event = json_decode($body, true); // Deduplicate by $event['id'] and respond quickly. http_response_code(204); ``` The official Standard Webhooks libraries (Node, Python, PHP, Go, Java, Ruby, C#, Rust) also verify Preflow's signature. ## Delivery - **At least once, no guaranteed order.** The same event may arrive more than once (e.g. your response got lost): deduplicate by `id`. To order a message's statuses, use `status_at`. - **Success is any 2xx within 10 s.** A 3xx (Preflow doesn't follow redirects), 4xx, 5xx, network error or timeout is a failure. Your response body is neither read nor stored. - **Retries** after 30 s, 2 min, 10 min, 30 min, 1 h, 3 h, 6 h, 12 h and 24 h (10 attempts over about 2 days). After that the delivery is marked `failed`; redeliver it from the screen or with `POST /v1/webhook-deliveries/{id}/retry`. - **At most 5 concurrent deliveries** per endpoint; while it is failing, one at a time. Preflow's delivery capacity is shared across endpoints: one server being down doesn't delay the others. - **An endpoint failing for 3 days in a row** (with no success in between and no gap of more than 25 h between failures) is disabled (`status: "disabled"`, `disabled_reason: "failing"`) and the workspace admins are notified. Fix it and re-enable it with `PATCH … { "status": "active" }`. - **A disabled endpoint receives nothing**: pending deliveries are cancelled and new events don't create deliveries for it. - **The endpoint belongs to whoever created it.** If that person stops being a workspace admin, or the key that created it is revoked, it is disabled (`disabled_reason: "creator_lost_access"`) and the admins are notified. Whoever re-enables it becomes responsible for it. - **Plan without API access** (Free plan): endpoints become `paused_plan` and nothing is sent. Deliveries are kept for up to 30 days and go out when the plan comes back; after that they are deleted along with the event and are never sent. - **30-day log** at `GET /v1/webhook-endpoints/{id}/deliveries`: status, HTTP code, duration and the latest attempts. Events and deliveries older than 30 days are deleted. `last_error`: `dns_or_address_refused` (the connection was never established: the name didn't resolve, it resolved to an internal, private or Preflow address, the port refused or didn't respond, or TLS failed; Preflow doesn't say which, so the log doesn't reveal network names and ports), `timeout` or `connection_failed` (after connecting, the response took more than 10 s or the connection dropped), `redirect_not_followed`, `http_error`, `invalid_response` or `event_scope_missing`. ## Rotate the secret `POST /v1/webhook-endpoints/{id}/rotate-secret` returns the new secret. For 24 h every notification carries both signatures (the new secret's and the previous one's): swap the secret on your server within that period and nothing is lost. Another rotation within those 24 h is refused (`webhook_rotation_in_progress`). ## Test 1. Register the endpoint and store the secret. 2. Click "Test" on the screen, or call `POST /v1/webhook-endpoints/{id}/test` (up to 5 per minute per endpoint). 3. Within ~10 s a signed `webhook.test` arrives. Check the status and the HTTP code your server returned in `GET /v1/webhook-endpoints/{id}/deliveries` (or under "Deliveries" on the screen). --- # Receive leads from your website > Send Preflow the conversions from your website form, landing page or app with POST /v1/inbound-submissions: MQL, attribution and Inbound cadence. Scopes: `leads:write` to record and `leads:read` to read the conversion. When a **person asks to be contacted** (a form on your website, a landing page, an app, your own chat), send the conversion to `POST /v1/inbound-submissions`. It follows the same path as a Preflow form: - it becomes an **MQL** and the account moves to Qualified; - the answers are stored on the lead and the source (UTM, campaign, page) goes into attribution and the marketing dashboards; - the workspace's Inbound settings decide the cadence, who handles it and who is notified, and the routing rules receive `campaign` and `utm_campaign`. ```bash curl https://api.preflow.sale/v1/inbound-submissions \ -H "Authorization: Bearer $PREFLOW_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "submission_id": "site-form-8812", "contact": { "name": "Ana Souza", "email": "ana@empresa.com.br", "phone": "+5511999998888", "company": "Acme" }, "answers": [ { "key": "team_size", "label": "How many people are on your sales team?", "value": "11-50" } ], "campaign": "black-friday-2026", "attribution": { "utm_source": "google", "utm_medium": "cpc", "utm_campaign": "black-friday-2026", "landing_url": "https://empresa.com.br/contato" }, "consent": { "granted": true, "text": "I agree to be contacted by Acme." } }' ``` ```json { "id": "6e0b…", "object": "inbound_submission", "submission_id": "site-form-8812", "status": "completed", "result": "lead_created", "lead_id": "9b2c…", "contact_id": null, "qualified": true, "mql_applied": true, "matched_by": null, "inbound_cadence": { "started": true, "reason": "distribution", "cadence_id": "4f1e…" }, "form_id": null, "occurred_at": "2026-11-18T13:05:00.000Z", "created_at": "2026-11-18T13:05:01.204Z", "completed_at": "2026-11-18T13:05:02.118Z" } ``` ## What happens in each case | `result` | When | What Preflow does | |---|---|---| | `lead_created` (`201`) | No one with that email, phone or LinkedIn | Creates the inbound lead as an MQL and starts the Inbound cadence | | `lead_updated` | The lead already existed and is not being handled | Fills in missing data, records the MQL and starts the cadence | | `lead_unchanged` | The lead is lost, won, archived, already in a cadence, or was qualified by a person | Only records the conversion in the history and attribution; nothing is reopened | | `contact_only` | `"qualified": false`, or the `form_id` form did not produce an MQL | Stores it as a contact only, with no lead, owner or cadence | - **MQL by default.** Every conversion is a marketing MQL, like a form with questions. Send `"qualified": false` for people who should not be approached yet. - **Use a Preflow form's rules.** With `form_id` (a form published in Marketing), the answers use that form's field ids, its MQL rules decide, and its funnel and campaign apply. - **`funnel_id`** picks the lead's funnel; **`campaign`** is the slug of a Preflow campaign. - **`submission_id`** is the conversion's id in your system. Sending the same `submission_id` again returns the same conversion (`200`), with any `Idempotency-Key`. If the response is `202` (uncertain outcome), repeat with the same `submission_id`: the conversion resumes without duplicating. - **`occurred_at`** is when the person converted (up to 30 days ago). An old conversion never overrides what a person decided after it. - **`attribution.fbc` / `fbp` / `fbclid`**: with Meta connected, the conversion is also sent to Meta's Conversions API. - The form's key can have only `leads:write`: the response then has no lead data and no `matched_by`. With `leads:read`, it also includes `lead`. - Dedicated limit: 120 conversions per minute per key. Answers add up to 64 KB at most, and text with a control character (other than tab and line break) is rejected with `400`. - A contact who asked not to be contacted (global, agency or workspace suppression) is rejected with `422 lead_suppressed` before anything is recorded. - When it finishes, the `inbound.submission_received` webhook is sent (see [Events](https://developers.preflow.sale/en/events/#leads-accounts-and-meetings)). ## Conversion API or `POST /v1/leads`? | Use | When | |---|---| | `POST /v1/inbound-submissions` | A person asked to be contacted just now (form, landing page, app). It counts as the lead's entry, becomes an MQL and goes into attribution | | [`POST /v1/leads`](https://developers.preflow.sale/en/guides/leads/#create-a-lead) | Your system has a record to bring into Preflow (ERP, CRM, import). The lead comes in without an MQL and existing leads don't change | ## From your website form to the API The key is secret: the website form sends the data to **your** server, and your server calls Preflow. Example in Node (Express): ```js app.post('/contact', express.json(), async (req, res) => { const response = await fetch('https://api.preflow.sale/v1/inbound-submissions', { method: 'POST', headers: { Authorization: `Bearer ${process.env.PREFLOW_API_KEY}`, 'Idempotency-Key': crypto.randomUUID(), 'Content-Type': 'application/json', }, body: JSON.stringify({ submission_id: req.body.form_submission_id, contact: { name: req.body.name, email: req.body.email, phone: req.body.phone }, answers: [{ key: 'message', label: 'Message', value: req.body.message }], attribution: { utm_source: req.body.utm_source, utm_campaign: req.body.utm_campaign, landing_url: req.get('referer') }, }), }); res.status(response.ok ? 200 : 502).end(); }); ``` Send `utm_*` only when there is a value: empty fields are ignored, unknown fields are rejected (`400`). --- # Authentication and scopes > A secret key per workspace, the Authorization header and the scopes each route requires. 1. In **Settings → Integrations → API & webhooks**, a workspace admin or owner creates a key, gives it a name and selects its scopes. 2. The key is shown **only once**. Store it in the secret vault of the server that calls the API. 3. Send it with every request: ```http Authorization: Bearer pf_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` ## Key rules - It belongs to **one** workspace. Every call acts on that workspace; nothing in the body or the URL changes that. - It can only do what its **scopes** allow (table below). - Once revoked, it stops working immediately. It is also revoked automatically when the person who created it is no longer a workspace admin. - Available on **paid plans** (and for clients funded by their agency). On the Free plan and on Try, the key responds `plan_upgrade_required`; once you subscribe, the same key works again. - It is for server-to-server use. Never put the key in your website, your mobile app or any code that runs on your customer's machine. Check your key with `GET /v1/me` ([Quickstart](https://developers.preflow.sale/en/quickstart/)). ## Scopes | Scope | Allows | |---|---| | `whatsapp:read` | Read lines, templates, the 24-hour window, messages and media | | `whatsapp:send` | Send WhatsApp messages and upload files | | `leads:read` | Look up leads and read their timeline | | `leads:write` | Create leads | | `accounts:read` | Read accounts, stages, owners and funnels | | `meetings:read` | Read meetings | | `cadences:read` | List cadences | | `cadences:write` | Enroll a lead in a cadence and stop the lead's cadence | | `webhooks:manage` | Create and manage webhooks | A route outside the key's scopes responds `403 insufficient_scope`, with the missing scope in `details.required_scope`, before anything happens. In the [API reference](https://developers.preflow.sale/en/reference/), each route shows the scope it requires (`x-required-scope`). ## Conventions - JSON in UTF-8. Send `Content-Type: application/json` on requests with a body. - Ids are UUIDs. Dates are ISO-8601, in UTC. Phone numbers are E.164 (`+5511999998888`). - Every response includes `X-Request-Id`. Give this value to support. - Bodies up to 1 MB. --- # Idempotency > Every write requires an Idempotency-Key; repeating the same request never runs it twice. Every `POST`, `PATCH` and `DELETE` requires the `Idempotency-Key` header: a value that is unique per operation, for example a UUID generated by your system. ```http Idempotency-Key: 2f1d9a52-0b6c-4c3e-9d8e-7a1b2c3d4e5f ``` - Repeating the **same request** with the same key within 24 h returns the same response without running it again (header `Idempotent-Replayed: true`). Use this to retry safely after a network error. - The same key with a **different body** responds `409 idempotency_conflict`. - While the first request is still running, it responds `409 request_in_progress`. - A transient refusal (`retryable: true`, such as `503`) releases the key: the retry runs again. - If the outcome is uncertain (for example, the provider didn't respond), the response is `202` with `"status": "unknown"` and retrying with the same key responds `409 request_outcome_unknown`. Nothing runs twice. Check the resource before trying again with a different key. ## Best practice Derive the key from what the operation means in your system (for example `order-1234-shipped`): that way a retry from your own process never sends the same message twice. --- # Pagination > Cursor-based lists, with limit and next_cursor. Lists use a cursor: `?limit=` (1 to 100, default 50) and `&cursor=` with the `next_cursor` from the previous page. ```json { "data": [ … ], "next_cursor": "eyJ…" } ``` - `next_cursor: null` means it's the last page. - Use the cursor exactly as you received it. A modified cursor, or one from another list, responds `400 invalid_cursor`. - To sync leads and accounts, combine `updated_since` with the cursor (see [Leads, accounts and cadences](https://developers.preflow.sale/en/guides/leads/#search-and-sync)). --- # Rate limits > Request limits per key and per line, RateLimit headers and the 429 error. | Limit | Value | |---|---| | Requests per key | 600 per minute | | WhatsApp sends | 60 per minute per key and 60 per minute per line | | Leads created (`POST /v1/leads`) | 60 per minute per key | | Conversions (`POST /v1/inbound-submissions`) | 120 per minute per key | | Cadence enrollments | 60 per minute per key | | Files (`POST /v1/files`) | 60 per minute and 1,000 per day per key | | Webhook tests | 5 per minute per endpoint (20 per workspace) | | Webhook redeliveries | 10 per minute per endpoint | | Webhook endpoint creation | 30 per hour | Every response includes `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` (seconds until the window resets). Over the limit: `429 rate_limited` with `Retry-After`. Wait that long and retry with the same `Idempotency-Key`. Bodies up to 1 MB; media files up to 16 MB. --- # Environments > Production and staging, each with its own base URL and its own keys. | Environment | Base URL | Key | |---|---|---| | Production | `https://api.preflow.sale/v1` | `pf_live_…` | | Staging | `https://api-hml.preflow.sale/v1` | `pf_test_…` | - A key only works in the environment where it was created. Using a key from one environment in the other responds `401 invalid_api_key`. - In production, messages are really sent and cost credits. To test your integration without reaching customers, use a test workspace. - The **Test Request** button in the [API reference](https://developers.preflow.sale/en/reference/) calls production through this site's proxy. For staging, use your terminal. --- # Versioning > The version is in the URL, compatible changes can ship at any time and breaking changes go to /v2. - The version is in the URL (`/v1`). - New fields and routes can appear at any time. Ignore fields you don't recognize, and handle new enum values (statuses, event types) without breaking. - A change that breaks integrations becomes `/v2`, and `/v1` keeps working for at least 6 months after the announcement. - Everything that changed is in the [Changelog](https://developers.preflow.sale/en/changelog/). --- # Errors > A single error format, when to retry and the full catalog of codes. Every error has the same format: ```json { "error": { "code": "insufficient_scope", "message": "The key does not have the scope required for this route.", "request_id": "req_6f1c2b0e8a7d4c3b9e2f1a0d5c4b3a29", "retryable": false, "details": { "required_scope": "whatsapp:send" } } } ``` - Branch on `code`, which is stable. `message` is meant for people and may change. - Retry only when `retryable` is `true`, and with the same `Idempotency-Key`. - Give the `request_id` to support. ## Catalog This table is generated from the API code on every release, so every code the API can return is listed here. ### General | HTTP | `code` | When | What to do | Retry | |---|---|---|---|---| | 400 | `idempotency_key_required` | POST, PATCH or DELETE without `Idempotency-Key` | Send the header | No | | 400 | `invalid_cursor` | The `cursor` was changed or belongs to another list | Use the previous page's `next_cursor` as is | No | | 400 | `invalid_idempotency_key` | Key longer than 255 characters or with characters outside visible ASCII | Use a UUID | No | | 400 | `invalid_json` | The body is not JSON | Fix the request | No | | 400 | `invalid_request` | A field is invalid or missing (`details.fields`) | Fix the request | No | | 401 | `api_key_revoked` | The key was revoked | Create another key | No | | 401 | `authentication_required` | No `Authorization: Bearer` header | Send the key | No | | 401 | `invalid_api_key` | Malformed or unknown key | Check the key and the environment (`pf_live_` in production) | No | | 403 | `insufficient_scope` | The key lacks the route's scope (`details.required_scope`). For webhooks, subscribing to or reading an event type also requires its module's read scope | Create a key with that scope | No | | 403 | `plan_upgrade_required` | The workspace plan has no API access (Free, Try) | Subscribe to a paid plan; the same key starts working again | No | | 403 | `workspace_archived` | The key's workspace was archived | Use a key from another workspace | No | | 404 | `lead_not_found` | The `lead_id` is not a lead of this workspace | Check the id | No | | 404 | `not_found` | The resource does not exist in this workspace | Check the id | No | | 404 | `route_not_found` | The route does not exist | Check the path and the version | No | | 405 | `method_not_allowed` | Method not accepted (see the `Allow` header) | Use the right method | No | | 409 | `idempotency_conflict` | The `Idempotency-Key` was already used with a different body | Generate a new key for the new operation | No | | 409 | `request_in_progress` | The request with this key is still running | Try again shortly | Sometimes (check `retryable`) | | 409 | `request_outcome_unknown` | The request with this key finished without a confirmed outcome | Check the resource before retrying with another key | No | | 413 | `payload_too_large` | Body over 1 MB, or file over 16 MB | Reduce the size | No | | 415 | `unsupported_media_type` | Body without `Content-Type: application/json` | Send the header | No | | 429 | `rate_limited` | Limit reached (`Retry-After`). Includes the webhook test, retry and creation limits (`details.bucket`) | Wait for the time in `Retry-After` | Yes | | 500 | `internal_error` | Unexpected error | For writes, check the resource before repeating | Yes | | 503 | `temporarily_unavailable` | Temporarily unavailable | Try again with the same `Idempotency-Key` | Yes | ### WhatsApp and files | HTTP | `code` | When | What to do | Retry | |---|---|---|---|---| | 402 | `insufficient_credits` | Not enough credits to send | Top up credits | No | | 404 | `file_not_found` | The `media.file_id` is not a file of this workspace | Upload it again with `POST /v1/files` | No | | 404 | `sender_not_found` | `from` is not a line of this workspace | Use an id from `GET /v1/whatsapp/senders` | No | | 404 | `template_not_found` | No template with that name | Check `GET /v1/whatsapp/templates` | No | | 409 | `contact_blocked` | Contact closed, lost, left the company, or from your own company | Talk to the team in Preflow | No | | 409 | `contact_paused` | The contact is paused until a date (`details.until`) | Try after that date | No | | 409 | `privacy_suppressed` | The contact asked not to receive messages | Do not send | No | | 409 | `sender_unavailable` | The line is not ready (disconnected, paused for quality or being set up) | Use another line or fix it in Preflow | No | | 422 | `file_not_uploaded` | The bytes were not sent to the upload URL | `PUT` the file before sending the message | No | | 422 | `invalid_phone` | Phone number not in E.164 | Use `+5511999998888` | No | | 422 | `media_type_not_allowed` | File type not accepted (`details.allowed`) | Convert the file | No | | 422 | `provider_rejected` | WhatsApp rejected the message; nothing was charged | Check the number and the content | No | | 422 | `send_refused` | Preflow refused the send for another reason | Contact support with the `request_id` | No | | 422 | `sender_required` | No `from` and no default line on the key | Send `from` or set the default line | No | | 422 | `template_not_approved` | The template is not approved for the line's provider | Wait for approval | No | | 422 | `template_unavailable_on_sender` | A WhatsApp Business app (phone) line cannot send templates | Use another line | No | | 422 | `template_variables_invalid` | Variables are missing (`details.missing`) | Fill in all of them | No | | 422 | `whatsapp_window_closed` | Text or media outside the 24-hour window (`details.last_inbound_at`) | Use an approved template | No | ### Leads, accounts, cadences and meetings | HTTP | `code` | When | What to do | Retry | |---|---|---|---|---| | 403 | `integration_actor_unavailable` | Whoever created the key can no longer enroll leads in the workspace | Ask an admin for a new key | No | | 404 | `cadence_not_found` | The cadence is not from this workspace or was archived | Use an id from `GET /v1/cadences` | No | | 404 | `lead_merged` | The lead was merged into another (`details.merged_into`) | Use the lead in `details.merged_into` from now on | No | | 409 | `cadence_born_cancelled` | Every step would be created cancelled (`details.reason`) | Check the reason; nothing was enrolled | No | | 409 | `cadence_enrollment_refused` | Any other enrollment refusal | Check the lead and try again with another `Idempotency-Key` | No | | 409 | `cadence_no_tasks_created` | No step can be created (`details.skipped_channels`) | Complete the lead's contact data (email, phone) or use another cadence | No | | 409 | `cadence_operator_unavailable` | The lead's account has no one to run the cadence (`details.reason`: `missing_cadence_operator`, `cadence_operator_conflicts_with_account_owner`, `cadence_operator_not_eligible`, `human_account_owner_not_eligible` or `ai_cadence_requires_human_account_owner`) | Set the account's pre-sales owner | No | | 409 | `external_id_in_progress` | Another request is creating the lead for this `external_id` right now | Try again shortly; the response returns the lead the other request created | Sometimes (check `retryable`) | | 409 | `lead_already_in_cadence` | The lead is already in this cadence | Nothing to do | No | | 409 | `lead_archived` | The lead is archived | Reopen the lead in Preflow | No | | 409 | `lead_engagement_paused` | The lead replied recently (`details.until`) | Try after `details.until` | No | | 409 | `lead_in_active_conversation` | The lead is in an ongoing conversation | Try after the conversation ends | No | | 409 | `lead_not_eligible_for_cadence` | The lead cannot enter a cadence now (`details.reason`: `lead_do_not_contact_until`, `lead_passed_meeting_stage`, `lost_cooldown`, `lost_reprospect_not_eligible`, `status_not_appendable`, `meeting_reprospect_not_eligible`, `not_eligible`) | Check the reason; `lost_cooldown` includes `details.cooldown_until` | No | | 422 | `cadence_has_no_steps` | The cadence has no steps | Use another cadence | No | | 422 | `lead_suppressed` | The contact asked not to be contacted (privacy). Also refuses conversions from `POST /v1/inbound-submissions`, before anything is recorded | Do not create the lead again | No | ### Conversions (POST /v1/inbound-submissions) | HTTP | `code` | When | What to do | Retry | |---|---|---|---|---| | 409 | `submission_id_conflict` | The `submission_id` was already used with different content | Use a new `submission_id` for a new conversion | No | | 409 | `submission_in_progress` | Another request is recording the same conversion right now | Try again shortly | Sometimes (check `retryable`) | | 422 | `answers_invalid` | With `form_id`: an answer for a field that does not exist, outside the options, or a required field left empty (`details.fields`) | Match the answers to the form | No | | 422 | `campaign_not_found` | `campaign` is not the slug of a campaign of this workspace (or it is archived) | Check the campaign slug | No | | 422 | `form_not_found` | `form_id` is not a published form of this workspace | Check the form id | No | | 422 | `funnel_not_found` | `funnel_id` is not an active funnel of this workspace | Use an id from `GET /v1/funnels` | No | ### Webhooks | HTTP | `code` | When | What to do | Retry | |---|---|---|---|---| | 400 | `invalid_webhook_url` | URL that is not `https://`, has a user and password, or is longer than 2048 characters | Fix the URL | No | | 400 | `unknown_event_type` | Event not in the catalog | Check `GET /v1/event-types` | No | | 400 | `webhook_url_not_allowed` | Internal, private, metadata or Preflow address | Use a public URL of your system | No | | 409 | `webhook_delivery_already_succeeded` | Retry of a delivery that already succeeded | Nothing to do: the event already arrived | No | | 409 | `webhook_delivery_in_progress` | The delivery is being sent right now | Try again shortly | No | | 409 | `webhook_endpoint_limit_reached` | The workspace already has 10 endpoints | Delete an endpoint | No | | 409 | `webhook_endpoint_not_active` | Test or retry on an endpoint that is disabled or paused by the plan | Turn the endpoint back on | No | | 409 | `webhook_rotation_in_progress` | The secret was rotated less than 24 h ago | Wait for the previous one to expire | No | --- # Events > Catalog of Preflow webhook events and the data format of each one. Every event arrives by [webhook](https://developers.preflow.sale/en/guides/webhooks/) in the same envelope and can be retrieved for 30 days with `GET /v1/events/{id}`. The list of what an endpoint can subscribe to in your workspace is at `GET /v1/event-types`. ## Envelope Every webhook is a `POST` with `Content-Type: application/json` and this envelope: ```json { "id": "evt_9b2f0c1d4e5a46b7a8c9d0e1f2a3b4c5", "type": "whatsapp.message.received", "created_at": "2026-11-16T15:04:05.123Z", "workspace_id": "6e0b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d", "data": { } } ``` Headers ([Standard Webhooks](https://www.standardwebhooks.com) spec): | Header | Value | |---|---| | `webhook-id` | The event `id`. It is the **same** on every attempt: use it to deduplicate. | | `webhook-timestamp` | Unix seconds of this attempt. | | `webhook-signature` | `v1,`; for 24 h after a secret rotation, two of them, separated by a space. | ## WhatsApp ### `whatsapp.message.received` A message received on one of the workspace's lines (from a lead or a contact). ```json { "id": "evt_…", "type": "whatsapp.message.received", "created_at": "2026-11-16T15:04:05.123Z", "workspace_id": "6e0b1c2d-…", "data": { "id": "0d9c8b7a-6f5e-4d3c-8b2a-1f0e9d8c7b6a", "conversation_id": "5a4b3c2d-1e0f-4a9b-8c7d-6e5f4a3b2c1d", "direction": "inbound", "status": "received", "type": "text", "text": "Hi, I'd like to know the price", "from": "+5511999990000", "to": "+5511888880000", "media": null, "template": null, "lead_id": "7c6b5a49-3827-4615-9a8b-7c6d5e4f3a2b", "contact_id": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "created_at": "2026-11-16T15:04:05.001Z" } } ``` `from` is the contact and `to` is the line (E.164). With a file, `type` is `image`, `audio`, `video`, `document` or `sticker`, and `media` carries `{ id, type, mime_type, file_name }` so you can download it through the WhatsApp API. ### `whatsapp.message.sent` A message was sent (accepted by the provider), from any source. Same fields, with `direction: "outbound"`, `from` = line, `to` = contact, plus: | Field | Value | |---|---| | `origin` | `api` (your integration), `cadence` (a cadence step), `ai` (an AI reply), `human` (a person in Preflow) or `whatsapp_app` (the WhatsApp Business app on a phone). Same value as in the API's message history. | | `client_reference` | Only with `origin: "api"`: the value you sent with the message | | `api_message_id` | Only with `origin: "api"` | A message the provider refused right away doesn't trigger `sent` (the API send call already responds with the error). ### `whatsapp.message.status_updated` A sent message was delivered, read or failed. Same fields as the message, plus: ```json { "status": "failed", "previous_status": "sent", "status_at": "2026-11-16T15:05:00Z", "failure": { "reason": "window_closed" } } ``` `status`: `delivered`, `read` or `failed`. Each status arrives once per message. `failure.reason` (only on `failed`): `window_closed` (outside the 24-hour window, a template is required), `invalid_recipient`, `recipient_opted_out`, `not_delivered_by_whatsapp` (WhatsApp decided not to deliver it), `rate_limited`, `template_error`, `media_error` or `delivery_failed`. ### `whatsapp.template.status_updated` ```json { "id": "2b3c4d5e-6f70-4a8b-9c0d-1e2f3a4b5c6d", "name": "boas_vindas", "language": "pt_BR", "category": "UTILITY", "provider": "meta", "status": "approved", "previous_status": "pending", "reason": null } ``` `status`: `approved`, `pending`, `rejected` or `archived`. ### `webhook.test` Sent by "Test" on the screen or by `POST /v1/webhook-endpoints/{id}/test`, only to that endpoint: `data` = `{ "endpoint_id": "…", "message": "Evento de teste do Preflow." }`. ## Leads, accounts and meetings Each event's `data` is a snapshot of the resource at the time of the event, in the same format as the corresponding `GET` routes; use the `id` to fetch the current state. | Event | When | `data` | |---|---|---| | `lead.created` | A new lead in the workspace (from any source, not only the API) | `{ lead }` | | `inbound.submission_received` | A conversion recorded by `POST /v1/inbound-submissions` (new lead, existing lead or contact only) | `{ inbound_submission }` | | `lead.lost` | A lead was marked as lost | `{ lead, reason, reason_label, scope, lost_at }` | | `account.stage_changed` | The account changed stage in a funnel | `{ account, funnel_id, product_id, from_stage, to_stage, intermediate_stage, changed_at }` | | `account.qualification_changed` | The account's qualification changed (e.g. it became Customer or Churn) | `{ account, from, to, changed_at }` | | `meeting.scheduled` | A meeting was booked | `{ meeting }` | | `meeting.rescheduled` | A meeting's time changed | `{ meeting, previous_starts_at }` | | `meeting.cancelled`, `meeting.completed`, `meeting.no_show` | A meeting was cancelled, held or a no-show | `{ meeting }` | - `scope` on `lead.lost`: `lead` (only this person) or `funnel` (the account leaves that funnel). - An account entering its first funnel doesn't trigger `account.stage_changed`: `lead.created` already covers it. - Blocks copied from Outlook or Google calendars don't trigger meeting events, and onboarding test leads don't trigger `lead.created`. ```json { "id": "evt_…", "type": "account.stage_changed", "created_at": "2026-11-16T15:00:00.000Z", "workspace_id": "6c1f…", "data": { "account": { "id": "4007…", "object": "account", "name": "Acme", "qualification": "sql", "…": "…" }, "funnel_id": "0aff…", "product_id": null, "from_stage": "qualified", "to_stage": "scheduled", "intermediate_stage": null, "changed_at": "2026-11-16T14:59:58.120Z" } } ``` --- # Changelog > What changed in the Preflow public API, release by release. ## v1 — inbound conversions - `POST /v1/inbound-submissions`: records the conversion of a person who asked to be contacted (website form, landing page, app). It follows the same path as a Preflow form: MQL by default (`"qualified": false` for a contact only), answers on the lead, attribution (UTM, campaign, page, Meta cookies), Inbound cadence. A lost, won, archived or already-handled lead only gets the record. `form_id` applies a Preflow form's MQL rules. `submission_id` is unique in the workspace. Limit of 120 per minute per key. Guide: [Receive leads from your website](https://developers.preflow.sale/en/guides/website-leads/). - `GET /v1/inbound-submissions/{id}`. - `inbound.submission_received` webhook. - The event type catalog in the OpenAPI spec (`WebhookEventTypeName`) now lists the lead, account and meeting events, which already existed. ## v1 — WhatsApp (2026-11-16) - `GET /v1/whatsapp/senders`, `GET /v1/whatsapp/templates`, `GET /v1/whatsapp/window`. - `POST /v1/files` (upload through a signed URL, up to 16 MB). - `POST /v1/whatsapp/messages` (text, approved template or media, to a phone number or a lead), `GET /v1/whatsapp/messages/{id}` (delivery status), `GET /v1/whatsapp/messages?to=` (history) and `GET /v1/whatsapp/messages/{id}/media`. - Default line per key, chosen on the keys screen. ## v1 — webhooks (2026-11-16) - Webhook endpoints (up to 10 per workspace) with the `webhooks:manage` scope: create, edit, disable/re-enable, delete, new secret (the previous one stays valid for 24 more hours), test, 30-day delivery log and redelivery. - Events `whatsapp.message.received`, `whatsapp.message.sent`, `whatsapp.message.status_updated` and `whatsapp.template.status_updated`, signed per the Standard Webhooks spec, delivered at least once with retries for about 2 days. Guide in [Webhooks](https://developers.preflow.sale/en/guides/webhooks/). - `GET /v1/event-types` and `GET /v1/events/{id}`. - Subscribing to or reading an event type also requires the read scope of its module (`whatsapp:read`, `leads:read`, `accounts:read`, `meetings:read`). - Redelivery refuses a delivery that already succeeded and accepts up to 10 per minute per endpoint; a failure before the TLS connection shows up only as `dns_or_address_refused`. ## v1 — foundation (2026-11-16) - Secret keys per workspace (`pf_live_` / `pf_test_`), with scopes, created and revoked in Settings → Integrations → API & webhooks. - Only a workspace admin or owner can create and revoke keys; a key stops working when the person who created it is no longer an admin. - `GET /v1/me` and `GET /v1/openapi.json`. - Idempotency on every write, a limit of 600 requests per minute per key and a single error format. ## v1 — leads, accounts, funnels, cadences and meetings - `POST /v1/leads`: creates a lead that comes in as inbound and follows the workspace's Inbound settings. Accepts phone-only leads; `external_id` is unique per workspace. - `GET /v1/leads`, `GET /v1/leads/{id}` and `GET /v1/leads/{id}/activities`. - `GET /v1/accounts`, `GET /v1/accounts/{id}` and `GET /v1/funnels`. - `GET /v1/cadences`, `POST /v1/leads/{id}/cadence-enrollments` and `POST /v1/leads/{id}/cadence-stop`. - `GET /v1/meetings` and `GET /v1/meetings/{id}`.