> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kycert.com.br/llms.txt
> Use this file to discover all available pages before exploring further.

# Criar cliente

> Cria um cliente (PF ou PJ) no tenant. Opcionalmente dispara um bureau run.

Se `run_bureau: true`, o comportamento é idêntico ao `POST /bureau/runs`:
o bureau é executado imediatamente e o resultado é entregue via webhook.

Requer escopo `customers:write`.


## Quando usar

Use este endpoint para registrar um cliente no kycert antes ou independentemente de rodar um bureau. Ideal para fluxos em que o cadastro acontece em etapas separadas da verificação KYC.

| Cenário                                 | Endpoint recomendado                            |
| --------------------------------------- | ----------------------------------------------- |
| Cadastrar + verificar em uma chamada    | `POST /api/v1/customers` com `run_bureau: true` |
| Verificar sem criar cadastro permanente | `POST /api/v1/bureau/runs`                      |
| Cadastrar agora, verificar depois       | `POST /api/v1/customers` (sem `run_bureau`)     |

## Campo `doc` na resposta

O CPF ou CNPJ nunca é retornado em claro. A resposta sempre retorna uma versão mascarada:

* CPF: `***456789**`
* CNPJ: `**34567890****`

## Campo `run_bureau`

Quando `run_bureau: true`, o bureau é disparado imediatamente após criar o cliente. O comportamento é idêntico ao `POST /api/v1/bureau/runs` e o resultado chega via webhook.

Veja [Conceitos — Run](/conceitos) para entender o ciclo de vida de um run.


## OpenAPI

````yaml POST /api/v1/customers
openapi: 3.0.3
info:
  title: kycert API
  version: '2026-06-03'
  description: >
    API KYC/AML para corretoras de câmbio autorizadas pelo Banco Central do
    Brasil.

    Permite rodar verificações de bureau em CPF ou CNPJ e receber o resultado
    via webhook.


    **Fluxo principal:**

    ```

    POST /runs → 202 (run_id) → [bureau processa 5–30s] → webhook entregue →
    agir

    ```
  contact:
    name: kycert
    url: https://kycert.com.br
  license:
    name: Proprietário
    url: https://kycert.com.br
servers:
  - url: https://admin.kycert.com.br
    description: Produção (sk_live_...)
  - url: https://admin.kycert.com.br
    description: Sandbox (sk_test_...)
security:
  - ApiKeyHeader: []
  - BearerToken: []
tags:
  - name: Runs
    description: Execução de bureau para CPF ou CNPJ
  - name: Customers
    description: Gestão de clientes do tenant
