RCSZilla Версія 1.0

Вебхуки

Сповіщення в реальному часі для вхідних SMS, WhatsApp та Email повідомлень.

Огляд

RCSZilla може надсилати HTTP POST-запити на ваш сервер при виникненні певних подій. Це дозволяє створювати інтеграції в реальному часі без polling.

ПолеОписConfigured in
incoming_smsA new SMS message was received by your Android device.Devices → Control → Webhooks tab
incoming_whatsappA new WhatsApp message was received by your Android device.Devices → Control → Webhooks tab
incoming_emailA new email arrived in an IMAP inbox linked to your SMTP server.Email Servers → Edit → Incoming Email (IMAP) section
testA test event sent manually from the UI.Same as above

Налаштування

Incoming SMS / WhatsApp Webhook

  1. Go to Devices and click the control icon for your device.
  2. Open the Webhooks tab.
  3. Enter your endpoint URL (must accept POST, return 2xx within 10 seconds).
  4. Optionally set a Webhook Secret for HMAC signature verification.
  5. Click Save, then Send Test Webhook to verify.

Incoming Email Webhook

  1. Go to Email Servers and edit (or add) a server.
  2. Expand the Incoming Email (IMAP) section.
  3. Enable IMAP polling and fill in the IMAP host, port, encryption, and credentials.
  4. Enter a webhook URL and optional secret.
  5. Save. A cron job checks for new emails every 2 minutes.

Формат запиту

Заголовки

HeaderОпис
Content-Typeapplication/json
User-AgentRCSZilla-Webhook/1.0
X-RCSZilla-EventEvent type: incoming_sms, incoming_whatsapp, incoming_email, or test
X-RCSZilla-DeliveryUnique delivery ID (use for deduplication)
X-RCSZilla-Signaturesha256=<hex-hmac> — only present if you set a webhook secret. The HMAC is computed over the raw JSON body using SHA-256.

incoming_sms / incoming_whatsapp

Fired when the Android app calls submit_reply with a new message.

JSON
{
  "event": "incoming_sms",
  "timestamp": "2026-05-27T14:30:00Z",
  "data": {
    "id": 209,
    "from": "+40712345678",
    "message": "Yes, I want to book an appointment",
    "channel": "sms",
    "device_id": 6,
    "contact": {
      "id": 42,
      "name": "John Doe",
      "phone": "+40712345678"
    },
    "auto_reply": "Thanks! We will get back to you shortly."
  }
}

Поле

ПолеТипОпис
eventstringincoming_sms or incoming_whatsapp
timestampstringISO 8601 UTC timestamp
data.idintID of the stored incoming message
data.fromstringSender phone number
data.messagestringMessage text
data.channelstringsms or whatsapp
data.device_idintDevice that received the message
data.contactobject|nullMatched contact (id, name, phone) or null if unknown sender
data.auto_replystring|nullAuto-reply text sent back, or null if no rule matched

incoming_email

Fired when the IMAP cron finds a new email in the configured mailbox.

JSON
{
  "event": "incoming_email",
  "timestamp": "2026-05-27T14:30:00Z",
  "data": {
    "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?",
    "received_at": "2026-05-27T14:28:00Z",
    "smtp_server_id": 5
  }
}

Поле

ПолеТипОпис
data.idintID of the stored email
data.from_emailstringSender email address
data.from_namestringSender display name
data.to_emailstringRecipient (your mailbox)
data.subjectstringEmail subject line
data.body_textstringPlain-text body (first 2000 chars)
data.received_atstringOriginal receive timestamp
data.smtp_server_idintWhich SMTP/IMAP server received this

Перевірка підписів

If you configure a webhook secret, each delivery includes an X-RCSZilla-Signature header. Verify it like this:

PHP
<?php
$payload = file_get_contents('php://input');
$secret  = 'whsec_your_secret_here';

$header    = $_SERVER['HTTP_X_RCSZILLA_SIGNATURE'] ?? '';
$expected  = 'sha256=' . hash_hmac('sha256', $payload, $secret);

if (!hash_equals($expected, $header)) {
    http_response_code(401);
    exit('Invalid signature');
}

$data = json_decode($payload, true);
// Process the event...
http_response_code(200);
echo json_encode(['ok' => true]);
Node.js
const crypto = require('crypto');

app.post('/webhook', (req, res) => {
  const payload = JSON.stringify(req.body);
  const secret  = 'whsec_your_secret_here';
  const sig     = req.headers['x-rcszilla-signature'] || '';
  const expected = 'sha256=' + crypto.createHmac('sha256', secret)
                                      .update(payload).digest('hex');

  if (sig !== expected) return res.status(401).send('Invalid signature');

  const { event, data } = req.body;
  console.log(`Received ${event}:`, data);
  res.json({ ok: true });
});
Python
import hmac, hashlib, json
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = 'whsec_your_secret_here'

