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

# Criar ou vincular pessoa ao chat

> WhatsApp ou Instagram. person_id vincula pessoa existente; sem ele, cria pessoa com os dados informados e vincula o contato do canal. Permissão da chave: crm/chats.update e crm/person.create. O acesso também respeita a empresa e as permissões do usuário criador da chave.



## OpenAPI

````yaml /openapi.json post /integrations/external/chats/{id}/create-person
openapi: 3.0.3
info:
  title: >-
    Integração Externa - Leads, Oportunidades, Tarefas, Arquivos, Propostas,
    Chats, Satisfação e Campos Personalizados
  version: 1.0.0
  description: >
    Documentação oficial da API externa da Wegly para campos personalizados,
    leads, oportunidades, tarefas, arquivos, propostas, chats e satisfação
    (`/integrations/external/custom-fields`, `/integrations/external/files`,
    `/integrations/external/leads`, `/integrations/external/deals`,
    `/integrations/external/tasks`, `/integrations/external/proposals`,
    `/integrations/external/chats` e `/integrations/external/satisfaction`).
    Todas as descrições estão em português e refletem as regras aplicadas pelo
    serviço.
servers:
  - url: https://api.wegly.com.br
    description: Ambiente de produção Wegly
security:
  - bearerAuth: []
tags:
  - name: Campos Personalizados
    description: >-
      Consulta dos campos personalizados disponíveis para uso nas integrações
      externas.
  - name: Arquivos
    description: >-
      Upload e consulta de arquivos vinculados diretamente a leads ou
      oportunidades. Arquivos de proposta usam as rotas de anexos em Propostas.
  - name: Leads
    description: >-
      Operações de listagem, criação, consulta e atualização de leads via
      integração externa.
  - name: Oportunidades
    description: Operações de criação de oportunidades (deals) via integração externa.
  - name: Tarefas
    description: >-
      Operações de listagem, criação, consulta, atualização e remoção de tarefas
      vinculadas a leads, oportunidades, entregas, pessoas, organizações ou
      clientes.
  - name: Satisfação
    description: >-
      Geração de links públicos para formulários de satisfação via integração
      externa.
  - name: Propostas
    description: >-
      Operações de listagem, criação, consulta, atualização e remoção de
      propostas via integração externa, incluindo seus anexos (arquivos e
      documentos da biblioteca).
  - name: Chats
    description: >-
      Operações principais de listagem, criação, consulta e resumo de não lidas
      de chats via integração externa.
paths:
  /integrations/external/chats/{id}/create-person:
    post:
      tags:
        - Chats
      summary: Criar ou vincular pessoa ao chat
      description: >-
        WhatsApp ou Instagram. person_id vincula pessoa existente; sem ele, cria
        pessoa com os dados informados e vincula o contato do canal. Permissão
        da chave: crm/chats.update e crm/person.create. O acesso também respeita
        a empresa e as permissões do usuário criador da chave.
      operationId: externalChatsCreatePerson
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
          description: UUID da conversa.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateExternalChatPerson'
      responses:
        '201':
          description: Operação realizada.
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: '#/components/schemas/ChatDetails'
                  - $ref: '#/components/schemas/ChatInstagramDetails'
        '400':
          description: Payload ou regra de negócio inválidos.
        '401':
          description: >-
            Chave de integração ausente, inválida, inativa ou expirada, ou
            domínio de origem não autorizado para a chave.
        '403':
          description: Permissão da chave ou do usuário insuficiente para o recurso.
        '404':
          description: Conversa ou recurso associado não encontrado no escopo acessível.
        '429':
          description: Limite de requisições da integração excedido.
        '500':
          description: Falha interna ou na comunicação com o provedor.