paths:
  /api/v1/customers:
    post:
      tags:
        - Customers
      summary: Criar cliente
      description: >
        Cria um cliente (PF ou PJ) no tenant. Opcionalmente dispara um bureau
        run.


        Se `run_bureau: true`, o comportamento é idêntico ao `POST
        /bureau/runs`:

        o bureau é executado imediatamente e o resultado é entregue via webhook.


        Requer escopo `customers:write`.
      operationId: createCustomer
      parameters:
        - name: x-kycert-api-version
          in: header
          required: false
          schema:
            type: string
            example: '2026-06-03'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateCustomerRequest'
            example:
              type: pf
              doc: '12345678901'
              name: João Silva
              email: joao@example.com
              run_bureau: true
              template_id: 550e8400-e29b-41d4-a716-446655440000
              webhook_url: https://broker.com/webhooks/kycert
              external_id: cust_abc123
              metadata:
                channel: app_mobile
      responses:
        '201':
          description: Cliente criado com sucesso
          headers:
            X-Request-Id:
              schema:
                type: string
                format: uuid
            X-Kycert-Api-Version:
              schema:
                type: string
            X-RateLimit-Limit:
              schema:
                type: integer
            X-RateLimit-Remaining:
              schema:
                type: integer
            X-RateLimit-Reset:
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateCustomerResponse'
              example:
                customer_id: 661e9511-f3ac-52e5-b827-557766551111
                object: customer
                status: em_analise
                type: pf
                name: João Silva
                email: joao@example.com
                doc: '***456789**'
                external_id: cust_abc123
                metadata:
                  channel: app_mobile
                created_at: '2026-06-12T14:00:00Z'
                run_id: 550e8400-e29b-41d4-a716-446655440000
                bureau_status: queued
                livemode: true
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          $ref: '#/components/responses/PaymentRequired'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/InternalError'
      x-codeSamples:
        - lang: cURL
          label: cURL
          source: |
            curl -X POST https://admin.kycert.com.br/api/v1/customers \
              -H "x-api-key: $KYCERT_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "type": "pf",
                "doc": "12345678901",
                "name": "João Silva",
                "email": "joao@example.com",
                "run_bureau": true,
                "template_id": "550e8400-e29b-41d4-a716-446655440000",
                "webhook_url": "https://broker.com/webhooks/kycert"
              }'
        - lang: Node
          label: Node.js
          source: >
            const res = await
            fetch('https://admin.kycert.com.br/api/v1/customers', {
              method: 'POST',
              headers: {
                'x-api-key': process.env.KYCERT_API_KEY,
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                type: 'pf',
                doc: '12345678901',
                name: 'João Silva',
                email: 'joao@example.com',
                run_bureau: true,
                template_id: '550e8400-e29b-41d4-a716-446655440000',
                webhook_url: 'https://broker.com/webhooks/kycert',
              }),
            })

            const { customer_id, run_id } = await res.json()

            console.log(customer_id, run_id)