@app.route('/webhook', methods=['POST'])
def webhook():
    payload = request.get_data()
    sig     = request.headers.get('X-RCSZilla-Signature', '')
    expected = 'sha256=' + hmac.new(
        SECRET.encode(), payload, hashlib.sha256
    ).hexdigest()

    if not hmac.compare_digest(sig, expected):
        abort(401)

    data = json.loads(payload)
    print(f"Event: {data['event']}", data['data'])
    return {'ok': True}

Політика повторних спроб

If your endpoint returns a non-2xx status code, times out (10 seconds), or is unreachable, the delivery is retried with exponential backoff:

AttemptDelay
1st retry1 minute
2nd retry5 minutes
3rd retry30 minutes
4th retry2 hours
5th retry (final)12 hours
*
After 5 failed attempts the webhook is marked as permanently failed. Successfully delivered webhooks are automatically cleaned up after 7 days. Failed deliveries are retained for 30 days.

Список доставок Webhook

GET /?endpoint=webhook_deliveries

Повертає пагінований список доставок webhook для автентифікованого користувача, з лічильниками статусів та необов'язковою фільтрацією.

Параметри запиту

ПолеТипОпис
statusstring необов'язково Фільтр за статусом: pending, processing, sent або failed.
event_typestring необов'язково Фільтр за типом події: incoming_sms, incoming_whatsapp, incoming_email або test.
limitint необов'язково Результатів на сторінку (1–100). За замовчуванням: 20.
offsetint необов'язково Зміщення пагінації. За замовчуванням: 0.

Приклад запиту

cURL
curl "https://api.rcszilla.com/?endpoint=webhook_deliveries&status=pending&limit=10" \
  -H "Authorization: Bearer YOUR-API-TOKEN"

Відповідь

JSON
{
  "success": true,
  "total": 42,
  "limit": 10,
  "offset": 0,
  "counts": {
    "pending": 3,
    "sent": 38,
    "failed": 1
  },
  "deliveries": [
    {
      "id": 156,
      "event_type": "incoming_sms",
      "webhook_url": "https://your-server.com/hook",
      "status": "pending",
      "attempts": 0,
      "max_attempts": 5,
      "http_status": null,
      "last_error": null,
      "next_retry_at": "2026-05-27T14:31:00Z",
      "created_at": "2026-05-27T14:30:05",
      "last_attempt_at": null
    }
  ]
}

Лічильники статусів

Об'єкт counts надає швидкий огляд усіх станів webhook без перегляду кожної доставки. Використовуйте для віджетів панелі або перевірок стану.

ПолеОпис
pendingУ черзі, очікує наступного запуску cron або вікна повторної спроби.
processingНаразі доставляється cron-воркером.
sentУспішно доставлено (HTTP 2xx). Автоочищення через 7 днів.
failedУсі спроби повторення вичерпано. Автоочищення через 30 днів.

Отримати доставку Webhook

GET /?endpoint=webhook_delivery

Повертає одну доставку webhook за ID, включаючи повний payload, який був (або буде) надісланий на ваш ендпойнт.

Параметри запиту

ПолеТипОпис
idint обов'язково ID доставки, повернутий webhook_deliveries.

Приклад запиту

cURL
curl "https://api.rcszilla.com/?endpoint=webhook_delivery&id=156" \
  -H "Authorization: Bearer YOUR-API-TOKEN"

Відповідь

JSON
{
  "success": true,
  "delivery": {
    "id": 156,
    "event_type": "incoming_sms",
    "webhook_url": "https://your-server.com/hook",
    "payload": {
      "event": "incoming_sms",
      "timestamp": "2026-05-27T14:30:00Z",
      "data": {
        "id": 209,
        "from": "+40712345678",
        "message": "Yes, I want to book",
        "channel": "sms",
        "device_id": 6,
        "contact": {
          "id": 42,
          "name": "John Doe",
          "phone": "+40712345678"
        },
        "auto_reply": null
      }
    },
    "status": "sent",
    "attempts": 1,
    "max_attempts": 5,
    "http_status": 200,
    "last_error": null,
    "next_retry_at": null,
    "created_at": "2026-05-27T14:30:05",
    "last_attempt_at": "2026-05-27T14:30:08"
  }
}
*
Використовуйте webhook_deliveries?status=failed для моніторингу несправних ендпойнтів, або status=pending для перевірки глибини черги. Поле counts у відповіді списку ідеально підходить для панелей моніторингу.

n8n Integration

To receive webhooks in n8n:

  1. Add a Webhook node to your workflow and copy its URL.
  2. Paste that URL into the webhook URL field in {APP_NAME} (Devices → Webhooks or Email Servers → IMAP).
  3. Test to confirm n8n receives the event.
  4. Connect downstream nodes to process the data (e.g., send a Slack message, update a CRM, trigger a reply).

Налаштування Cron

Add these cron jobs to your server:

crontab
# Fire pending webhooks (every minute)
* * * * * /usr/bin/php /path/to/send_sms/cron/process_webhook_queue.php

# Poll IMAP inboxes for new emails (every 2 minutes)
*/2 * * * * /usr/bin/php /path/to/send_sms/cron/process_incoming_emails.php