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

# Ativar integração

> Provisiona a integração Chatwoot: cria a inbox no Chatwoot e ativa o roteamento de mensagens

**Auth:** `TokenAccount` ou `TokenInstance` • **Rate-limit:** `Global` (100/min) • **Idempotente:** não

## Descrição

Ativa a integração Chatwoot para uma instância. A RyzeAPI cria uma inbox no Chatwoot e mantém a conexão em tempo real. O `chatwootApiToken` é encriptado at-rest com **AES-256-GCM** e não é retornado por este endpoint (é exposto em plaintext apenas em [`GET /api/chatwoot/list/:instance`](/pt/api/chatwoot/info)).

<Warning>
  Esta operação tem timeout interno de **60s**, a primeira ativação envolve criação de inbox e abertura de WebSocket, o que pode demorar dependendo da latência até o Chatwoot.
</Warning>

## Exemplo

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/chatwoot/set/suporte" \
    -H "token: $Token_Account" \
    -H "Content-Type: application/json" \
    -d '{
      "chatwootBaseUrl":   "https://chatwoot.example.com",
      "chatwootAccountId": 5,
      "chatwootApiToken":  "sk_live_abc123...",
      "inboxName":         "WhatsApp - Orion",
      "signMessages":      true,
      "ignoreGroups":      false,
      "startAsPending":    false,
      "reopenResolved":    true
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch("https://ryzeapi.cloud/api/chatwoot/set/suporte", {
    method: "POST",
    headers: {
      "token":        process.env.Token_Account,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      chatwootBaseUrl:   "https://chatwoot.example.com",
      chatwootAccountId: 5,
      chatwootApiToken:  "sk_live_abc123...",
      inboxName:         "WhatsApp - Orion",
      signMessages:      true,
      ignoreGroups:      false,
      startAsPending:    false,
      reopenResolved:    true
    })
  });
  ```

  ```python Python theme={null}
  import os, requests

  requests.post(
      "https://ryzeapi.cloud/api/chatwoot/set/suporte",
      headers={
          "token":        os.environ["Token_Account"],
          "Content-Type": "application/json"
      },
      json={
          "chatwootBaseUrl":   "https://chatwoot.example.com",
          "chatwootAccountId": 5,
          "chatwootApiToken":  "sk_live_abc123...",
          "inboxName":         "WhatsApp - Orion",
          "signMessages":      True,
          "ignoreGroups":      False,
          "startAsPending":    False,
          "reopenResolved":    True
      }
  )
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
      "os"
      "strings"
  )

  func main() {
      body := strings.NewReader(`{
          "chatwootBaseUrl":   "https://chatwoot.example.com",
          "chatwootAccountId": 5,
          "chatwootApiToken":  "sk_live_abc123...",
          "inboxName":         "WhatsApp - Orion",
          "signMessages":      true,
          "ignoreGroups":      false,
          "startAsPending":    false,
          "reopenResolved":    true
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/chatwoot/set/suporte", body)
      req.Header.Set("token", os.Getenv("Token_Account"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

## Resposta de sucesso

```json 201 Created theme={null}
{
  "instance": "suporte",
  "status": "active",
  "bridge_integration_id": "int_xyz789abc",
  "message": "chatwoot integration activated"
}
```

| Campo                   | Descrição                                                             |
| ----------------------- | --------------------------------------------------------------------- |
| `instance`              | Nome da instância onde a integração foi ativada.                      |
| `status`                | `"active"` quando a ativação foi concluída.                           |
| `bridge_integration_id` | ID interno da integração, usado como referência nas demais operações. |
| `message`               | Mensagem fixa de confirmação.                                         |

## Parâmetros de rota

<ParamField path="instance" type="string" required>
  Nome da instância (ex.: `suporte`).
</ParamField>

## Headers

<ParamField header="token" type="string" required>
  `TokenAccount` ou `TokenInstance`.
</ParamField>

<ParamField header="Content-Type" type="string" required>
  `application/json`
</ParamField>

## Request body

<ParamField body="chatwootBaseUrl" type="string" required>
  URL da instalação Chatwoot (RFC 3986). O `/` final é removido. Ex.: `https://chatwoot.example.com`.
</ParamField>

<ParamField body="chatwootAccountId" type="integer" required>
  ID numérico da conta Chatwoot. Precisa ser maior que `0`.
</ParamField>

<ParamField body="chatwootApiToken" type="string" required>
  API token (`access_token`) do agente Chatwoot. Encriptado at-rest com AES-256-GCM. Não é retornado por este endpoint, mas é exposto em plaintext em [`GET /api/chatwoot/list/:instance`](/pt/api/chatwoot/info).
</ParamField>

<ParamField body="inboxName" type="string" default="RyzeAPI">
  Nome do inbox a ser criado no Chatwoot.
</ParamField>

<ParamField body="signMessages" type="boolean">
  Se `true`, prefixa mensagens enviadas pela RyzeAPI com a assinatura do agente Chatwoot.
</ParamField>

<ParamField body="ignoreGroups" type="boolean">
  Se `true`, eventos de grupo não são roteados para o Chatwoot.
</ParamField>

<ParamField body="startAsPending" type="boolean">
  Se `true`, conversas novas começam como `pending` (em vez de `open`).
</ParamField>

<ParamField body="reopenResolved" type="boolean">
  Se `true`, mensagens novas em conversas marcadas como `resolved` reabrem-nas automaticamente.
</ParamField>

## Erros

A API classifica a falha e devolve um status HTTP útil com uma mensagem **acionável**. O texto bruto da causa raiz (vinda do Chatwoot) é incluído após `Detail:`.

| HTTP | `error.message`                                                                                                         | Causa                                                                          |
| :--: | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
|  400 | `Chatwoot account or endpoint not found - verify chatwootBaseUrl (...) and chatwootAccountId (...). Detail: ...`        | Account ID errado, URL inválida ou Chatwoot devolveu 404/422.                  |
|  400 | `Chatwoot rejected the request as invalid ... Detail: ...`                                                              | Erro 422 do Chatwoot (validação do payload).                                   |
|  400 | `invalid body: ...`                                                                                                     | Body malformado ou campos obrigatórios ausentes.                               |
|  401 | `Chatwoot rejected the API token - verify chatwootApiToken. Detail: ...`                                                | Token Chatwoot inválido (Chatwoot devolveu `HTTP 401: Invalid Access Token`).  |
|  403 | `Chatwoot denied the request - verify the API token has admin scope on account <id>. Detail: ...`                       | Token sem escopo de admin na conta.                                            |
|  404 | `instance not found`                                                                                                    | Instância não existe na RyzeAPI.                                               |
|  500 | `chatwoot integration failed: persist integration: ...`                                                                 | Falha de persistência local (DB).                                              |
|  502 | `Chatwoot is unreachable at <url> - verify chatwootBaseUrl and that the host is reachable from the server. Detail: ...` | DNS, `connection refused`, `i/o timeout`, `dial tcp` ou Chatwoot retornou 5xx. |
|  503 | `integration gateway not configured`                                                                                    | Módulo Chatwoot não habilitado no servidor.                                    |

<Tip>
  Use o **status HTTP** para reagir programaticamente (`401` → corrigir token, `502` → reverificar URL/conectividade) e exiba `error.message` ao usuário final, ela já vem com a próxima ação sugerida.
</Tip>

### Exemplos de payload de erro

Token inválido:

```json theme={null}
{
  "success": false,
  "error": {
    "message": "Chatwoot rejected the API token - verify chatwootApiToken. Detail: https://chatwoot.example.com/api/v1/accounts/5/inboxes HTTP 401: {\"error\":\"Invalid Access Token\"}"
  }
}
```

Host inacessível:

```json theme={null}
{
  "success": false,
  "error": {
    "message": "Chatwoot is unreachable at https://chatwoot.example.com - verify chatwootBaseUrl and that the host is reachable from the server. Detail: Post \"https://chatwoot.example.com/api/v1/accounts/5/inboxes\": dial tcp [::1]:443: connect: connection refused"
  }
}
```

## Próximo

<CardGroup cols={2}>
  <Card title="Ver status / info" icon="circle-info" href="/pt/api/chatwoot/info">
    Confira o `status` e o `last_error` da integração.
  </Card>

  <Card title="Desativar integração" icon="power-off" href="/pt/api/chatwoot/deactivate">
    Remova a integração (a inbox no Chatwoot é preservada).
  </Card>
</CardGroup>