components:
  schemas:
    CreateCustomerRequest:
      type: object
      required:
        - type
        - doc
        - name
      properties:
        type:
          type: string
          enum:
            - pf
            - pj
          description: Tipo do cliente — pessoa física ou jurídica
        doc:
          type: string
          description: CPF (11 dígitos) ou CNPJ (14 dígitos), sem formatação
          example: '12345678901'
        name:
          type: string
          minLength: 2
          maxLength: 300
          description: Nome completo (PF) ou razão social (PJ)
        email:
          type: string
          format: email
          description: Email do cliente. Obrigatório para PF.
        phone:
          type: string
          description: Telefone do cliente. Opcional.
        birth_date:
          type: string
          format: date
          description: Data de nascimento no formato YYYY-MM-DD (apenas PF)
        address:
          type: object
          description: Endereço do cliente
          properties:
            street:
              type: string
            number:
              type: string
            city:
              type: string
            state:
              type: string
              minLength: 2
              maxLength: 2
              description: UF (2 caracteres)
            zip:
              type: string
        external_id:
          type: string
          maxLength: 255
          description: >-
            Seu identificador interno para este cliente. Deve ser único no
            tenant.
        metadata:
          type: object
          additionalProperties:
            type: string
            maxLength: 500
          maxProperties: 10
          description: Até 10 pares chave-valor string
        run_bureau:
          type: boolean
          description: |
            Se true, dispara um bureau run imediatamente após criar o cliente.
            Requer `template_id`.
        template_id:
          type: string
          format: uuid
          description: |
            ID do template de bureau (obrigatório quando `run_bureau: true`)
        webhook_url:
          type: string
          format: uri
          description: >
            URL HTTPS para entrega do resultado do bureau (quando `run_bureau:
            true`)
    CreateCustomerResponse:
      type: object
      properties:
        customer_id:
          type: string
          format: uuid
          description: Identificador único do cliente
        object:
          type: string
          enum:
            - customer
        status:
          type: string
          example: em_analise
        type:
          type: string
          enum:
            - pf
            - pj
        name:
          type: string
        email:
          type: string
        doc:
          type: string
          description: CPF/CNPJ mascarado — nunca retorna em claro
          example: '***456789**'
        external_id:
          type: string
          nullable: true
        metadata:
          type: object
          nullable: true
        created_at:
          type: string
          format: date-time
        run_id:
          type: string
          nullable: true
          format: uuid
          description: ID do run de bureau criado (presente apenas quando run_bureau=true)
        bureau_status:
          type: string
          nullable: true
          enum:
            - queued
          description: Status do bureau (presente apenas quando run_bureau=true)
        livemode:
          type: boolean
    ErrorResponse:
      type: object
      properties:
        error:
          type: object
          properties:
            type:
              type: string
              enum:
                - invalid_request_error
                - authentication_error
                - authorization_error
                - billing_error
                - server_error
            code:
              type: string
              description: Código específico do erro
            message:
              type: string
              description: Descrição legível do erro
            param:
              type: string
              nullable: true
              description: Campo que causou o erro (quando aplicável)
  responses:
    BadRequest:
      description: Requisição inválida — corrija os dados e tente novamente
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            missing_subject:
              summary: subject ausente
              value:
                error:
                  type: invalid_request_error
                  code: missing_subject
                  message: subject é obrigatório.
                  param: subject
            invalid_document:
              summary: CPF/CNPJ inválido
              value:
                error:
                  type: invalid_request_error
                  code: invalid_document
                  message: CPF (11 dígitos) ou CNPJ (14 dígitos) inválido.
                  param: subject.doc
            subject_type_mismatch:
              summary: tipo incompatível com template
              value:
                error:
                  type: invalid_request_error
                  code: subject_type_mismatch
                  message: Este template espera subject.type pj, recebido pf.
                  param: subject.type
            template_not_found:
              summary: template não encontrado
              value:
                error:
                  type: invalid_request_error
                  code: template_not_found
                  message: Template não encontrado.
                  param: template_id
            invalid_json:
              summary: JSON malformado
              value:
                error:
                  type: invalid_request_error
                  code: invalid_json
                  message: JSON inválido.
                  param: null
    Unauthorized:
      description: API key ausente ou inválida
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            missing_api_key:
              value:
                error:
                  type: authentication_error
                  code: missing_api_key
                  message: API key ausente.
                  param: null
            invalid_api_key:
              value:
                error:
                  type: authentication_error
                  code: invalid_api_key
                  message: API key inválida ou inativa.
                  param: null
    PaymentRequired:
      description: Saldo insuficiente ou billing suspenso
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              type: billing_error
              code: billing_suspended
              message: Saldo insuficiente para realizar a consulta.
              param: null
    Forbidden:
      description: Escopo insuficiente para esta operação
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              type: authorization_error
              code: insufficient_scope
              message: Esta chave não tem permissão para criar runs.
              param: null
    Conflict:
      description: Conflito — cliente com este CPF/CNPJ ou external_id já existe
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            customer_already_exists:
              summary: CPF/CNPJ já cadastrado
              value:
                error:
                  type: invalid_request_error
                  code: customer_already_exists
                  message: Cliente com este CPF/CNPJ já existe.
                  param: doc
                  existing_customer_id: 661e9511-f3ac-52e5-b827-557766551111
            external_id_conflict:
              summary: external_id duplicado
              value:
                error:
                  type: invalid_request_error
                  code: external_id_conflict
                  message: external_id já existe para este tenant.
                  param: external_id
                  existing_customer_id: 661e9511-f3ac-52e5-b827-557766551111
    RateLimited:
      description: Limite de requisições atingido — aguarde Retry-After
      headers:
        Retry-After:
          schema:
            type: integer
          description: Segundos a aguardar antes de tentar novamente
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              type: server_error
              code: rate_limit_exceeded
              message: Limite de uso da chave atingido.
              param: null
    InternalError:
      description: Falha interna — tente novamente com backoff exponencial
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              type: server_error
              code: internal_error
              message: Erro interno. Tente novamente.
              param: null
  securitySchemes:
    ApiKeyHeader:
      type: apiKey
      in: header
      name: x-api-key
      description: API key no header x-api-key (recomendado)
    BearerToken:
      type: http
      scheme: bearer
      description: API key como Bearer token no header Authorization

````