API de Mensajes Entrantes
Lee los mensajes SMS, WhatsApp y Email recibidos mediante la API REST.
Descripción general
Estos endpoints te permiten obtener los mensajes entrantes recibidos por RCSZilla — SMS y WhatsApp a través de dispositivos Android, y Email mediante consulta IMAP. Úsalos para lecturas masivas, sincronización con CRM o como alternativa a los webhooks.
| Endpoint | Método | Descripción |
|---|---|---|
incoming_messages | GET | Listar mensajes SMS y WhatsApp recibidos. |
incoming_emails | GET | Listar emails recibidos de buzones IMAP. |
Para un polling eficiente, usa
after_id en vez de rangos de fechas. Guarda el mayor id de la última respuesta y pásalo en la siguiente llamada — solo recibirás mensajes nuevos, sin duplicados.Listar SMS / WhatsApp entrantes
Devuelve una lista paginada de mensajes SMS y WhatsApp recibidos por tus dispositivos Android. Incluye información de contacto y dispositivo.
Parámetros de consulta
| Campo | Tipo | Descripción | |
|---|---|---|---|
since | string | opcional | Fecha-hora ISO 8601. Solo mensajes recibidos en o después de esta hora. |
until | string | opcional | Fecha-hora ISO 8601. Solo mensajes recibidos en o antes de esta hora. |
channel | string | opcional | Filtrar por canal: sms o whatsapp. |
device_id | int | opcional | Filtrar por ID de dispositivo. |
from_phone | string | opcional | Filtrar por número de teléfono del remitente (coincidencia exacta). |
after_id | int | opcional | Solo devolver mensajes con ID mayor que este valor. Ideal para polling incremental. |
limit | int | opcional | Resultados por página (1–100). Por defecto: 50. |
offset | int | opcional | Desplazamiento de paginación. Por defecto: 0. |
Ejemplo de solicitud
curl "https://api.rcszilla.com/?endpoint=incoming_messages&after_id=208&limit=50" \ -H "Authorization: Bearer YOUR-API-TOKEN"
curl "https://api.rcszilla.com/?endpoint=incoming_messages&since=2026-05-27T00:00:00Z&channel=sms&limit=20" \ -H "Authorization: Bearer YOUR-API-TOKEN"
curl "https://api.rcszilla.com/?endpoint=incoming_messages&from_phone=%2B40712345678&limit=10" \ -H "Authorization: Bearer YOUR-API-TOKEN"
Respuesta
JSON
{
"success": true,
"total": 142,
"limit": 50,
"offset": 0,
"messages": [
{
"id": 209,
"channel": "sms",
"from_phone": "+40712345678",
"message": "Yes, I want to book an appointment for Monday",
"received_at": "2026-05-27 14:30:05",
"contact": {
"id": 42,
"name": "John Doe",
"phone": "+40712345678"
},
"device": {
"id": 6,
"name": "Office Samsung"
}
},
{
"id": 208,
"channel": "whatsapp",
"from_phone": "+40798765432",
"message": "Hello, do you have availability this week?",
"received_at": "2026-05-27 14:25:12",
"contact": null,
"device": {
"id": 6,
"name": "Office Samsung"
}
}
]
}
Campos de respuesta
| Campo | Tipo | Descripción |
|---|---|---|
id | int | ID único del mensaje. Usa el valor más alto como after_id para polling incremental. |
channel | string | sms or whatsapp |
from_phone | string | Número de teléfono del remitente. |
message | string | Texto del mensaje. |
received_at | string | Cuándo se recibió el mensaje. |
contact | object|null | Contacto coincidente (id, nombre, teléfono) o null si el remitente es desconocido. |
device | object|null | Dispositivo que recibió el mensaje (id, nombre). |
Listar emails entrantes
Devuelve una lista paginada de emails recibidos por buzones IMAP vinculados a tus servidores SMTP. Incluye cuerpo en texto plano y HTML.
Parámetros de consulta
| Campo | Tipo | Descripción | |
|---|---|---|---|
since | string | opcional | Fecha-hora ISO 8601. Solo mensajes recibidos en o después de esta hora. |
until | string | opcional | Fecha-hora ISO 8601. Solo mensajes recibidos en o antes de esta hora. |
smtp_server_id | int | opcional | Filtrar por ID de servidor SMTP/IMAP. |
from_email | string | opcional | Filtrar por dirección de email del remitente (coincidencia exacta). |
search | string | opcional | Buscar en asunto, from_email y from_name (coincidencia parcial). |
after_id | int | opcional | Solo devolver mensajes con ID mayor que este valor. Ideal para polling incremental. |
limit | int | opcional | Resultados por página (1–100). Por defecto: 50. |
offset | int | opcional | Desplazamiento de paginación. Por defecto: 0. |
Ejemplo de solicitud
curl "https://api.rcszilla.com/?endpoint=incoming_emails&after_id=309&limit=20" \ -H "Authorization: Bearer YOUR-API-TOKEN"
curl "https://api.rcszilla.com/?endpoint=incoming_emails&search=order&since=2026-05-01T00:00:00Z" \ -H "Authorization: Bearer YOUR-API-TOKEN"
Respuesta
JSON
{
"success": true,
"total": 38,
"limit": 20,
"offset": 0,
"emails": [
{
"id": 310,
"from_email": "customer@example.com",
"from_name": "John Doe",
"to_email": "support@yourbusiness.com",
"subject": "Re: Your order #1234",
"body_text": "Hi, when will my order arrive?\n\nThanks,\nJohn",
"body_html": "<p>Hi, when will my order arrive?</p>",
"message_id": "<abc123@mail.example.com>",
"received_at": "2026-05-27 14:28:00",
"created_at": "2026-05-27 14:30:02",
"server": {
"id": 5,
"label": "Support Mailbox"
}
}
]
}
Campos de respuesta
| Campo | Tipo | Descripción |
|---|---|---|
id | int | ID único del email. Usa el valor más alto como after_id para polling incremental. |
from_email | string | Dirección de email del remitente. |
from_name | string | Nombre mostrado del remitente. |
to_email | string | Dirección del destinatario (tu buzón). |
subject | string | Línea de asunto del email. |
body_text | string | Cuerpo en texto plano. |
body_html | string | Cuerpo HTML (puede estar vacío si el email era solo texto plano). |
message_id | string | Header Message-ID del email (para threading / deduplicación). |
received_at | string | Cuándo se recibió el mensaje. |
server | object | Servidor SMTP/IMAP que recibió este email (id, etiqueta). |
Patrón de polling recomendado
La forma más eficiente de leer mensajes nuevos es el patrón de cursor after_id. Aquí un ejemplo completo:
PHP
<?php
$token = 'YOUR_API_TOKEN';
$api = 'https://api.rcszilla.com';
$last_id = (int) file_get_contents('/tmp/last_sms_id.txt') ?: 0;
$url = "$api/?endpoint=incoming_messages&after_id=$last_id&limit=100";
$resp = json_decode(file_get_contents($url, false, stream_context_create([
'http' => ['header' => "Authorization: Bearer $token"]
])), true);
foreach ($resp['messages'] as $msg) {
echo "[{$msg['channel']}] {$msg['from_phone']}: {$msg['message']}\n";
if ((int)$msg['id'] > $last_id) $last_id = (int)$msg['id'];
}
file_put_contents('/tmp/last_sms_id.txt', $last_id);
Node.js
const fs = require('fs');
const TOKEN = 'YOUR_API_TOKEN';
const API = 'https://api.rcszilla.com';
let lastId = 0;
try { lastId = parseInt(fs.readFileSync('/tmp/last_sms_id.txt', 'utf8')) || 0; } catch {}
const url = `${API}/?endpoint=incoming_messages&after_id=${lastId}&limit=100`;
const resp = await fetch(url, { headers: { Authorization: `Bearer ${TOKEN}` } });
const data = await resp.json();
for (const msg of data.messages) {
console.log(`[${msg.channel}] ${msg.from_phone}: ${msg.message}`);
if (msg.id > lastId) lastId = msg.id;
}
fs.writeFileSync('/tmp/last_sms_id.txt', String(lastId));
Python
import requests, pathlib
TOKEN = 'YOUR_API_TOKEN'
API = 'https://api.rcszilla.com'
STATE = pathlib.Path('/tmp/last_sms_id.txt')
last_id = int(STATE.read_text()) if STATE.exists() else 0
resp = requests.get(f'{API}/?endpoint=incoming_messages&after_id={last_id}&limit=100',
headers={'Authorization': f'Bearer {TOKEN}'}).json()
for msg in resp['messages']:
print(f"[{msg['channel']}] {msg['from_phone']}: {msg['message']}")
last_id = max(last_id, msg['id'])
STATE.write_text(str(last_id))
Para entrega en tiempo real en vez de polling, configura un Webhook. Puedes usar ambos: webhooks para notificación instantánea y la API para lecturas masivas o recuperación tras inactividad.