> ## 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 chat com template

> Cria ou reutiliza um chat WhatsApp e envia o template inicial. Informe wa_contact_id ou person_contact_id. assigned_agent_id é ID do agente, não do usuário. A rota não recebe arquivos: mídia de cabeçalho do template deve ser informada por URL. Permissão da chave: crm/chats.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
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:
    post:
      tags:
        - Chats
      summary: Criar chat com template
      description: >-
        Cria ou reutiliza um chat WhatsApp e envia o template inicial. Informe
        wa_contact_id ou person_contact_id. assigned_agent_id é ID do agente,
        não do usuário. A rota não recebe arquivos: mídia de cabeçalho do
        template deve ser informada por URL. Permissão da chave:
        crm/chats.create. O acesso também respeita a empresa e as permissões do
        usuário criador da chave.
      operationId: externalChatsCreate
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateExternalChat'
      responses:
        '201':
          description: Operação realizada.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChatSummary'
        '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:
    CreateExternalChat:
      type: object
      required:
        - whatsapp_phone_id
        - template
      anyOf:
        - required:
            - wa_contact_id
        - required:
            - person_contact_id
      properties:
        whatsapp_phone_id:
          type: string
          format: uuid
        wa_contact_id:
          type: string
          maxLength: 50
        person_contact_id:
          type: string
          format: uuid
        remote_profile_name:
          type: string
          maxLength: 255
          nullable: true
        crm_person_id:
          type: string
          format: uuid
          nullable: true
        assigned_agent_id:
          type: string
          format: uuid
          nullable: true
        status:
          $ref: '#/components/schemas/ChatStatusEnum'
        template:
          $ref: '#/components/schemas/ChatTemplateInfo'
        template_fields:
          type: array
          items:
            $ref: '#/components/schemas/ChatTemplateField'
    ChatSummary:
      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
        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/ChatMessageSummary'
          nullable: true
        crm_person:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatCrmPersonSummary'
          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:
            - 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
        ai_attendance:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatAiAttendance'
          nullable: true
          description: >-
            Presente nos registros de WhatsApp da listagem; null quando a
            conversa nunca teve agente de IA ou o recurso está desativado. Não
            faz parte da criação nem dos detalhes.
      required:
        - id
        - wa_contact_id
        - contact_name
        - contact_number
        - status
        - priority
        - chat_type
        - unread_count
        - is_manually_unread
        - channel_type
        - channel_account_id
        - can_send_open_message
    ChatStatusEnum:
      type: string
      enum:
        - OPEN
        - RESOLVED
        - SNOOZED
    ChatTemplateInfo:
      type: object
      required:
        - name
        - language
      properties:
        name:
          type: string
        language:
          type: string
    ChatTemplateField:
      type: object
      required:
        - component
        - type
        - value
      properties:
        component:
          type: string
          enum:
            - HEADER
            - BODY
            - BUTTONS
        type:
          type: string
          enum:
            - TEXT
            - IMAGE
            - VIDEO
            - DOCUMENT
            - LOCATION
        value:
          type: string
          description: >-
            Valor do campo. Em campos IMAGE, VIDEO ou DOCUMENT, aceita uma URL
            http(s) ou `file:<n>`, em que n é a posição (a partir de 0) do
            arquivo enviado no mesmo formulário, contando primeiro os de `files`
            e depois os de `file`.
        index:
          type: number
        button_index:
          type: number
        card_index:
          type: number
    ChatTypeEnum:
      type: string
      enum:
        - INDIVIDUAL
        - GROUP
    ChatPriorityValue:
      type: integer
      enum:
        - 0
        - 1
        - 2
        - 3
      description: 0 = baixa, 1 = normal, 2 = alta, 3 = urgente.
    ChatPhoneSummary:
      type: object
      properties:
        id:
          type: string
          format: uuid
        display_number:
          type: string
          nullable: true
    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.
    ChatCrmPersonSummary:
      type: object
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
    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'
    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
    ChatAiAttendance:
      type: object
      description: >-
        Resumo do atendimento por agente de IA em uma conversa WhatsApp da
        listagem.
      properties:
        state:
          type: string
          enum:
            - AI
            - TRANSFERRED
            - TEAM
          description: >-
            AI: o agente conduz a conversa. TRANSFERRED: transferida pelo agente
            e ainda sem resposta de uma pessoa. TEAM: com a equipe.
        agent:
          type: object
          properties:
            id:
              type: string
              format: uuid
            name:
              type: string
            profile_name:
              type: string
              nullable: true
        since:
          type: string
          format: date-time
          nullable: true
          description: >-
            Com o agente atendendo, início do atendimento; depois, momento em
            que o agente saiu da conversa.
        end_reason:
          type: string
          nullable: true
          enum:
            - TRANSFER_RULE
            - FALLBACK
            - RESPONSE_LIMIT
            - HUMAN_REPLY
            - MANUAL_ASSIGNMENT
            - CHAT_RESOLVED
            - AI_COINS_EXHAUSTED
            - OUTSIDE_ACTIVE_HOURS
          description: >-
            Motivo do encerramento do atendimento pelo agente; null enquanto ele
            conduz a conversa.
        transferred_to:
          type: object
          nullable: true
          description: Pessoa que recebeu a conversa na transferência.
          properties:
            id:
              type: string
              format: uuid
            name:
              type: string
    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
    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
    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
  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.