> ## 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.

# Activar integración

> Provisiona la integración de Chatwoot: crea la inbox en Chatwoot y activa el enrutamiento de mensajes

**Auth:** `TokenAccount` o `TokenInstance` • **Rate limit:** `Global` (100/min) • **Idempotente:** no

## Descripción

Activa la integración de Chatwoot para una instancia. RyzeAPI crea una inbox en Chatwoot y mantiene la conexión en tiempo real. El `chatwootApiToken` se cifra en reposo con **AES-256-GCM** y no es devuelto por este endpoint (solo se expone en plaintext en [`GET /api/chatwoot/list/:instance`](/es/api/chatwoot/info)).

<Warning>
  Esta operación tiene un timeout interno de **60 s**, la primera activación implica crear la inbox y abrir la conexión, lo que puede tardar dependiendo de la latencia hacia Chatwoot.
</Warning>

## Ejemplo

<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>

## Respuesta exitosa

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

| Campo                   | Descripción                                                                   |
| ----------------------- | ----------------------------------------------------------------------------- |
| `instance`              | Nombre de la instancia donde se activó la integración.                        |
| `status`                | `"active"` cuando la activación se completó.                                  |
| `bridge_integration_id` | ID interno de la integración, usado como referencia en las demás operaciones. |
| `message`               | Mensaje fijo de confirmación.                                                 |

## Parámetros de ruta

<ParamField path="instance" type="string" required>
  Nombre de la instancia (p. ej., `suporte`).
</ParamField>

## Cabeceras

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

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

## Cuerpo de la solicitud

<ParamField body="chatwootBaseUrl" type="string" required>
  URL de la instalación de Chatwoot (RFC 3986). La `/` final se elimina. Ejemplo: `https://chatwoot.example.com`.
</ParamField>

<ParamField body="chatwootAccountId" type="integer" required>
  ID numérico de la cuenta de Chatwoot. Debe ser mayor que `0`.
</ParamField>

<ParamField body="chatwootApiToken" type="string" required>
  Token de API (`access_token`) del agente de Chatwoot. Cifrado en reposo con AES-256-GCM. No es devuelto por este endpoint, pero se expone en plaintext en [`GET /api/chatwoot/list/:instance`](/es/api/chatwoot/info).
</ParamField>

<ParamField body="inboxName" type="string" default="RyzeAPI">
  Nombre del inbox que se creará en Chatwoot.
</ParamField>

<ParamField body="signMessages" type="boolean">
  Cuando es `true`, antepone a los mensajes enviados por RyzeAPI la firma del agente de Chatwoot.
</ParamField>

<ParamField body="ignoreGroups" type="boolean">
  Cuando es `true`, los eventos de grupos no se enrutan a Chatwoot.
</ParamField>

<ParamField body="startAsPending" type="boolean">
  Cuando es `true`, las nuevas conversaciones inician como `pending` (en lugar de `open`).
</ParamField>

<ParamField body="reopenResolved" type="boolean">
  Cuando es `true`, los nuevos mensajes en conversaciones marcadas como `resolved` las reabren automáticamente.
</ParamField>

## Errores

La API clasifica el fallo y devuelve un estado HTTP útil con un mensaje **accionable**. El texto crudo de la causa raíz (proveniente de Chatwoot) se incluye después de `Detail:`.

| HTTP | `error.message`                                                                                                         | Causa                                                                            |
| :--: | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
|  400 | `Chatwoot account or endpoint not found - verify chatwootBaseUrl (...) and chatwootAccountId (...). Detail: ...`        | ID de cuenta incorrecto, URL inválida o Chatwoot devolvió 404/422.               |
|  400 | `Chatwoot rejected the request as invalid ... Detail: ...`                                                              | Error 422 de Chatwoot (validación de payload).                                   |
|  400 | `invalid body: ...`                                                                                                     | Cuerpo malformado o campos requeridos ausentes.                                  |
|  401 | `Chatwoot rejected the API token - verify chatwootApiToken. Detail: ...`                                                | Token de Chatwoot inválido (Chatwoot devolvió `HTTP 401: Invalid Access Token`). |
|  403 | `Chatwoot denied the request - verify the API token has admin scope on account <id>. Detail: ...`                       | El token no tiene permisos de administrador en la cuenta.                        |
|  404 | `instance not found`                                                                                                    | La instancia no existe en RyzeAPI.                                               |
|  500 | `chatwoot integration failed: persist integration: ...`                                                                 | Fallo de persistencia 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`, o Chatwoot devolvió 5xx.   |
|  503 | `integration gateway not configured`                                                                                    | Módulo Chatwoot no habilitado en el servidor.                                    |

<Tip>
  Usa el **estado HTTP** para reaccionar de forma programática (`401` → corregir token, `502` → revisar URL/conectividad) y muestra `error.message` al usuario final, ya incluye la siguiente acción sugerida.
</Tip>

### Ejemplos de payload de error

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 inalcanzable:

```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"
  }
}
```

## Siguiente

<CardGroup cols={2}>
  <Card title="Ver estado / información" icon="circle-info" href="/es/api/chatwoot/info">
    Consulta el `status` y el `last_error` de la integración.
  </Card>

  <Card title="Desactivar integración" icon="power-off" href="/es/api/chatwoot/deactivate">
    Elimina la integración (la inbox en Chatwoot se conserva).
  </Card>
</CardGroup>
