# Configuracion En Freshchat API Library

Esta API usa autenticacion por header Bearer Token.

Freshchat no genera automaticamente el token para esta API. Freshchat solo envia el header que configures en API Library. La API valida ese header contra la variable de entorno `FRESHCHAT_API_TOKEN`.

## Configuracion Base

En Freshchat:

1. Ir a `Settings > Advanced > APIs and Custom Placeholders`.
2. Activar `APIs and Custom Placeholders`.
3. Entrar a `API Library`.
4. Click en `Create new API`.

Usar esta configuracion para cada endpoint:

```text
Request type: POST
Encoding: JSON
Authentication: Custom headers
```

Headers:

```http
Authorization: Bearer <tu-token>
Content-Type: application/json
```

Importante:

- El nombre del header debe ser `Authorization`, sin espacios.
- El valor si lleva espacio: `Bearer <tu-token>`.
- El token debe ser el mismo valor de `FRESHCHAT_API_TOKEN` en `.env`.
- No pongas el token en mensajes visibles del bot.

## API: Iniciar Workflow

Nombre sugerido:

```text
MacroBase Workflow Start
```

Model name sugerido:

```text
workflow_start
```

URL:

```text
https://tu-dominio.com/freshchat/workflow/start
```

Body:

```json
{
  "cliente": "{{contact.id}}",
  "nombreCompleto": "{{contact.name}}",
  "nombre": "{{contact.firstname}}",
  "telefono": "{{contact.phone}}",
  "email": "{{contact.email}}",
  "canal": "whatsapp",
  "supports_interactive": true
}
```

Campos utiles de respuesta:

```text
$.error
$.mensaje
$.response_type
$.option_1
$.option_1_id
$.option_2
$.option_2_id
$.option_3
$.option_3_id
$.fallback_text
$.data.messages[0].type
$.data.messages[0].sections
```

## API: Iniciar Workflow Interactivo Desde Backend

Usa esta API si quieres que tu backend envie el mensaje interactivo dentro de Freshchat/WhatsApp. En este caso la automation solo necesita `Trigger an API`; no agregues `Send a message`.

Requiere configurar en el servidor:

```env
FRESHWORKS_API_BASE_URL=https://macrobase-chat.myfreshworks.com
FRESHWORKS_API_TOKEN=<token-oficial-freshchat>
FRESHWORKS_DEFAULT_ACTOR_TYPE=agent
FRESHWORKS_DEFAULT_ACTOR_ID=<id-del-agente-o-bot-si-aplica>
```

Nombre sugerido:

```text
MacroBase Workflow Start Interactive
```

Model name sugerido:

```text
workflow_start_interactive
```

URL:

```text
http://129.80.4.9:8010/freshchat/workflow/start-interactive
```

Body:

```json
{
  "cliente": "{{contact.id}}",
  "conversation_id": "{{conversation.id}}",
  "user_id": "{{contact.id}}",
  "nombreCompleto": "{{contact.name}}",
  "nombre": "{{contact.firstname}}",
  "telefono": "{{contact.phone}}",
  "email": "{{contact.email}}",
  "canal": "whatsapp",
  "supports_interactive": true
}
```

Si el placeholder `{{conversation.id}}` no existe en tu cuenta, usa el selector de placeholders de Freshworks para encontrar el ID de conversacion equivalente.

Campos utiles:

```text
$.error
$.mensaje
$.sent
$.data.conversation_id
$.data.freshchat_message
```

Importante: esta API no usa `Send a message` de Advanced Automations. El mensaje lo envia directamente el backend mediante Freshchat Conversation API.

## API: Manejar Opcion Seleccionada

Nombre sugerido:

```text
MacroBase Workflow Handle Option
```

Model name sugerido:

```text
workflow_option
```

URL:

```text
https://tu-dominio.com/freshchat/workflow/handle-option
```

Body usando la variable antigua `OpcionPrincipal`:

```json
{
  "cliente": "{{contact.id}}",
  "selected_option": "{{workflow.OpcionPrincipal}}",
  "canal": "whatsapp",
  "supports_interactive": true
}
```

Body si Freshchat puede guardar el ID plano:

