Developers ยท Custom API
Connect your own chat and help desk.
Send your customers' messages to Raha over a signed HTTPS API. An AI employee answers, and the reply comes back to your system by callback, by polling, or both. Two channels: Website chat and Tickets.
- Version 1
- HTTPS and JSON
- HMAC-SHA256 signatures
- Business and Pro plans
On this page
Overview
The Custom API connects a website chat or a ticketing system that you run to RahaAi. Your customers keep writing where they already do; Raha's AI employees answer them, and your team can take over at any time.
| Topic | Website chat | Tickets |
|---|---|---|
| Conversation | One per customer | One per ticket. A customer with three tickets has three conversations. |
| Customer | Your stable customer.external_id | Your stable customer.external_id |
| Context Raha receives | The customer, the page URL, a few attributes | The customer, and per ticket: ID, subject, status, priority, URL, attributes |
| Status sync | Not applicable | Both ways: your ticket status moves the conversation, and a status set in Raha comes back to you (on by default) |
| Where the owner connects it | Raha app: Channels, Website chat | Raha app: Channels, Tickets |
channel in events from Raha | website_chat | tickets |
What Raha does#
- An AI employee answers. The employee the owner assigned to the channel replies to each customer message, in the customer's language, from the business's knowledge. Different employees can answer Website chat and Tickets.
- People can take over. A message from your human agent silences the AI in that conversation. The owner can also take a conversation over, hand it back and write to the customer from the Raha app.
- The owner's Raha sees everything. These conversations appear in the owner's Inbox like any other channel, and Raha, the owner's AI agent, can find, read and summarise them. Messages Raha prepares for customers wait for the owner's approval.
- You stay the system of record. Raha only talks to your system through this API. You decide what is shown to your customers and where.
How messages flow#
Your system Raha
| |
| POST /events (signed with your secret) |
|------------------------------------------------->| stored, then the AI employee answers
| |
| callback to your HTTPS URL (signed by Raha) |
|<-------------------------------------------------| ... or you poll GET /events
| |
| your agent replies: POST /events |
| (message.agent_created) |
|------------------------------------------------->| the AI stops answering this conversationYou send events (customer messages, your agents' messages, ticket and customer updates) with POST /events. Raha sends events back (the AI's replies, handoffs, status changes) in one of three ways, chosen by the owner:
| Delivery | How replies reach you | Choose it when |
|---|---|---|
| Callback | Raha POSTs each event, signed, to your HTTPS callback URL | You have a public endpoint and want replies immediately |
| Polling | You read GET /events and confirm with POST /events/ack | You cannot expose an endpoint, for example behind a firewall |
| Both | Callback and polling carry the same events with the same IDs | You want a safety net: poll to catch up after an outage |
Quick start
The steps are the same for both channels; only the connection you create and the shape of the first message differ. Allow about ten minutes.
Website chat#
Create the connection in the Raha app
Open Channels, then Website chat, then connect. Give the connection a name (1 to 64 characters) and choose how replies reach you: callback, polling or both. For callbacks enter your HTTPS callback URL (port 443; see the URL rules).
Copy the key ID and the two secrets
The app shows four values: the key ID (
ck_...), the request signing secret (rsk_...), the callback signing secret (csk_...) and the base URL. The secrets are shown once. Put them in your server's secret store now. If you lose one, rotate the secrets in the app.Choose who answers
In the app, assign an AI employee to Website chat (the "Who answers" step). Without one, messages are stored but nobody replies.
Send a first signed message
Save this helper as
raha.shand fill in your key ID and request secret. It signs and sends any request, the way Authentication describes.raha.sh # raha.sh: source this file, then call: raha METHOD /path-after-the-prefix [json-body] KEY_ID="ck_Q7mZ3xK9vB2nR8tL5wYd4c" # the key ID from the Raha app SECRET="rsk_EXAMPLE0ONLY0not0a0real0secret0aaaaaaaaaaaa" # the request signing secret, from your secret store HOST="https://app.raha.to" PREFIX="/channels/custom-api/v1" raha() { local method="$1" path="$PREFIX$2" body="${3:-}" ts body_hash sig ts=$(date +%s) body_hash=$(printf '%s' "$body" | openssl dgst -sha256 -hex | sed 's/^.* //') sig=$(printf 'v1\n%s\n%s\n%s\n%s\n%s' "$KEY_ID" "$ts" "$method" "$path" "$body_hash" \ | openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //') curl -sS -X "$method" "$HOST$path" \ -H "Raha-Key-Id: $KEY_ID" -H "Raha-Timestamp: $ts" -H "Raha-Signature: v1=$sig" \ -H "Content-Type: application/json" ${body:+--data-binary "$body"} echo }curl: send a chat message # raha.sh is the helper above (source it first) raha POST /events "$(printf '{"type":"message.created","id":"msg_%s","occurred_at":"%s","customer":{"external_id":"cus_381","name":"Ali Rezaei"},"chat":{"page_url":"https://shop.example.com/pricing"},"message":{"text":"Hello, do you ship to Dubai?"}}' "$(date +%s)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)")"You should get
202with{"accepted":[{"id":"msg_...","status":"accepted"}]}. In the app the connection changes from Pending to Connected at your first verified request.Receive the reply
With callbacks, Raha POSTs a signed
message.createdevent to your callback URL a few seconds later; verify it and answer2xx. Until your endpoint exists, press Send test in the app: Raha sends a signedtest.ping.With polling, read the reply and acknowledge it:
curl: poll and acknowledge raha GET "/events?limit=50" # the reply is in "events"; keep "next_cursor" raha POST /events/ack '{"cursor":"PASTE_NEXT_CURSOR_HERE"}'
Tickets#
Create the connection in the Raha app
Open Channels, then Tickets, then connect. Name it, choose the delivery mode and the callback URL as above. Ticket status sync is on by default.
Copy the key ID and the two secrets
Exactly as for Website chat: key ID, request signing secret, callback signing secret and base URL, shown once.
Choose who answers
Assign an AI employee to the Tickets channel. It can be a different employee from the one on Website chat.
Send a first signed ticket message
Use the same
raha.shhelper. A ticket message carries aticketobject, whoseexternal_idis your ticket ID; Raha opens one conversation per ticket.curl: send a ticket message # raha.sh is the helper above (source it first) raha POST /events "$(printf '{"type":"message.created","id":"msg_%s","occurred_at":"%s","ticket":{"external_id":"T-4512","subject":"Refund for order 4512","status":"open","priority":"high","url":"https://help.example.com/tickets/4512"},"customer":{"external_id":"cus_381","name":"Ali Rezaei","email":"[email protected]"},"message":{"text":"My refund has not arrived yet."}}' "$(date +%s)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)")"Receive the reply
The reply arrives with the same
ticket.external_id, so you can attach it to the right ticket. It arrives as a callback, or inGET /eventsif you poll (acknowledge as above). Status changes made in Raha arrive asticket.status_changed.
Connection settings#
The owner can change these in the connection's settings in the app at any time. Your system does not set them through the API.
| Setting | Choices | Default |
|---|---|---|
| Delivery | Callback, polling or both | Callback |
| Callback URL | An HTTPS address; required unless delivery is polling only (rules below) | None |
| Events to send | message.created, conversation.handoff, ticket.status_changed (tickets only), typing (website chat only). test.ping is always sent. | All of the channel's events |
| Handoff control | Off: only the owner and Raha hand over. Takeover: your system may hand a conversation to a human. Takeover and resume: it may also hand it back to the AI. | Off |
| Ticket status sync | On or off (tickets only) | On |
| File fetching | Allow Raha to download files you name by HTTPS URL | Off |
| IP allow-list | Up to 20 IPv4 or IPv6 ranges (CIDR) that your requests may come from; empty allows any | Empty |
Rules for the callback URL
- HTTPS only, on port 443, at most 1,024 bytes. No user name or password, no fragment, no IP address as the host.
- The host must resolve to public addresses. Private, loopback, link-local and cloud-metadata addresses are refused when the owner saves the URL and again on every delivery.
- Raha does not follow redirects and does not use a proxy. TLS 1.2 or newer with a valid certificate is required.
- Your endpoint has 5 seconds in total to answer.
Rotating the secrets
In the app, Rotate secrets creates a new request secret and a new callback secret and shows them once. The previous secrets keep working for 24 hours: Raha accepts requests signed with either request secret, and signs each callback with both callback secrets. Deploy the new secrets during that window and nothing is interrupted. After 24 hours only the new secrets work.
Authentication and signing
There are no bearer tokens. Every request you send is signed with HMAC-SHA256 using your request signing secret, and every callback Raha sends is signed with your callback signing secret. A secret never travels over the network.
Credentials#
| Value | Looks like | Used for |
|---|---|---|
| Key ID | ck_ and 22 letters or digits | Identifies your connection. Sent in Raha-Key-Id. Not secret; it never changes for the connection. |
| Request signing secret | rsk_ and 43 characters | Signs the requests you send to Raha. |
| Callback signing secret | csk_ and 43 characters | Raha signs callbacks with it; you verify them. |
| Base URL | https://app.raha.to/channels/custom-api/v1 | Every route below is relative to it. |
The workspace, the connection and the channel come only from the verified key. Nothing in a request body can select another workspace or channel.
Request headers#
| Header | Value |
|---|---|
Raha-Key-Id | Your key ID, ck_... |
Raha-Timestamp | The current time as whole Unix seconds, in decimal (for example 1792577700) |
Raha-Signature | v1= followed by the lowercase hex HMAC-SHA256 of the base string |
Content-Type | application/json for events; the file's own type for POST /files |
POST /channels/custom-api/v1/events HTTP/1.1
Host: app.raha.to
Content-Type: application/json
Raha-Key-Id: ck_Q7mZ3xK9vB2nR8tL5wYd4c
Raha-Timestamp: 1792577700
Raha-Signature: v1=6556772158da0ca212b751eca993e96195e8ae46c675165c1e367fa463047ddbThe base string#
Join these six values with a single line feed (\n, byte 10). There is no trailing line feed.
v1
<key_id>
<timestamp>
<METHOD>
<path with query>
<sha256 of the raw body, lowercase hex><METHOD>is the uppercase HTTP method,GETorPOST.<path with query>is the request target exactly as it appears on the request line. It starts with/channels/custom-api/v1/(not the host) and, when there is a query string, continues with?and the query string exactly as you send it: no re-encoding, no sorting. Example:/channels/custom-api/v1/events?after=c2VxOjQyMTk&limit=50.<sha256 of the raw body>is the lowercase hex SHA-256 of the exact bytes you send. For a request without a body it is the hash of the empty string:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.- The signature is the lowercase hex of HMAC-SHA256 over that string. The key is the request signing secret exactly as shown, including its `rsk_` prefix, as UTF-8 bytes. Do not base64-decode it.
Time window and replay#
Raha-Timestampmust be within 300 seconds of Raha's clock, in either direction. Keep your servers on NTP. Otherwise Raha answers401 timestamp_out_of_range.- A signature that Raha has already seen within that window is refused with
401 replayed. A retry therefore needs a new timestamp and a new signature; two identical requests in the same second carry the same signature, so send identical requests at least one second apart. - Retrying is safe: the event
idis the idempotency key, so an event that was stored the first time is answeredduplicate. - Raha checks the signature, the timestamp, replay and the IP allow-list before it reads the body.
Rotating secrets#
- In the Raha app open the connection and choose Rotate secrets. Copy the new request and callback secrets (shown once).
- From that moment Raha accepts requests signed with either request secret, and signs each callback with both callback secrets:
Raha-Signature: v1=<new>,v1=<previous>. - Deploy the new secrets. Your callback verifier accepts the callback if any
v1=value matches (the examples below do this). - After 24 hours the previous secrets stop working. The app shows when.
IP allow-list#
The owner can restrict the connection to up to 20 IPv4 or IPv6 ranges (CIDR). A request from any other address is refused with 403 ip_not_allowed before the signature is even checked. The allow-list applies to requests you send; callbacks go to your callback URL.
Signing examples#
Each example signs a request, sends a first message and then polls. They need only the language's standard tools (curl and openssl; Node.js 18 or newer; Python 3.8 or newer; PHP 8 with curl). Read the secret from your environment or secret store, never from source code.
# raha.sh: source this file, then call: raha METHOD /path-after-the-prefix [json-body]
KEY_ID="ck_Q7mZ3xK9vB2nR8tL5wYd4c" # the key ID from the Raha app
SECRET="rsk_EXAMPLE0ONLY0not0a0real0secret0aaaaaaaaaaaa" # the request signing secret, from your secret store
HOST="https://app.raha.to"
PREFIX="/channels/custom-api/v1"
raha() {
local method="$1" path="$PREFIX$2" body="${3:-}" ts body_hash sig
ts=$(date +%s)
body_hash=$(printf '%s' "$body" | openssl dgst -sha256 -hex | sed 's/^.* //')
sig=$(printf 'v1\n%s\n%s\n%s\n%s\n%s' "$KEY_ID" "$ts" "$method" "$path" "$body_hash" \
| openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //')
curl -sS -X "$method" "$HOST$path" \
-H "Raha-Key-Id: $KEY_ID" -H "Raha-Timestamp: $ts" -H "Raha-Signature: v1=$sig" \
-H "Content-Type: application/json" ${body:+--data-binary "$body"}
echo
}
# Send a message (a fresh ID and timestamp each time)
raha POST /events "$(printf '{"type":"message.created","id":"msg_%s","occurred_at":"%s","customer":{"external_id":"cus_381","name":"Ali Rezaei"},"chat":{"page_url":"https://shop.example.com/pricing"},"message":{"text":"Hello, do you ship to Dubai?"}}' "$(date +%s)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)")"
# Read what Raha sent back (polling), then acknowledge up to the cursor you received
raha GET "/events?limit=50"
raha POST /events/ack '{"cursor":"PASTE_NEXT_CURSOR_HERE"}'// Node.js 18 or newer, no dependencies. Run: node send.mjs
import { createHash, createHmac } from "node:crypto";
const BASE_URL = "https://app.raha.to";
const API_PREFIX = "/channels/custom-api/v1";
const KEY_ID = "ck_Q7mZ3xK9vB2nR8tL5wYd4c"; // the key ID from the Raha app
const REQUEST_SECRET = process.env.RAHA_REQUEST_SECRET; // rsk_..., from your secret store
// Returns the three headers that authenticate one request. "pathWithQuery" is exactly what you put on the request line.
function signRequest(method, pathWithQuery, body = "") {
const timestamp = Math.floor(Date.now() / 1000).toString();
const bodyHash = createHash("sha256").update(body).digest("hex");
const base = ["v1", KEY_ID, timestamp, method.toUpperCase(), pathWithQuery, bodyHash].join("\n");
const signature = createHmac("sha256", REQUEST_SECRET).update(base).digest("hex");
return { "Raha-Key-Id": KEY_ID, "Raha-Timestamp": timestamp, "Raha-Signature": "v1=" + signature };
}
async function raha(method, path, payload) {
const body = payload === undefined ? "" : JSON.stringify(payload); // sign exactly the string you send
const pathWithQuery = API_PREFIX + path;
const headers = signRequest(method, pathWithQuery, body);
if (body) headers["Content-Type"] = "application/json";
const response = await fetch(BASE_URL + pathWithQuery, { method, headers, body: body || undefined });
return { status: response.status, body: await response.text() };
}
const now = Date.now();
console.log(
await raha("POST", "/events", {
type: "message.created",
id: "msg_" + now, // your own unique message ID: it is the idempotency key
occurred_at: new Date(now).toISOString(),
customer: { external_id: "cus_381", name: "Ali Rezaei" },
chat: { page_url: "https://shop.example.com/pricing" },
message: { text: "Hello, do you ship to Dubai?" },
}),
);
console.log(await raha("GET", "/events?limit=50"));# Python 3.8 or newer, standard library only. Run: python send.py
import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
BASE_URL = "https://app.raha.to"
API_PREFIX = "/channels/custom-api/v1"
KEY_ID = "ck_Q7mZ3xK9vB2nR8tL5wYd4c" # the key ID from the Raha app
REQUEST_SECRET = os.environ["RAHA_REQUEST_SECRET"] # rsk_..., from your secret store
def signed_headers(method, path_with_query, body=b""):
"""The three headers that authenticate one request. path_with_query is exactly what is on the request line."""
timestamp = str(int(time.time()))
body_hash = hashlib.sha256(body).hexdigest()
base = "\n".join(["v1", KEY_ID, timestamp, method.upper(), path_with_query, body_hash])
signature = hmac.new(REQUEST_SECRET.encode(), base.encode(), hashlib.sha256).hexdigest()
return {"Raha-Key-Id": KEY_ID, "Raha-Timestamp": timestamp, "Raha-Signature": "v1=" + signature}
def raha(method, path, payload=None):
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else b"" # sign what you send
path_with_query = API_PREFIX + path
headers = signed_headers(method, path_with_query, body)
if body:
headers["Content-Type"] = "application/json"
request = urllib.request.Request(BASE_URL + path_with_query, data=body or None, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=10) as response:
return response.status, response.read().decode()
except urllib.error.HTTPError as error:
return error.code, error.read().decode()
now = int(time.time())
print(raha("POST", "/events", {
"type": "message.created",
"id": "msg_%d" % now, # your own unique message ID: it is the idempotency key
"occurred_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"customer": {"external_id": "cus_381", "name": "Ali Rezaei"},
"chat": {"page_url": "https://shop.example.com/pricing"},
"message": {"text": "Hello, do you ship to Dubai?"},
}))
print(raha("GET", "/events?limit=50"))<?php
// PHP 8 with the curl extension. Run: php send.php
const BASE_URL = "https://app.raha.to";
const API_PREFIX = "/channels/custom-api/v1";
const KEY_ID = "ck_Q7mZ3xK9vB2nR8tL5wYd4c"; // the key ID from the Raha app
$requestSecret = getenv("RAHA_REQUEST_SECRET"); // rsk_..., from your secret store
// Signs and sends one request. $path is relative to the API prefix; sign exactly the string you send.
function raha(string $method, string $path, ?array $payload = null): array {
global $requestSecret;
$body = $payload === null ? "" : json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$pathWithQuery = API_PREFIX . $path;
$timestamp = (string) time();
$base = implode("\n", ["v1", KEY_ID, $timestamp, strtoupper($method), $pathWithQuery, hash("sha256", $body)]);
$signature = hash_hmac("sha256", $base, $requestSecret);
$headers = [
"Raha-Key-Id: " . KEY_ID,
"Raha-Timestamp: " . $timestamp,
"Raha-Signature: v1=" . $signature,
];
$options = [
CURLOPT_CUSTOMREQUEST => strtoupper($method),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
];
if ($body !== "") {
$headers[] = "Content-Type: application/json";
$options[CURLOPT_POSTFIELDS] = $body;
}
$options[CURLOPT_HTTPHEADER] = $headers;
$curl = curl_init(BASE_URL . $pathWithQuery);
curl_setopt_array($curl, $options);
$responseBody = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
return [$status, $responseBody];
}
$now = time();
print_r(raha("POST", "/events", [
"type" => "message.created",
"id" => "msg_" . $now, // your own unique message ID: it is the idempotency key
"occurred_at" => gmdate("Y-m-d\TH:i:s\Z", $now),
"customer" => ["external_id" => "cus_381", "name" => "Ali Rezaei"],
"chat" => ["page_url" => "https://shop.example.com/pricing"],
"message" => ["text" => "Hello, do you ship to Dubai?"],
]));
print_r(raha("GET", "/events?limit=50"));Test vector
Check your own implementation against this fixed request before you call the API. All values are fake examples.
| Input | Value |
|---|---|
| Key ID | ck_Q7mZ3xK9vB2nR8tL5wYd4c |
| Request secret | rsk_EXAMPLE0ONLY0not0a0real0secret0aaaaaaaaaaaa |
| Timestamp | 1792577700 |
| Method and path | POST /channels/custom-api/v1/events |
| Body (exact bytes) | {"type":"message.created","id":"msg_9f2a","occurred_at":"2026-10-21T10:15:00Z","customer":{"external_id":"cus_381"},"chat":{"page_url":"https://shop.example.com/pricing"},"message":{"text":"Hello, do you ship to Dubai?"}} |
| sha256 of the body | ae91a80734257a7fa92cae9e6af71d714be16d6818187bb6c9f018cd62a8d353 |
| Expected Raha-Signature | v1=6556772158da0ca212b751eca993e96195e8ae46c675165c1e367fa463047ddb |
API reference
Every route, with its limits, request and response. All routes are relative to the base URL and every request is signed.
Conventions#
| Topic | Details |
|---|---|
| Base URL | https://app.raha.to/channels/custom-api/v1 |
| Format | JSON in UTF-8. Events are application/json; a file upload is the file's raw bytes. |
| Authentication | The three signing headers on every request (Authentication). |
| Body sizes | Events: 256 KiB. Files: 16 MiB. Other bodies: 4 KiB. Larger bodies are refused with 413. |
| Timestamps | RFC 3339 with a zone offset, for example 2026-10-21T10:15:00Z. |
| Your IDs | Opaque strings that you choose, within the patterns in the field tables. |
| Errors | A JSON body { "code", "message", "path" } and an HTTP status (Errors). Act on code; message is English text for developers. |
| Unknown fields | Requests with fields Raha does not know are refused with 422 invalid_field. In what Raha sends you, ignore fields you do not recognise. |
Routes#
| Method and path | Purpose | Rate limit per connection |
|---|---|---|
POST /events | Send one event, or a batch of up to 20 | 20 per second, burst 40 |
POST /files | Upload one file for a later message | 2 per second |
GET /events | Poll the events Raha sent | 5 per second, shared by the four read routes |
POST /events/ack | Confirm polled events up to a cursor | (shared) |
GET /conversations/messages | Read a conversation again (resync) | (shared) |
GET /files/{file_id} | Download a file Raha sent | (shared) |
POST/events#
Send events to Raha
Send one event as the body, or { "events": [ ... ] } with 1 to 20 events, at most 256 KiB in total. A batch is all or nothing: if any event is refused, none is stored. Raha answers 202 once every event is stored durably; the AI's reply follows on its own. Events of one conversation are processed in the order Raha accepted them, so send them in order.
{
"type": "message.created",
"id": "msg_9f2a",
"occurred_at": "2026-10-21T10:15:00Z",
"ticket": {
"external_id": "T-4512",
"subject": "Refund for order 4512",
"status": "open",
"priority": "high",
"url": "https://help.example.com/tickets/4512",
"attributes": { "department": "billing" }
},
"customer": {
"external_id": "cus_381",
"name": "Ali Rezaei",
"email": "[email protected]",
"language": "fa",
"attributes": { "plan": "gold", "city": "Dubai" }
},
"message": {
"text": "ุณูุงู
ุ ูพูู ุณูุงุฑุดู
ูููุฒ ุจุฑฺูฏุดุชู",
"files": [{ "file_id": "fil_7k2m5q4w3r2t6y3u5i4o2p4a6s" }]
}
}{
"type": "message.created",
"id": "msg_9f2b",
"occurred_at": "2026-10-21T10:16:30Z",
"customer": {
"external_id": "cus_381",
"name": "Ali Rezaei",
"language": "en"
},
"chat": {
"page_url": "https://shop.example.com/pricing",
"attributes": { "cart_items": "2" }
},
"message": { "text": "Hello, do you ship to Dubai?" }
}{
"accepted": [
{ "id": "msg_9f2a", "status": "accepted" }
]
}Sending the same event id again with the same body is answered "status": "duplicate" and changes nothing. The same id with a different body is refused with 409 id_conflict.
{
"accepted": [
{ "id": "msg_9f2a", "status": "duplicate" }
]
}{
"events": [
{
"type": "conversation.updated",
"id": "upd_8833",
"occurred_at": "2026-10-21T10:02:00Z",
"customer": { "external_id": "cus_381" },
"ticket": { "external_id": "T-4512", "status": "pending" }
},
{
"type": "message.agent_created",
"id": "agt_5502",
"occurred_at": "2026-10-21T10:02:05Z",
"customer": { "external_id": "cus_381" },
"ticket": { "external_id": "T-4512" },
"agent": { "name": "Reza (support)" },
"message": { "text": "We are sending a replacement today." }
}
]
}Events you send#
type | Send it when | Effect in Raha |
|---|---|---|
message.created | A customer wrote: text, files or both. | Stored as the customer's message. The assigned employee replies, unless the conversation is with a human. |
message.agent_created | A human agent of your business wrote to the customer in your system. | Stored as the business's outgoing message, and the conversation switches to the human: the AI stops answering it. |
conversation.updated | A ticket's facts changed (subject, status, priority, URL, attributes), a chat's facts changed, or your system hands the conversation over or back. | Facts are updated; ticket status is synced; handoff applies only as the owner's handoff control allows. |
customer.updated | A customer's name, e-mail, phone, language or attributes changed. | The customer's profile is updated. |
{
"type": "message.agent_created",
"id": "agt_5501",
"occurred_at": "2026-10-21T10:22:10Z",
"customer": { "external_id": "cus_381" },
"ticket": { "external_id": "T-4512" },
"agent": { "name": "Reza (support)" },
"message": { "text": "Hi Ali, I am processing your refund now." }
}{
"type": "conversation.updated",
"id": "upd_8832",
"occurred_at": "2026-10-21T10:25:00Z",
"customer": { "external_id": "cus_381" },
"ticket": {
"external_id": "T-4512",
"status": "pending",
"priority": "urgent"
},
"handoff": "takeover"
}{
"type": "customer.updated",
"id": "cup_1207",
"occurred_at": "2026-10-21T10:30:00Z",
"customer": {
"external_id": "cus_381",
"name": "Ali Rezaei",
"email": "[email protected]",
"language": "fa",
"attributes": { "plan": "platinum" }
}
}An update for a ticket that Raha does not know yet creates nothing: it is accepted and ignored. A handoff the owner has not allowed is also accepted and ignored. A ticket is created by its first message.created.
Event fields
| Field | Type | Limits and notes |
|---|---|---|
id | string, required | ^[A-Za-z0-9._:-]{1,128}$. Unique within the connection. It is the idempotency key. |
type | string, required | One of the four types above. |
occurred_at | string, required | RFC 3339 with an offset. Not older than 24 hours and not more than 5 minutes ahead, otherwise 422 stale_event. |
customer | object, required | See the customer fields. customer.external_id is required in every event. |
ticket | object | Tickets. Required for ticket messages. See the ticket fields. |
chat | object | Website chat. Optional. See the chat fields. |
message | object | Required in message.created and message.agent_created. |
agent | object | message.agent_created only. { "name": string }, 1 to 128 characters. |
handoff | string | conversation.updated only. takeover or resume. |
customer
| Field | Type | Limits and notes |
|---|---|---|
external_id | string, required | ^[A-Za-z0-9._@+-]{1,100}$. Your stable ID for this customer. Every conversation of the customer is grouped under it. |
name | string | 1 to 128 characters. |
email | string | A valid mailbox, at most 254 characters. Stored encrypted; shown only to workspace members who may read channels. |
phone | string | E.164: +, then 7 to 15 digits, the first not zero. Stored encrypted, like the e-mail. |
language | string | BCP 47 such as en or fa-IR, at most 16 characters. A hint only; Raha replies in the language the customer writes. |
attributes | object | See attributes. |
ticket
| Field | Type | Limits and notes |
|---|---|---|
external_id | string, required | ^[A-Za-z0-9._:@#/-]{1,128}$. Your ticket ID. One conversation per value. |
subject | string | 1 to 255 characters. Becomes the conversation's title in the owner's Inbox. |
status | string | open, pending, solved or closed. |
priority | string | low, normal, high or urgent. |
url | string | An HTTPS URL, at most 1,024 characters. The owner can open the ticket in your system from it. |
attributes | object | See attributes. |
chat
| Field | Type | Limits and notes |
|---|---|---|
page_url | string | An HTTPS URL, at most 1,024 characters. The page the visitor is on. |
attributes | object | See attributes. |
attributes
At most 20 keys. A key is lowercase: ^[a-z][a-z0-9_]{0,63}$. A value is a string of at most 256 characters. Raha treats attributes as data about the customer or ticket, never as instructions.
message
| Field | Type | Limits and notes |
|---|---|---|
text | string | At most 4,000 characters. |
files | array | At most 10 items. Each is { "file_id": "fil_..." } from POST /files, or, when the owner enabled file fetching, { "url": "https://...", "file_name": string }. |
A message needs text, files or both. Audio is the exception: an audio file must be the only file of its message and the message must have no text.
POST/files#
Upload one file
The body is the file's raw bytes (not multipart), at most 16 MiB. Upload first, then reference the returned file_id in a message within one hour; an unreferenced file is deleted after that, and a file_id can be used by one message. The signature's body hash is the SHA-256 of the file's bytes.
| Header | Notes |
|---|---|
Content-Type | Required. The file's media type, one of the accepted types below. |
Raha-File-Name | Optional. The file name, percent-encoded UTF-8, at most 255 characters after decoding, without /, \ or control characters. |
# Uses KEY_ID, SECRET, HOST and PREFIX from raha.sh above. Percent-encode a Raha-File-Name that is not plain ASCII.
FILE="./invoice.pdf"
path="$PREFIX/files"
ts=$(date +%s)
body_hash=$(openssl dgst -sha256 -hex < "$FILE" | sed 's/^.* //') # sha256 of the file's bytes
sig=$(printf 'v1\n%s\n%s\n%s\n%s\n%s' "$KEY_ID" "$ts" "POST" "$path" "$body_hash" \
| openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //')
curl -sS -X POST "$HOST$path" \
-H "Raha-Key-Id: $KEY_ID" -H "Raha-Timestamp: $ts" -H "Raha-Signature: v1=$sig" \
-H "Content-Type: application/pdf" -H "Raha-File-Name: invoice.pdf" \
--data-binary @"$FILE"import { readFile } from "node:fs/promises";
// signRequest() and the constants are the ones from the signing example above
const bytes = await readFile("./invoice.pdf");
const pathWithQuery = API_PREFIX + "/files";
const response = await fetch(BASE_URL + pathWithQuery, {
method: "POST",
headers: {
...signRequest("POST", pathWithQuery, bytes), // the body hash is over the file's bytes
"Content-Type": "application/pdf",
"Raha-File-Name": encodeURIComponent("invoice.pdf"), // percent-encoded UTF-8
},
body: bytes,
});
console.log(response.status, await response.json()); // 201 { file_id: "fil_7k2m5q4w3r2t6y3u5i4o2p4a6s", expires_at: "..." }{
"file_id": "fil_7k2m5q4w3r2t6y3u5i4o2p4a6s",
"expires_at": "2026-10-21T11:15:00Z"
}{
"type": "message.created",
"id": "msg_9f2d",
"occurred_at": "2026-10-21T10:35:00Z",
"customer": { "external_id": "cus_381" },
"ticket": { "external_id": "T-4512" },
"message": {
"text": "Here are the photos.",
"files": [
{ "file_id": "fil_7k2m5q4w3r2t6y3u5i4o2p4a6s" },
{ "url": "https://files.example.com/photos/damage-1.jpg", "file_name": "damage-1.jpg" }
]
}
}Accepted files
- Images: JPEG, PNG, WebP, GIF. Video: MP4, 3GPP, QuickTime, WebM. Documents: PDF, plain text, CSV, Word, Excel and PowerPoint (
.doc,.docx,.xls,.xlsx,.ppt,.pptx). - Audio: OGG, MP3, M4A/MP4, WAV, WebM, at most 10 MiB. Raha transcribes it for the AI. It must be the only file of its message, and the message must have no text.
- The type is checked against the file's bytes, not only the header: a mismatch is
415 unsupported_media_type. - A file by URL needs the owner's file fetching setting; otherwise
422 file_fetch_disabled. Raha downloads it over HTTPS on port 443 from public addresses only, follows no redirects, and stops at 16 MiB or 30 seconds. - A
file_idthat is not yours, has expired or was already used is422 unknown_file.
GET/events#
Poll the events Raha sent
Available when the connection's delivery is polling or both (otherwise 403 polling_disabled). Returns the events Raha sent through your connection, oldest first, after the cursor; with no after it starts at the beginning of the 7-day window. Delivered and acknowledged events stay readable until they expire after 7 days.
| Parameter | Type | Notes |
|---|---|---|
after | string | The next_cursor of the previous page. ^[A-Za-z0-9_-]{1,128}$. |
limit | integer | 1 to 100. Default 50. |
{
"events": [
{
"event_id": "evt_mq4tx7b2kc5djw3npa6hz5r7ge",
"type": "message.created",
"occurred_at": "2026-10-21T10:15:04Z",
"channel": "website_chat",
"conversation_id": "7d1c5f0e-8a34-4c1b-9b6e-2f3a41c8d9e0",
"customer": { "external_id": "cus_381" },
"message": { "id": "0199f5a1-8d3f-7e51-8d9a-1e3d0a8a2b12", "text": "Yes, we ship to Dubai.", "files": [] },
"sender": { "kind": "ai", "name": "Sara" }
}
],
"next_cursor": "c2VxOjQyMTk"
}next_cursor is the value to pass as after for the next page and as cursor to acknowledge; it is null when the page is empty. The events are exactly those a callback would carry, with the same event_id. See Events Raha sends.
POST/events/ack#
Confirm polled events
Marks every event up to and including the cursor as acknowledged. Acknowledge after you have stored or processed the events. Reading again before you acknowledge returns the same events, so process by event_id idempotently.
{ "cursor": "c2VxOjQyMTk" }{ "acknowledged": 1 }acknowledged is how many events this request newly acknowledged. A bad cursor is 422 invalid_field.
GET/conversations/messages#
Read a conversation again
Use it to resync after an outage or to rebuild a conversation: it returns the messages of one conversation both ways, oldest first. It works whatever the delivery mode.
| Parameter | Type | Notes |
|---|---|---|
customer_id | string, required | The customer's external_id. |
ticket_id | string | Required for Tickets (the ticket's external_id). Refused for Website chat. |
after | string | The next_cursor of the previous page. |
limit | integer | 1 to 100. Default 50. |
raha GET "/conversations/messages?customer_id=cus_381&ticket_id=T-4512&limit=50"{
"messages": [
{
"id": "0199f5a1-6b2d-7c30-8e75-0c1b8e7f9a90",
"direction": "inbound",
"sender": { "kind": "customer", "name": "Ali Rezaei" },
"text": "ุณูุงู
ุ ูพูู ุณูุงุฑุดู
ูููุฒ ุจุฑฺูฏุดุชู",
"files": [],
"created_at": "2026-10-21T10:15:00Z",
"delivery_status": null
},
{
"id": "0199f5a1-8d3f-7e51-8d9a-1e3d0a8a2b12",
"direction": "outbound",
"sender": { "kind": "ai", "name": "Sara" },
"text": "Hello Ali, I am sorry about the delay. Your refund was issued today; the receipt is attached.",
"files": [{ "file_id": "0199f5a1-9e40-7f62-a1b0-2f4e1b9b3c23" }],
"created_at": "2026-10-21T10:15:09Z",
"delivery_status": "delivered"
}
],
"next_cursor": "c2VxOjk4"
}| Field | Notes |
|---|---|
direction | inbound (from the customer) or outbound (to the customer). |
sender.kind | customer, ai, human, agent or system; sender.name may be null. |
files | The files' IDs (UUIDs). A file Raha sent can be downloaded with GET /files/{file_id}. |
delivery_status | queued, sending, sent, delivered, read, failed or null. |
An unknown customer or ticket is 404 not_found.
GET/files/{file_id}#
Download a file Raha sent
file_id is the ID in the files of a message Raha sent through your connection. The answer is 302 with a Location link that is valid for 15 minutes; the same kind of link is already in each file's url in the event. Fetch the Location without your Raha headers. A file that is not one of your conversations' is 404 not_found.
# Do not follow the redirect with the signed request: read the Location header, then fetch that link without Raha headers.
ts=$(date +%s); path="$PREFIX/files/0199f5a1-9e40-7f62-a1b0-2f4e1b9b3c23"
body_hash=$(printf '%s' "" | openssl dgst -sha256 -hex | sed 's/^.* //')
sig=$(printf 'v1\n%s\n%s\n%s\n%s\n%s' "$KEY_ID" "$ts" "GET" "$path" "$body_hash" \
| openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //')
LINK=$(curl -sS -o /dev/null -w '%{redirect_url}' "$HOST$path" \
-H "Raha-Key-Id: $KEY_ID" -H "Raha-Timestamp: $ts" -H "Raha-Signature: v1=$sig")
curl -sS -o invoice.pdf "$LINK"Errors#
Every error has the same body. A 422 also names the field in path.
{ "code": "timestamp_out_of_range", "message": "The timestamp is more than 300 seconds from the server clock." }{ "code": "invalid_field", "message": "customer.external_id is required.", "path": "customer.external_id" }| Status | code | Meaning and what to do |
|---|---|---|
| 401 | invalid_signature | The signature is missing or wrong. Check the base string, the secret (with its rsk_ prefix) and that you sign the exact bytes you send. |
| 401 | unknown_key | The key ID is not known. Check Raha-Key-Id. |
| 401 | timestamp_out_of_range | Raha-Timestamp is more than 300 seconds from Raha's clock. Fix your clock and sign again. |
| 401 | replayed | This signature was already used within the window. Sign again with a new timestamp. |
| 403 | ip_not_allowed | The request came from an address outside the owner's IP allow-list. |
| 403 | disconnected | The owner disconnected the connection. Reconnect it in the app. |
| 403 | polling_disabled | The connection's delivery is callback only. The owner can switch to polling or both. |
| 404 | not_found | An unknown customer, ticket or file. |
| 405 | method_not_allowed | The route does not accept that method. |
| 409 | id_conflict | An event with this id and a different body was stored earlier. Use a new id. |
| 413 | too_large | Events over 256 KiB, a file over 16 MiB, or another body over 4 KiB. |
| 415 | unsupported_media_type | Events must be application/json; a file's type is not accepted or does not match its bytes. |
| 422 | invalid_json | The body is not one JSON value. |
| 422 | invalid_field | A field is missing, unknown, of the wrong type or outside its limits; see path. |
| 422 | stale_event | occurred_at is more than 24 hours old or more than 5 minutes ahead. |
| 422 | unknown_file | A file_id that is not yours, has expired or was already used. |
| 422 | file_fetch_disabled | A file by url while the owner has not enabled file fetching. |
| 429 | rate_limited | Too many requests. Wait Retry-After seconds. |
| 503 | not_ready | Raha is starting. Retry after Retry-After seconds, with a new signature. |
| 5xx | unavailable | A temporary failure. Retry with backoff. |
Retrying. Retry network errors, timeouts, 429, 503 and other 5xx. Sign every attempt again with a fresh timestamp and keep the same event id: the idempotency key makes the retry safe. Do not retry other 4xx errors; fix the request.
Rate limits#
| Routes | Limit per connection |
|---|---|
POST /events | 20 requests per second, burst of 40 |
POST /files | 2 requests per second |
GET /events, POST /events/ack, GET /conversations/messages, GET /files/{file_id} | 5 requests per second together |
Above a limit Raha answers 429 rate_limited with a Retry-After header, and stores nothing from that request. Use batches for bulk loads.
HTTP/1.1 429 Too Many Requests
Retry-After: 1
Content-Type: application/json
{ "code": "rate_limited", "message": "Too many requests." }Callbacks and events from Raha
Raha sends your system the AI's replies, handoffs and status changes as events. The same events reach you as signed callbacks, through polling, or both.
Events Raha sends#
| Field | Notes |
|---|---|
event_id | evt_ and 26 characters (a to z, 2 to 7). Unique and stable: a repeated delivery of the same event has the same event_id. |
type | message.created, conversation.handoff, ticket.status_changed, typing or test.ping. |
occurred_at | RFC 3339. |
channel | website_chat or tickets. |
conversation_id | Raha's ID for the conversation (a UUID). Absent from test.ping. |
customer.external_id | Your customer ID. |
ticket.external_id | Your ticket ID, on the Tickets channel. |
type | Sent when | Extra fields |
|---|---|---|
message.created | An AI employee answers, or the owner or a team member writes from the Raha app (including a message Raha sends for the owner once approved). | message { id, text, files[] }, sender { kind: ai or human, name }. Each file: file_id (UUID), file_name, mime_type, url, url_expires_at (15 minutes). text is plain text of at most 4,096 characters. |
conversation.handoff | The AI handed the conversation to a person, or the owner took it over or returned it to the AI. | state (human or ai: who answers now), by (ai, owner or external), reason (a short code of at most 64 characters). |
ticket.status_changed | A ticket's status was changed in Raha (tickets with status sync on). | status: open, pending or closed. |
typing | The AI employee is writing (website chat, if the owner selected it). | None. |
test.ping | The owner pressed Send test in the app. | None. No conversation or customer. Answer 2xx. |
{
"event_id": "evt_mq4tx7b2kc5djw3npa6hz5r7ge",
"type": "message.created",
"occurred_at": "2026-10-21T10:15:09Z",
"channel": "tickets",
"conversation_id": "7d1c5f0e-8a34-4c1b-9b6e-2f3a41c8d9e0",
"customer": { "external_id": "cus_381" },
"ticket": { "external_id": "T-4512" },
"message": {
"id": "0199f5a1-8d3f-7e51-8d9a-1e3d0a8a2b12",
"text": "Hello Ali, I am sorry about the delay. Your refund was issued today; the receipt is attached.",
"files": [
{
"file_id": "0199f5a1-9e40-7f62-a1b0-2f4e1b9b3c23",
"file_name": "refund-receipt.pdf",
"mime_type": "application/pdf",
"url": "https://app.raha.to/d/EXAMPLE-SIGNED-LINK",
"url_expires_at": "2026-10-21T10:30:09Z"
}
]
},
"sender": { "kind": "ai", "name": "Sara" }
}{
"event_id": "evt_mq4tx7b2kc5djw3npa6hz5r7ge",
"type": "message.created",
"occurred_at": "2026-10-21T10:15:04Z",
"channel": "website_chat",
"conversation_id": "7d1c5f0e-8a34-4c1b-9b6e-2f3a41c8d9e0",
"customer": { "external_id": "cus_381" },
"message": {
"id": "0199f5a1-8d3f-7e51-8d9a-1e3d0a8a2b12",
"text": "Yes, we ship to Dubai.",
"files": []
},
"sender": { "kind": "ai", "name": "Sara" }
}{
"event_id": "evt_c6n3ud5tq2wk7ha4zrb5y2pfjm",
"type": "conversation.handoff",
"occurred_at": "2026-10-21T10:40:00Z",
"channel": "tickets",
"conversation_id": "7d1c5f0e-8a34-4c1b-9b6e-2f3a41c8d9e0",
"customer": { "external_id": "cus_381" },
"ticket": { "external_id": "T-4512" },
"state": "human",
"reason": "customer_asked_for_a_person",
"by": "ai"
}{
"event_id": "evt_h2x6bq4mrv7sd3kjw5pa6zngtc",
"type": "ticket.status_changed",
"occurred_at": "2026-10-21T11:02:00Z",
"channel": "tickets",
"conversation_id": "7d1c5f0e-8a34-4c1b-9b6e-2f3a41c8d9e0",
"customer": { "external_id": "cus_381" },
"ticket": { "external_id": "T-4512" },
"status": "closed"
}{
"event_id": "evt_p5k7wd2qh4ucx6mta3zrn2bjsg",
"type": "typing",
"occurred_at": "2026-10-21T10:15:02Z",
"channel": "website_chat",
"conversation_id": "7d1c5f0e-8a34-4c1b-9b6e-2f3a41c8d9e0",
"customer": { "external_id": "cus_381" }
}{
"event_id": "evt_t4e2s6tq7pi5ng3xkzr2w7ahcb",
"type": "test.ping",
"occurred_at": "2026-10-21T10:00:00Z",
"channel": "website_chat"
}Which types you receive is the owner's choice (the Events to send setting; test.ping always arrives). Ignore types and fields you do not recognise, and answer 2xx to them, so that Raha can add new ones.
The callback request#
Raha POSTs the event as JSON to your callback URL. The headers carry what you need to verify it. The body is exactly the bytes that were signed, so keep it raw until you have verified it.
| Header | Value |
|---|---|
Raha-Event-Id | The event's event_id. |
Raha-Timestamp | Unix seconds when Raha signed this attempt. |
Raha-Delivery-Attempt | 1, 2 or 3. |
Raha-Signature | v1=<hex>. During the 24 hours after a rotation: v1=<hex>,v1=<hex>, one per valid callback secret. |
POST /raha/callback HTTP/1.1
Host: api.yourcompany.example
Content-Type: application/json
Raha-Event-Id: evt_mq4tx7b2kc5djw3npa6hz5r7ge
Raha-Timestamp: 1792577705
Raha-Delivery-Attempt: 1
Raha-Signature: v1=00f9c640d997245ad13bd3be9cf84dbca83646fbd5abe1ac77945217b954c008,v1=77c635fe9345720802d9f06006cfd449c892e5d3324c8da866586c75541475f6
{"event_id":"evt_mq4tx7b2kc5djw3npa6hz5r7ge","type":"message.created", ...}Verifying a callback#
v1
<event_id>
<timestamp>
<sha256 of the raw body, lowercase hex>- Read the raw body bytes. Do not parse and re-serialise JSON before you hash it.
- Check that
Raha-Timestampis within 300 seconds of your clock. - Compute
sha256(raw body)as lowercase hex and build the base stringv1\n<Raha-Event-Id>\n<Raha-Timestamp>\n<hash>. - Compute the HMAC-SHA256 of it with your callback secret, including its `csk_` prefix, as lowercase hex.
- Compare it, in constant time, with each
v1=value inRaha-Signature. Accept the callback if any matches. (Two values appear only while a rotation overlaps.) - Only now parse the JSON. Drop the event if you already handled its
event_id; otherwise queue the work and answer2xxwithin 5 seconds.
Answer a failed verification with 401. Raha treats it as a permanent failure and does not retry it.
// npm install express
import express from "express";
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
// The callback secret (csk_...). During a rotation keep both the new and the previous one, separated by commas.
const CALLBACK_SECRETS = (process.env.RAHA_CALLBACK_SECRETS ?? "").split(",").filter(Boolean);
const TOLERANCE_SECONDS = 300;
function verifyCallback(headers, rawBody) {
const eventId = headers["raha-event-id"];
const timestamp = headers["raha-timestamp"];
const seconds = Number(timestamp);
if (!eventId || !Number.isFinite(seconds) || Math.abs(Date.now() / 1000 - seconds) > TOLERANCE_SECONDS) return false;
const bodyHash = createHash("sha256").update(rawBody).digest("hex");
const base = ["v1", eventId, timestamp, bodyHash].join("\n");
// The header holds one signature, or two while a secret rotates: "v1=<hex>,v1=<hex>". Accept a match with either.
const received = String(headers["raha-signature"] ?? "")
.split(",")
.map((part) => part.trim())
.filter((part) => part.startsWith("v1="))
.map((part) => part.slice(3));
return CALLBACK_SECRETS.some((secret) => {
const expected = Buffer.from(createHmac("sha256", secret).update(base).digest("hex"));
return received.some((signature) => {
const given = Buffer.from(signature);
return given.length === expected.length && timingSafeEqual(given, expected);
});
});
}
const handled = new Set(); // use a database or Redis with a 7-day expiry in production
const app = express();
// Keep the body raw: the signature covers the exact bytes, so verify before you parse.
app.post("/raha/callback", express.raw({ type: "*/*", limit: "1mb" }), (req, res) => {
if (!verifyCallback(req.headers, req.body)) return res.sendStatus(401);
const event = JSON.parse(req.body.toString("utf8"));
if (handled.has(event.event_id)) return res.sendStatus(200); // a retry: already handled
handled.add(event.event_id);
// Queue the work and answer within 5 seconds. Raha only needs a 2xx.
res.sendStatus(200);
});
app.listen(8080);# pip install flask
import hashlib
import hmac
import os
import time
from flask import Flask, request
# The callback secret (csk_...). During a rotation keep both the new and the previous one, separated by commas.
CALLBACK_SECRETS = [s for s in os.environ.get("RAHA_CALLBACK_SECRETS", "").split(",") if s]
TOLERANCE_SECONDS = 300
handled = set() # use a database or Redis with a 7-day expiry in production
app = Flask(__name__)
def verify_callback(headers, raw_body):
event_id = headers.get("Raha-Event-Id")
timestamp = headers.get("Raha-Timestamp")
try:
seconds = int(timestamp)
except (TypeError, ValueError):
return False
if not event_id or abs(time.time() - seconds) > TOLERANCE_SECONDS:
return False
body_hash = hashlib.sha256(raw_body).hexdigest()
base = "\n".join(["v1", event_id, timestamp, body_hash]).encode()
# The header holds one signature, or two while a secret rotates: "v1=<hex>,v1=<hex>". Accept a match with either.
received = [part.strip()[3:] for part in headers.get("Raha-Signature", "").split(",") if part.strip().startswith("v1=")]
for secret in CALLBACK_SECRETS:
expected = hmac.new(secret.encode(), base, hashlib.sha256).hexdigest().encode()
if any(hmac.compare_digest(expected, signature.encode()) for signature in received):
return True
return False
@app.post("/raha/callback")
def raha_callback():
raw_body = request.get_data() # the raw bytes: verify before you parse
if not verify_callback(request.headers, raw_body):
return "", 401
event = request.get_json(force=True)
if event["event_id"] in handled:
return "", 200 # a retry: already handled
handled.add(event["event_id"])
# Queue the work and answer within 5 seconds. Raha only needs a 2xx.
return "", 200<?php
// callback.php: point the callback URL at it. PHP 8.
// The callback secret (csk_...). During a rotation keep both the new and the previous one, separated by commas.
$secrets = array_filter(explode(",", getenv("RAHA_CALLBACK_SECRETS") ?: ""));
const TOLERANCE_SECONDS = 300;
function verify_callback(array $secrets, string $rawBody): bool {
$eventId = $_SERVER["HTTP_RAHA_EVENT_ID"] ?? "";
$timestamp = $_SERVER["HTTP_RAHA_TIMESTAMP"] ?? "";
if ($eventId === "" || !ctype_digit($timestamp) || abs(time() - (int) $timestamp) > TOLERANCE_SECONDS) {
return false;
}
$base = implode("\n", ["v1", $eventId, $timestamp, hash("sha256", $rawBody)]);
// The header holds one signature, or two while a secret rotates: "v1=<hex>,v1=<hex>". Accept a match with either.
$received = [];
foreach (explode(",", $_SERVER["HTTP_RAHA_SIGNATURE"] ?? "") as $part) {
$part = trim($part);
if (str_starts_with($part, "v1=")) {
$received[] = substr($part, 3);
}
}
foreach ($secrets as $secret) {
$expected = hash_hmac("sha256", $base, $secret);
foreach ($received as $signature) {
if (hash_equals($expected, $signature)) {
return true;
}
}
}
return false;
}
$rawBody = file_get_contents("php://input"); // the raw bytes: verify before you parse
if (!verify_callback($secrets, $rawBody)) {
http_response_code(401);
exit;
}
$event = json_decode($rawBody, true);
// Skip an event_id you already handled (database or cache lookup), otherwise queue the work.
// Answer within 5 seconds. Raha only needs a 2xx.
http_response_code(200);# Recompute the signature of a callback you saved: body.json is the exact raw body, the other values are its headers.
EVENT_ID="evt_mq4tx7b2kc5djw3npa6hz5r7ge"; TS="1792577705"; SECRET="csk_EXAMPLE0ONLY0not0a0real0callback0secret0aaa"
BODY_HASH=$(openssl dgst -sha256 -hex < body.json | sed 's/^.* //')
printf 'v1\n%s\n%s\n%s' "$EVENT_ID" "$TS" "$BODY_HASH" | openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //'
# The output must equal one of the v1=<hex> values in the Raha-Signature header.Test vector
| Input | Value |
|---|---|
| Callback secret (current) | csk_EXAMPLE0ONLY0not0a0real0callback0secret0aaa |
| Callback secret (previous) | csk_EXAMPLE0ONLY0previous0callback0secret0aaaaa |
Raha-Event-Id | evt_mq4tx7b2kc5djw3npa6hz5r7ge |
Raha-Timestamp | 1792577705 |
| Raw body (exact bytes) | {"event_id":"evt_mq4tx7b2kc5djw3npa6hz5r7ge","type":"message.created","occurred_at":"2026-10-21T10:15:04Z","channel":"website_chat","conversation_id":"7d1c5f0e-8a34-4c1b-9b6e-2f3a41c8d9e0","customer":{"external_id":"cus_381"},"message":{"id":"0199f5a1-8d3f-7e51-8d9a-1e3d0a8a2b12","text":"Yes, we ship to Dubai.","files":[]},"sender":{"kind":"ai","name":"Sara"}} |
| sha256 of the body | 31c1a380660ada0ca8468c5077a60dd19bc9baaab6711eb099a42cccfb01419d |
| Signature with the current secret | 00f9c640d997245ad13bd3be9cf84dbca83646fbd5abe1ac77945217b954c008 |
| Signature with the previous secret | 77c635fe9345720802d9f06006cfd449c892e5d3324c8da866586c75541475f6 |
Delivery, retries and the breaker#
| Your answer | What Raha does |
|---|---|
Any 2xx within 5 seconds | The event is delivered. The response body is ignored. |
A timeout, 408, 425, 429 or any 5xx | Retried: at most 3 attempts in about 60 seconds. A Retry-After of up to 60 seconds is honoured. |
Any other answer, including a redirect, 401, 403 and 404 | The delivery fails and is not retried. |
| A callback URL that fails the URL rules (not HTTPS, private address, bad certificate) | The delivery fails; see the URL rules. |
- Raha sends one event at a time per conversation, oldest first. While one event is retrying, later events of that conversation wait behind it.
- What counts as delivered: a
2xxcallback, or an acknowledged poll. The owner's Inbox shows the message as delivered. - The breaker. After five failed deliveries in a row, Raha marks the connection's callbacks as failing, shows "callback failing" to the owner and notifies them. Raha keeps trying with one probe a minute and restores the connection at the first success. The owner's Send test also closes it.
- Nothing is lost. Events are kept for 7 days. When delivery includes polling,
GET /eventsstill returns every event while callbacks fail; with callback-only delivery the owner can switch to both, andGET /conversations/messagesalways returns the conversation.
Idempotency#
- A callback or a poll can deliver the same event more than once. Deduplicate by `event_id`. A message also has a stable
message.id. - When you use both callbacks and polling, the two carry the same
event_ids: record the IDs you handled in one place. - On your side, always send your own stable event
id. After a timeout, send the event again with the sameid.
Testing the connection#
In the app, Send test queues a signed test.ping to your callback URL and shows the HTTP status your endpoint answered. A delivered ping also moves a new connection to Connected. The app lists the latest 50 deliveries with their state, attempts and last failure, without message content.
Behaviour notes
What to expect from Raha in common situations.
| Situation | What happens |
|---|---|
| A human agent of yours writes | Send it as message.agent_created. The AI stops answering that conversation. This always happens; it does not depend on any setting. |
| Your system hands a conversation over or back | conversation.updated with handoff: takeover or resume. It applies only if the owner allowed it (Takeover, or Takeover and resume). With handoff control Off the request is accepted and ignored: an external resume never gives a conversation back to the AI unless the owner allows it. |
| The owner takes over, resumes or writes in the app | You receive conversation.handoff (by: owner) and, for a message, message.created with sender.kind: human. |
| The AI hands over | You receive conversation.handoff with state: human, by: ai and a reason. |
| A customer message is old | The AI answers only messages younger than 15 minutes. An older message is stored for the owner but not answered. |
| An event is too old | An event whose occurred_at is more than 24 hours in the past, or more than 5 minutes ahead, is refused with 422 stale_event. Raha does not import older history. |
| Several tickets from one customer | One conversation per ticket, one customer. Names, photos and leads stay with the customer. |
| A customer writes on a closed ticket | The conversation reopens (and, with status sync on, the status becomes open). |
| Ticket status sync (on by default) | Your open and pending map to Raha's open and pending; solved and closed map to closed. A status set in Raha comes back as ticket.status_changed. |
| Order of events | Events of one conversation are processed in the order Raha accepted them. Send them in the order they happened. |
| The same event twice | One message. The second answer says duplicate. |
| Customer data | E-mail and phone are encrypted at rest and shown only to workspace members who may read channels. Message text, subjects and attributes are treated as data, never as instructions. |
| Your plan changes | The channels are included in Business, Pro and the free trial. Solo cannot create them. If a workspace loses the plan, your requests are still accepted and stored, but the AI stops replying and the app shows the channel as not included; the owner's own messages still go out. Regaining the plan resumes AI replies, with nothing else to do. |
| A connection is disconnected | The next request is refused with 403 disconnected. |
Security notes for integrators
Read this before you build a website chat.
The right shape for a website chat#
Visitor's browser
Your chat widget. No Raha key, no signature. It talks only to your server.
Your server
Authenticates the visitor, sets customer.external_id, validates the message, signs it, calls Raha. Verifies callbacks and pushes replies to the widget.
Raha
Stores the event, the AI employee answers, the reply returns by signed callback or polling.
- Keep secrets on the server. Store
rsk_andcsk_in an environment variable or secret manager. Keep them out of source control, client bundles, mobile apps, logs, error reports and support tickets. - Your server decides who the customer is. Derive
customer.external_idfrom your own session or login. Never accept it from the browser: a visitor who can choose it could write as, and read the replies of, another customer. - Validate before you forward. Check length (4,000 characters), file types and sizes, and rate-limit visitors on your side, so one visitor cannot use up your connection's request budget or the AI's attention.
- Push replies to the widget from your own server. Receive Raha's callback (or poll), then deliver it to the right visitor over your own WebSocket, Server-Sent Events or polling endpoint.
- Verify every callback. Check the signature on the raw body in constant time, check the timestamp, deduplicate by
event_id, and only then parse and act. An unauthenticated callback endpoint lets anyone speak as Raha to your customers. - Treat content as untrusted. Customer text, names, ticket subjects, attributes and file names are data. Render messages as text, never as HTML you did not escape; Raha's replies are plain text. Scan uploaded files as you would any upload.
- Use HTTPS everywhere and sync your clocks. Requests more than 300 seconds off are refused.
- Restrict where requests come from. If your servers have fixed addresses, ask the owner to set the IP allow-list.
- Do not log secrets or signatures. Log the key ID, event IDs and status codes instead.
- Share only what is needed. E-mail, phone and attributes are optional; send only what helps the conversation.
Changelog
Changes to the Custom API. The version is in the base URL and in the signature scheme (v1).
| Version | Changes |
|---|---|
| v1.0.0, 2026 | First release. Website chat and Tickets channels. Signed requests (v1 HMAC-SHA256) with a 300-second window and replay refusal. Routes POST /events, POST /files, GET /events, POST /events/ack, GET /conversations/messages, GET /files/{file_id}. Inbound events message.created, message.agent_created, conversation.updated, customer.updated. Outbound events message.created, conversation.handoff, ticket.status_changed, typing, test.ping. Signed callbacks with retries and a breaker; polling with acknowledgement and 7-day retention. Secret rotation with a 24-hour overlap; IP allow-list. |
Within v1, Raha may add optional fields, event types and error codes. Ignore what you do not recognise. A breaking change would be a new version.
Questions about the API? Write to [email protected].