components:
  schemas:
    CreateExternalChatPerson:
      type: object
      properties:
        person_id:
          type: string
          format: uuid
          description: >-
            Vincula uma pessoa existente; sem este campo, informe name para
            criar.
        name:
          type: string
          minLength: 1
        birth_date:
          anyOf:
            - type: string
              format: date
            - type: string
              format: date-time
        gender:
          type: integer
        notes:
          type: string
        contacts:
          type: array
          items:
            $ref: '#/components/schemas/ChatPersonContactInput'
        address:
          $ref: '#/components/schemas/ChatPersonAddressInput'
        addresses:
          type: array
          items:
            $ref: '#/components/schemas/ChatPersonAddressInput'
        documents:
          type: array
          items:
            $ref: '#/components/schemas/ChatPersonDocumentInput'
      anyOf:
        - required:
            - person_id
        - required:
            - name
    ChatDetails:
      type: object
      properties:
        id:
          type: string
          format: uuid
        wa_contact_id:
          type: string
        contact_name:
          type: string
        contact_number:
          type: string
        status:
          $ref: '#/components/schemas/ChatStatusEnum'
        chat_type:
          $ref: '#/components/schemas/ChatTypeEnum'
        unread_count:
          type: integer
        is_manually_unread:
          type: boolean
        priority:
          $ref: '#/components/schemas/ChatPriorityValue'
        archived_at:
          type: string
          format: date-time
          nullable: true
        phone_number:
          $ref: '#/components/schemas/ChatPhoneDetails'
        assigned_agent:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatAgentSummary'
          nullable: true
        last_message:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatMessageSummary'
          nullable: true
        crm_person:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatPersonDetails'
          nullable: true
        last_customer_msg_at:
          type: string
          format: date-time
          nullable: true
        session_expires_at:
          type: string
          format: date-time
          nullable: true
        can_send_open_message:
          type: boolean
          description: Indica se a janela atual permite mensagem aberta.
        has_pending_copilot_actions:
          type: boolean
        pending_copilot_actions_count:
          type: integer
        channel_type:
          type: string
          enum:
            - WHATSAPP
        channel_account_id:
          type: string
          format: uuid
        channel_account:
          $ref: '#/components/schemas/ChatChannelAccount'
        external_contact:
          $ref: '#/components/schemas/ChatExternalContact'
        legacy:
          type: object
          properties:
            whatsapp_chat_id:
              type: string
              format: uuid
            whatsapp_phone_id:
              type: string
              format: uuid
            wa_contact_id:
              type: string
        remote_profile_name:
          type: string
          nullable: true
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
        participants:
          type: array
          items:
            $ref: '#/components/schemas/ChatAgentSummary'
        crm_marketing_lead_source:
          type: array
          items:
            type: object
            properties: {}
            additionalProperties: true
        assignable_agents:
          type: array
          items:
            $ref: '#/components/schemas/ChatAssignableAgentSummary'
          description: >-
            Incluído ao consultar os detalhes; pode ser omitido nos retornos das
            mutações.
        whatsapp_flow_sessions:
          type: array
          items:
            $ref: '#/components/schemas/ChatFlowSession'
        pending_copilot_actions:
          type: array
          items:
            $ref: '#/components/schemas/ChatPendingCopilotAction'
      required:
        - id
        - status
        - priority
        - channel_type
        - participants
        - created_at
        - updated_at
        - phone_number
        - crm_person
        - pending_copilot_actions
        - whatsapp_flow_sessions
    ChatInstagramDetails:
      type: object
      properties:
        id:
          type: string
          format: uuid
        wa_contact_id:
          type: string
          nullable: true
          description: Sempre null nas conversas Instagram.
        contact_name:
          type: string
        contact_number:
          type: string
        status:
          $ref: '#/components/schemas/ChatStatusEnum'
        chat_type:
          $ref: '#/components/schemas/ChatTypeEnum'
        unread_count:
          type: integer
        is_manually_unread:
          type: boolean
        priority:
          $ref: '#/components/schemas/ChatPriorityValue'
        archived_at:
          type: string
          format: date-time
          nullable: true
        assigned_agent_id:
          type: string
          format: uuid
          nullable: true
        phone_number:
          $ref: '#/components/schemas/ChatPhoneSummary'
        assigned_agent:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatAgentSummary'
          nullable: true
        last_message_at:
          type: string
          format: date-time
          nullable: true
        last_message:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatInstagramMessage'
          nullable: true
        crm_person:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatPersonDetails'
          nullable: true
        last_customer_msg_at:
          type: string
          format: date-time
          nullable: true
        session_expires_at:
          type: string
          format: date-time
          nullable: true
        can_send_open_message:
          type: boolean
          description: Indica se a janela atual permite mensagem aberta.
        has_pending_copilot_actions:
          type: boolean
        pending_copilot_actions_count:
          type: integer
        has_active_whatsapp_flow_session:
          type: boolean
        active_whatsapp_flow_sessions:
          type: array
          items:
            $ref: '#/components/schemas/ChatActiveFlowSession'
        has_upcoming_scheduled_message:
          type: boolean
          description: Presente na listagem; indica agendamento futuro.
        channel_type:
          type: string
          enum:
            - INSTAGRAM
        channel_account_id:
          type: string
          format: uuid
        channel_account:
          $ref: '#/components/schemas/ChatChannelAccount'
        external_contact:
          $ref: '#/components/schemas/ChatExternalContact'
        legacy:
          type: object
          properties: {}
          description: Objeto vazio para Instagram.
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
        participants:
          type: array
          items:
            $ref: '#/components/schemas/ChatAgentSummary'
        assignable_agents:
          type: array
          items:
            $ref: '#/components/schemas/ChatAssignableAgentSummary'
        crm_marketing_lead_sources:
          type: array
          items:
            type: object
            properties: {}
            additionalProperties: true
        pending_copilot_actions:
          type: array
          items:
            $ref: '#/components/schemas/ChatPendingCopilotAction'
      required:
        - id
        - status
        - channel_type
        - participants
        - assignable_agents
        - pending_copilot_actions
    ChatPersonContactInput:
      type: object
      properties:
        type:
          type: integer
          enum:
            - 0
            - 1
            - 2
            - 3
            - 4
            - 5
            - 6
            - 7
          description: >-
            0 WhatsApp, 1 e-mail, 2 celular, 3 telefone, 4 Instagram, 5
            Facebook, 6 LinkedIn, 7 outros.
        value:
          type: string
          minLength: 1
        primary:
          type: boolean
      required:
        - type
        - value
    ChatPersonAddressInput:
      type: object
      properties:
        name:
          type: string
        street:
          type: string
        number:
          type: string
        complement:
          type: string
        district:
          type: string
        city:
          type: string
        state:
          type: string
        postal_code:
          type: string
        status:
          type: integer
          enum:
            - 0
            - 1
        type:
          type: integer
          enum:
            - 0
            - 1
            - 2
            - 3
    ChatPersonDocumentInput:
      type: object
      properties:
        type:
          type: integer
          enum:
            - 0
            - 1
            - 2
            - 3
            - 4
          description: 0 CNH, 1 RG, 2 passaporte, 3 CPF, 4 outros.
        value:
          type: string
          minLength: 1
        label:
          type: string
          minLength: 1
          description: Obrigatório quando type=4.
      required:
        - type
        - value
      anyOf:
        - properties:
            type:
              type: integer
              enum:
                - 0
                - 1
                - 2
                - 3
        - properties:
            type:
              type: integer
              enum:
                - 4
          required:
            - label
    ChatStatusEnum:
      type: string
      enum:
        - OPEN
        - RESOLVED
        - SNOOZED
    ChatTypeEnum:
      type: string
      enum:
        - INDIVIDUAL
        - GROUP
    ChatPriorityValue:
      type: integer
      enum:
        - 0
        - 1
        - 2
        - 3
      description: 0 = baixa, 1 = normal, 2 = alta, 3 = urgente.
    ChatPhoneDetails:
      allOf:
        - $ref: '#/components/schemas/ChatPhoneSummary'
        - type: object
          properties:
            raw_number:
              type: string
            phone_number_id:
              type: string
    ChatAgentSummary:
      type: object
      properties:
        agent_id:
          type: string
          format: uuid
        user:
          type: object
          allOf:
            - $ref: '#/components/schemas/ExternalUserSummary'
          nullable: true
    ChatMessageSummary:
      type: object
      properties:
        id:
          type: string
          format: uuid
        type:
          $ref: '#/components/schemas/ChatMessageTypeEnum'
        origin:
          $ref: '#/components/schemas/ChatMessageOriginEnum'
        from_me:
          type: boolean
        sent_via:
          $ref: '#/components/schemas/ChatMessageSentViaEnum'
        status:
          $ref: '#/components/schemas/ChatMessageDeliveryStatusEnum'
        body_text:
          type: string
          nullable: true
        content_payload:
          type: object
          nullable: true
          additionalProperties: true
        reactions:
          type: array
          items:
            $ref: '#/components/schemas/ChatReaction'
        meta_timestamp:
          type: string
          format: date-time
        is_history:
          type: boolean
        history_phase:
          type: integer
          nullable: true
        history_chunk_order:
          type: integer
          nullable: true
        history_progress:
          type: integer
          nullable: true
        is_media_placeholder:
          type: boolean
        agent:
          type: object
          nullable: true
          properties:
            id:
              type: string
              format: uuid
            user:
              type: object
              allOf:
                - $ref: '#/components/schemas/ExternalUserSummary'
              nullable: true
        user:
          type: object
          allOf:
            - $ref: '#/components/schemas/ExternalUserSummary'
          nullable: true
        crm_marketing_lead_source:
          type: array
          nullable: true
          items:
            type: object
            additionalProperties: true
        transcription:
          type: string
          nullable: true
        is_forwarded:
          type: boolean
        whatsapp_ai_agent_id:
          type: string
          format: uuid
          nullable: true
          description: >-
            Agente de IA que enviou a mensagem; null para pessoas e automações.
            Em `last_message`, é preenchido apenas na listagem de chats.
    ChatPersonDetails:
      type: object
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        birth_date:
          type: string
          format: date-time
          nullable: true
        gender:
          type: integer
          nullable: true
        notes:
          type: string
          nullable: true
        contacts:
          type: array
          items:
            $ref: '#/components/schemas/ChatPersonContact'
        documents:
          type: array
          items:
            $ref: '#/components/schemas/ChatPersonDocument'
        address:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatPersonAddress'
          nullable: true
    ChatChannelAccount:
      type: object
      properties:
        id:
          type: string
          format: uuid
        type:
          type: string
          description: WHATSAPP_PHONE para WhatsApp; tipo da conta para Instagram.
        display_name:
          type: string
          nullable: true
        provider_status:
          type: string
    ChatExternalContact:
      type: object
      properties:
        id:
          type: string
        handle:
          type: string
          nullable: true
        display_name:
          type: string
          nullable: true
        avatar_url:
          type: string
          nullable: true
    ChatAssignableAgentSummary:
      type: object
      properties:
        agent_id:
          type: string
          format: uuid
        status:
          type: string
        user:
          $ref: '#/components/schemas/ExternalUserSummary'
    ChatFlowSession:
      type: object
      properties:
        session_id:
          type: string
          format: uuid
        flow_id:
          type: string
          format: uuid
        flow_name:
          type: string
        status:
          type: string
          enum:
            - ACTIVE
            - WAITING_INPUT
            - WAITING_TIME
            - PAUSED_BY_HUMAN
            - TRANSFERRED
            - COMPLETED
            - FAILED
            - CANCELED
        status_label:
          type: string
        is_active:
          type: boolean
        started_at:
          type: string
          format: date-time
        last_activity_at:
          type: string
          format: date-time
        finished_at:
          type: string
          format: date-time
          nullable: true
        current_step:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatFlowStep'
          nullable: true
    ChatPendingCopilotAction:
      type: object
      properties:
        id:
          type: string
          format: uuid
        company_id:
          type: string
          format: uuid
        execution_id:
          type: string
          format: uuid
        agent_id:
          type: string
          format: uuid
        agent_name:
          type: string
          nullable: true
        chat_id:
          type: string
          format: uuid
          nullable: true
        action_key:
          type: string
        status:
          type: string
        confidence:
          type: string
          nullable: true
        requires_review:
          type: boolean
        input_payload: {}
        output_payload:
          nullable: true
        failure_reason:
          type: string
          nullable: true
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
        executed_at:
          type: string
          format: date-time
          nullable: true
    ChatPhoneSummary:
      type: object
      properties:
        id:
          type: string
          format: uuid
        display_number:
          type: string
          nullable: true
    ChatInstagramMessage:
      type: object
      properties:
        id:
          type: string
          format: uuid
        type:
          type: string
          description: Tipo normalizado da mensagem do canal.
        origin:
          type: string
          enum:
            - INBOUND
            - API_OUTBOUND
            - APP_ECHO
            - SYSTEM
        from_me:
          type: boolean
        sent_via:
          $ref: '#/components/schemas/ChatMessageSentViaEnum'
        status:
          type: string
          enum:
            - PROCESSING
            - SENT
            - DELIVERED
            - READ
            - FAILED
            - DELETED
          description: Status da mensagem no Instagram, em maiúsculas.
        body_text:
          type: string
          nullable: true
        content_payload:
          type: object
          nullable: true
          additionalProperties: true
        reactions:
          type: array
          items:
            $ref: '#/components/schemas/ChatReaction'
        meta_timestamp:
          type: string
          format: date-time
        is_history:
          type: boolean
        history_phase:
          type: integer
          nullable: true
        history_chunk_order:
          type: integer
          nullable: true
        history_progress:
          type: integer
          nullable: true
        is_media_placeholder:
          type: boolean
        agent:
          type: object
          nullable: true
          properties:
            id:
              type: string
              format: uuid
            user:
              type: object
              allOf:
                - $ref: '#/components/schemas/ExternalUserSummary'
              nullable: true
        user:
          type: object
          allOf:
            - $ref: '#/components/schemas/ExternalUserSummary'
          nullable: true
        crm_marketing_lead_source:
          type: array
          nullable: true
          items:
            type: object
            additionalProperties: true
        is_forwarded:
          type: boolean
        wamid:
          type: string
          nullable: true
        provider_message_id:
          type: string
          nullable: true
        ref_wamid:
          type: string
          nullable: true
        ref_provider_message_id:
          type: string
          nullable: true
        error_code:
          type: string
          nullable: true
          description: Código textual do erro, por exemplo `DELIVERY_UNKNOWN`.
        error_message:
          type: string
          nullable: true
        shared_content:
          type: object
          properties: {}
          nullable: true
          additionalProperties: true
        media:
          type: array
          items:
            $ref: '#/components/schemas/ChatInstagramAttachment'
        attachments:
          type: array
          items:
            $ref: '#/components/schemas/ChatInstagramAttachment'
        provider_timestamp:
          type: string
          format: date-time
        channel_type:
          type: string
          enum:
            - INSTAGRAM
        quoted_message:
          allOf:
            - $ref: '#/components/schemas/ChatInstagramMessage'
            - type: object
              properties:
                page:
                  type: integer
      required:
        - id
        - type
        - origin
        - from_me
        - sent_via
        - status
        - body_text
        - meta_timestamp
        - media
        - attachments
        - channel_type
    ChatActiveFlowSession:
      allOf:
        - $ref: '#/components/schemas/ChatFlowSession'
        - type: object
          properties:
            journey:
              type: object
              properties:
                completed_steps:
                  type: array
                  items:
                    $ref: '#/components/schemas/ChatFlowStep'
                current_step:
                  type: object
                  allOf:
                    - $ref: '#/components/schemas/ChatFlowStep'
                  nullable: true
                upcoming_steps:
                  type: array
                  items:
                    $ref: '#/components/schemas/ChatFlowStep'
    ExternalUserSummary:
      type: object
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        avatar:
          type: string
          nullable: true
    ChatMessageTypeEnum:
      type: string
      enum:
        - text
        - reaction
        - image
        - video
        - audio
        - document
        - template
        - interactive
        - location
        - call
        - contacts
        - unsupported
        - sticker
        - button
      description: >-
        Tipos mais comuns. Mensagens recebidas guardam o tipo informado pelo
        provedor, de modo que outros valores podem aparecer.
    ChatMessageOriginEnum:
      type: string
      enum:
        - INBOUND
        - API_OUTBOUND
        - MOBILE_APP_ECHO
        - SYSTEM
    ChatMessageSentViaEnum:
      type: string
      enum:
        - CONTACT
        - API
        - MOBILE_DEVICE
        - SYSTEM
    ChatMessageDeliveryStatusEnum:
      type: string
      enum:
        - processing
        - sent
        - delivered
        - read
        - failed
        - received
        - deleted
        - delivery_unknown
      description: >-
        Status persistido da mensagem; delivery_unknown indica que o resultado
        do envio ainda não foi confirmado.
    ChatReaction:
      type: object
      properties:
        id:
          type: string
          format: uuid
        emoji:
          type: string
        actor:
          type: string
          enum:
            - CONTACT
            - BUSINESS
            - SYSTEM
          description: '`SYSTEM` pode aparecer em reações do Instagram.'
        reactor_wa_id:
          type: string
        reactor_user_id:
          type: string
          format: uuid
          nullable: true
        created_at:
          type: string
          format: date-time
    ChatPersonContact:
      type: object
      properties:
        id:
          type: string
          format: uuid
        type:
          type: integer
        value:
          type: string
        primary:
          type: boolean
    ChatPersonDocument:
      type: object
      properties:
        id:
          type: string
          format: uuid
        type:
          type: integer
        label:
          type: string
          nullable: true
        value:
          type: string
    ChatPersonAddress:
      type: object
      properties:
        id:
          type: string
          format: uuid
        status:
          type: integer
        type:
          type: integer
        name:
          type: string
          nullable: true
        street:
          type: string
          nullable: true
        number:
          type: string
          nullable: true
        complement:
          type: string
          nullable: true
        district:
          type: string
          nullable: true
        city:
          type: string
          nullable: true
        state:
          type: string
          nullable: true
        postal_code:
          type: string
          nullable: true
    ChatFlowStep:
      type: object
      properties:
        node_id:
          type: string
        node_key:
          type: string
        name:
          type: string
        status:
          type: string
          nullable: true
        status_label:
          type: string
          nullable: true
        branch_key:
          type: string
          nullable: true
        branch_label:
          type: string
          nullable: true
        started_at:
          type: string
          format: date-time
          nullable: true
        finished_at:
          type: string
          format: date-time
          nullable: true
    ChatInstagramAttachment:
      type: object
      properties:
        id:
          type: string
          format: uuid
        media_id:
          type: string
          nullable: true
        provider_media_id:
          type: string
          nullable: true
        provider_type:
          type: string
          nullable: true
        content_kind:
          type: string
        mime_type:
          type: string
          nullable: true
        file_name:
          type: string
          nullable: true
        file_size:
          type: number
          nullable: true
        storage_path:
          type: string
          nullable: true
        public_url:
          type: string
          nullable: true
        source_url:
          type: string
          nullable: true
        url:
          type: string
          nullable: true
        is_downloaded:
          type: boolean
        download_status:
          type: string
        metadata:
          type: object
          properties: {}
          nullable: true
          additionalProperties: true
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API key
      description: >-
        Chave de integração com prefixo wegly_, enviada em Authorization: Bearer
        <chave>. Não é JWT. A chave deve estar ativa, não excluída e dentro da
        validade. Com allowed_domain, Origin (ou Referer na ausência de Origin)
        precisa informar o hostname permitido. A empresa e as permissões são
        obtidas pela chave.

````

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