```json
{
  "cliente": "{{contact.id}}",
  "selected_option": "{{workflow.selected_option}}",
  "selected_option_id": "{{workflow.selected_option_id}}",
  "canal": "whatsapp",
  "supports_interactive": true
}
```

## API: MBIA Login

Nombre sugerido:

```text
MacroBase MBIA Login
```

Model name sugerido:

```text
mbia_login
```

URL:

```text
https://tu-dominio.com/freshchat/mbia/login
```

Body:

```json
{
  "cliente": "{{contact.id}}",
  "nombreCompleto": "{{contact.name}}",
  "nombre": "{{contact.firstname}}",
  "telefono": "{{contact.phone}}",
  "email": "{{contact.email}}"
}
```

Campos utiles:

```text
$.error
$.mensaje
$.data.validado
```

## API: MBIA Bot

Nombre sugerido:

```text
MacroBase MBIA Bot
```

Model name sugerido:

```text
mbia_bot
```

URL:

```text
https://tu-dominio.com/freshchat/mbia/bot
```

Body:

```json
{
  "cliente": "{{contact.id}}",
  "nombreCompleto": "{{contact.name}}",
  "nombre": "{{contact.firstname}}",
  "telefono": "{{contact.phone}}",
  "email": "{{contact.email}}",
  "peticion": "{{contact.last_incoming_message}}"
}
```

Campos utiles:

```text
$.error
$.mensaje
$.data.intent
$.data.confidence
```

## API: Encuesta Start

Nombre sugerido:

```text
MacroBase Encuesta Start
```

Model name sugerido:

```text
encuesta_start
```

URL:

```text
https://tu-dominio.com/freshchat/encuesta/start
```

Body:

```json
{
  "cliente": "{{contact.id}}",
  "nombre": "{{contact.firstname}}",
  "empresa": "{{contact.empresa_lista}}",
  "canal": "whatsapp",
  "supports_interactive": true
}
```

## API: Encuesta Question

Crear una API por cada pregunta o reutilizar una cambiando el body desde la automatizacion.

URL:

```text
https://tu-dominio.com/freshchat/encuesta/question
```

Body para rapidez:

```json
{
  "cliente": "{{contact.id}}",
  "step": "rapidez",
  "canal": "whatsapp",
  "supports_interactive": true
}
```

Body para amabilidad:

```json
{
  "cliente": "{{contact.id}}",
  "step": "amabilidad",
  "canal": "whatsapp",
  "supports_interactive": true
}
```

Body para resolucion:

```json
{
  "cliente": "{{contact.id}}",
  "step": "resolucion",
  "canal": "whatsapp",
  "supports_interactive": true
}
```

## API: Encuesta Save

Nombre sugerido:

```text
MacroBase Encuesta Save
```

Model name sugerido:

```text
encuesta_save
```

URL:

```text
https://tu-dominio.com/freshchat/encuesta/save
```

Body:

```json
{
  "nombre": "{{contact.name}}",
  "empresa": "{{contact.empresa_lista}}",
  "agente_id": "{{assignee.id}}",
  "agente": "{{assignee.firstname}} {{assignee.lastname}} {{assignee.email}}",
  "rapidez": "{{workflow.rapidez}}",
  "amabilidad": "{{workflow.amabilidad}}",
  "resolucion": "{{workflow.resolucion}}",
  "fecha_hora_conversacion_abierta": "{{conversation.opened_timestamp}}"
}
```

Campos utiles:

```text
$.error
$.mensaje
$.data.promedio
```

## Como Usar La Respuesta En Acciones Posteriores

Freshchat guarda la respuesta con el `model name` configurado. En acciones posteriores puedes usar los campos del objeto de respuesta segun lo permita la UI.

Ejemplos de campos que devuelve esta API:

```json
{
  "error": "false",
  "mensaje": "Selecciona una opción",
  "response_type": "list",
  "option_1": "Emergencia de Cobro",
  "option_1_id": "emergencia_cobro",
  "fallback_text": "Por favor responde con una de estas opciones..."
}
```

Si Freshchat no permite renderizar componentes interactivos desde API externa, usar:

```text
mensaje
fallback_text
option_1
option_2
option_3
```

Si Freshchat si permite leer objetos anidados, usar:

```text
data.messages[0].buttons
data.messages[0].sections
data.messages[0].fallback_text
```
