# Mensajes con botones y listas

`POST /v1/messages`

Botones de respuesta, listas y un botón con enlace, **sin plantilla**: `POST /v1/messages` con `type: "interactive"` y el objeto `interactive` de Meta, tal cual lo documenta Meta.

**Cuándo se puede: sólo dentro de la ventana de 24 h** (el contacto te escribió en las últimas 24 horas), igual que el texto libre. Fuera de la ventana Meta lo rechaza: el mensaje queda `failed` con `lastErrorCode: WINDOW_24H_EXPIRED` (`GET /v1/messages/:id` y el webhook `message.status`). Para escribirle primero a alguien hace falta una **plantilla aprobada**.

**Tres tipos.** `button`: de 1 a 3 botones de respuesta. `list`: un botón que abre una lista de hasta 10 opciones en secciones. `cta_url`: un botón que abre una página web.

**Botones** (`interactive.type: "button"`):

```json
{"type":"interactive","interactive":{"type":"button","header":{"type":"text","text":"Turno del jueves"},"body":{"text":"Hola Ana, ¿confirmás tu turno del jueves 20 a las 10:30?"},"footer":{"text":"Clínica Ejemplo"},"action":{"buttons":[{"type":"reply","reply":{"id":"turno-confirmar","title":"Confirmo"}},{"type":"reply","reply":{"id":"turno-cambiar","title":"Cambiar horario"}},{"type":"reply","reply":{"id":"turno-cancelar","title":"Cancelar"}}]}}}
```

**Lista** (`interactive.type: "list"`):

```json
{"type":"interactive","interactive":{"type":"list","header":{"type":"text","text":"Menú del día"},"body":{"text":"Elegí tu pedido y te lo mandamos en 30 minutos."},"footer":{"text":"Pizzería Ejemplo"},"action":{"button":"Ver opciones","sections":[{"title":"Pizzas","rows":[{"id":"pz-muzza","title":"Muzzarella","description":"8 porciones · $9.000"},{"id":"pz-napo","title":"Napolitana","description":"8 porciones · $10.500"}]},{"title":"Bebidas","rows":[{"id":"bb-agua","title":"Agua 500 ml"}]}]}}}
```

**Botón con enlace** (`interactive.type: "cta_url"`): `"action": { "name": "cta_url", "parameters": { "display_text": "Ver factura", "url": "https://tienda.example/facturas/A-1042" } }`. Tocarlo abre el navegador: no genera webhook.

**Cuando el contacto toca un botón o elige una fila** te llega `message.received`. `data.message` es el de Meta, intacto (`type: "interactive"`), y WAIA Connect suma **`data.reply`**: `type` (`button_reply`, `list_reply`, o `button` si tocó una respuesta rápida de una plantilla), `id` (el que mandaste), `title`, `description` (sólo listas) y `messageId` (el `msg_…` del mensaje tocado, si salió por WAIA Connect):

```json
{"type":"message.received","data":{"message":{"type":"interactive","context":{"id":"wamid.…"},"interactive":{"type":"button_reply","button_reply":{"id":"turno-confirmar","title":"Confirmo"}}},"reply":{"type":"button_reply","id":"turno-confirmar","title":"Confirmo","messageId":"msg_…"}}}
```

Cuando el contacto toca un botón se abre de nuevo la ventana de 24 h.

**Límites de Meta** (en caracteres; un emoji cuenta uno). Botones: título ≤ 20 y distinto de los otros, `id` ≤ 256, cuerpo ≤ 1024, encabezado de texto ≤ 60 o imagen, video o documento, pie ≤ 60. Lista: botón ≤ 20, hasta 10 secciones y **10 filas en total**, fila con `id` ≤ 200 (sin repetir), título ≤ 24 y descripción ≤ 72, título de sección ≤ 24 (obligatorio con más de una sección), cuerpo ≤ 4096, encabezado sólo de texto ≤ 60. Botón con enlace: texto ≤ 20, cuerpo ≤ 1024.

**Errores.** Se revisan antes de mandar nada a Meta: `400 INTERACTIVE_INVALID` con **todos** los errores juntos en `details.errors[]` (`field` = la ruta JSON, `code`, `message` en tu idioma; por ejemplo `COUNT`, `TOO_LONG`, `DUPLICATE`, `HEADER_TEXT_ONLY`). La `Idempotency-Key`, el estado (`GET /v1/messages/:id`) y los eventos de entrega funcionan igual que con un texto.

**Cómo se cobra.** WAIA Connect cobra el abono fijo por número y **no tiene tope de mensajes**: un mensaje con botones cuenta como un mensaje, igual que un texto. Meta cobra aparte, con su tarifa: dentro de la ventana de 24 h es un mensaje de **servicio**, con **1.000 gratis por número y por mes**; desde el 1.001 Meta cobra cada uno. Detalle: [Lo que cobra Meta y lo que cobra WAIA Connect](https://waiaconnect.com/docs/cambio-de-precios-de-meta).

## Ejemplos

### cURL

```bash
# Only inside the 24-hour window (the contact wrote to you in the last 24 h).
curl -X POST https://api.waiaconnect.com/v1/messages \
  -H "Authorization: Bearer wc_live_YOUR_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{"connectionId":"conn_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","to":"5493511234567","type":"interactive","interactive":{"type":"button","body":{"text":"Hi Ana, can you confirm your appointment on Thursday at 10:30?"},"footer":{"text":"Example Clinic"},"action":{"buttons":[{"type":"reply","reply":{"id":"appt-confirm","title":"Confirm"}},{"type":"reply","reply":{"id":"appt-change","title":"Change time"}}]}}}'
# A list instead:       "interactive": {"type":"list","body":{"text":"Pick your order"},"action":{"button":"See options","sections":[{"title":"Pizzas","rows":[{"id":"pz-1","title":"Margherita","description":"8 slices"}]}]}}
# One URL button:       "interactive": {"type":"cta_url","body":{"text":"Your invoice is ready"},"action":{"name":"cta_url","parameters":{"display_text":"See invoice","url":"https://shop.example/inv/A-1042"}}}
# The tap comes back as message.received with data.reply:
# {"type":"button_reply","id":"appt-confirm","title":"Confirm","messageId":"msg_…"}
```

### Node.js

```javascript
// Only inside the 24-hour window (the contact wrote to you in the last 24 h).
const res = await fetch("https://api.waiaconnect.com/v1/messages", {
  method: "POST",
  headers: {
    "Authorization": "Bearer wc_live_YOUR_API_KEY",
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    "connectionId": "conn_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "to": "5493511234567",
    "type": "interactive",
    "interactive": {
      "type": "button",
      "body": {
        "text": "Hi Ana, can you confirm your appointment on Thursday at 10:30?"
      },
      "footer": {
        "text": "Example Clinic"
      },
      "action": {
        "buttons": [
          {
            "type": "reply",
            "reply": {
              "id": "appt-confirm",
              "title": "Confirm"
            }
          },
          {
            "type": "reply",
            "reply": {
              "id": "appt-change",
              "title": "Change time"
            }
          }
        ]
      }
    }
  })
});
const sent = await res.json(); // { id: "msg_…", status: "queued" } — 400 INTERACTIVE_INVALID lists every mistake

// In your webhook handler, after verifying the signature:
if (evt.type === "message.received" && evt.data.reply) {
  const { type, id, title, messageId } = evt.data.reply; // type: button_reply | list_reply | button
  if (id === "appt-confirm") await confirmAppointment(evt.data.message.from, messageId); // your code
}
```

### PHP

```php
<?php
// Only inside the 24-hour window (the contact wrote to you in the last 24 h).
$ch = curl_init("https://api.waiaconnect.com/v1/messages");
curl_setopt_array($ch, [
  CURLOPT_POST => true,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer wc_live_YOUR_API_KEY",
    "Idempotency-Key: " . bin2hex(random_bytes(16)),
    "Content-Type: application/json",
  ],
  CURLOPT_POSTFIELDS => json_encode(["connectionId" => "conn_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","to" => "5493511234567","type" => "interactive","interactive" => ["type" => "button","body" => ["text" => "Hi Ana, can you confirm your appointment on Thursday at 10:30?"],"footer" => ["text" => "Example Clinic"],"action" => ["buttons" => [["type" => "reply","reply" => ["id" => "appt-confirm","title" => "Confirm"]],["type" => "reply","reply" => ["id" => "appt-change","title" => "Change time"]]]]]]),
]);
echo curl_exec($ch);

// In your webhook handler: $reply = $evt["data"]["reply"] ?? null;
// if ($reply && $reply["id"] === "appt-confirm") { /* your code */ }
```

### Python

```python
import requests, uuid
# Only inside the 24-hour window (the contact wrote to you in the last 24 h).
res = requests.post("https://api.waiaconnect.com/v1/messages",
  headers={
    "Authorization": "Bearer wc_live_YOUR_API_KEY",
    "Idempotency-Key": str(uuid.uuid4()),
  },
  json={"connectionId":"conn_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","to":"5493511234567","type":"interactive","interactive":{"type":"button","body":{"text":"Hi Ana, can you confirm your appointment on Thursday at 10:30?"},"footer":{"text":"Example Clinic"},"action":{"buttons":[{"type":"reply","reply":{"id":"appt-confirm","title":"Confirm"}},{"type":"reply","reply":{"id":"appt-change","title":"Change time"}}]}}})
print(res.json())  # {"id": "msg_…", "status": "queued"}

# In your webhook handler:
# reply = evt["data"].get("reply")
# if reply and reply["id"] == "appt-confirm": ...  # your code
```

## Notas

- **No es lo mismo que una plantilla con botones.** Una plantilla con botones (respuesta rápida, URL, copiar código) sirve **fuera** de la ventana, necesita la aprobación de Meta y puede tener costo según su categoría. El mensaje interactivo no se aprueba, pero sólo sale dentro de las 24 h.
- **Convivencia:** la regla de las 24 h vale igual para lo que mandás por la API. Lo que mandás desde la app WhatsApp Business del teléfono sigue sus propias reglas.
- WAIA Connect no guarda el texto, los títulos ni los ids de tus botones: sólo cuántos eran.
- Mandar productos o el catálogo por `/v1` todavía no está disponible.
