MiDesk Webhook API
Documentation for the endpoint that receives webhooks forwarded by MiDesk.
POST /api/v1/webhooks/mideskKey principle (read first)
Section titled “Key principle (read first)”MiDesk does not retry on a non-2xx response. The endpoint processes in this order:
- Verify the HMAC signature on the raw body.
- Parse JSON + validate the payload against the schema — synchronously, BEFORE storing.
- Valid → write to the
webhook_eventstable, return200, then upsert ticket/contact/comment asynchronously. - Invalid (broken JSON or bad schema) → return
400, store nothing.
Consequence for the caller (MiDesk): there are 3 cases that return non-2xx — 400 (bad payload / broken JSON), 401 (invalid/missing signature), 429 (rate limit). 200 means “the payload is valid, received and stored safely”, not that processing (the upsert) has finished — that step runs async.
⚠️ Trade-off: because MiDesk does not retry, a payload that gets a
400is lost for good (never stored in the DB). To keep a reconciliation trail, every rejection logs a warning with the base64 payload (payload_b64=...). If you need “never lose data”, you must switch back to a store-first strategy (always200, validate async) — the opposite of the current design.
Authentication — HMAC-SHA256
Section titled “Authentication — HMAC-SHA256”MiDesk signs each request and sends the signature in a header. The app verifies by recomputing the HMAC over the raw request body (the original bytes, before JSON parsing) and comparing with crypto.timingSafeEqual.
signature = HMAC_SHA256(secret, raw_request_body)The header name, encoding, and prefix are all configured via env (the exact MiDesk spec is not finalized — once it is, only .env needs updating, not code):
| Env | Default | Meaning |
|---|---|---|
MIDESK_HMAC_SECRET | — (required) | Secret used to sign/verify |
MIDESK_SIGNATURE_HEADER | x-midesk-signature | Header carrying the signature |
MIDESK_SIGNATURE_ENCODING | hex | hex or base64 |
MIDESK_SIGNATURE_PREFIX | (empty) | E.g. sha256= if the signature is prefixed |
A wrong, missing, wrong-length, or missing-prefix signature (when a prefix is configured) → 401. The secret and signature are never logged.
Request
Section titled “Request”Headers
Section titled “Headers”| Header | Required | Notes |
|---|---|---|
X-Midesk-Signature | ✅ | HMAC-SHA256 signature of the raw body (per the env vars above). Header name is configurable via env. |
Content-Type | ❌ | The body is read raw for every content-type and parsed as JSON afterwards. Sending application/json is the norm, but other content-types are accepted too (as long as the body is valid JSON). A body that cannot be parsed as JSON → 400. |
Body limit ~1MB.
JSON per the MiDesk spec. Properties stay snake_case.
| Field | Type | Required | Description |
|---|---|---|---|
ticket_id | string | ✅ | Ticket code, includes the #, e.g. #3668890. Stored in the DB after stripping the #. |
title | string | ✅ | Ticket title/summary |
priority | number | ✅ | 0 = Unset, 1 = Low, 2 = Medium, 3 = High, 4 = Urgent |
status | string | ✅ | new | open | pending | solved | closed |
channel | string | ✅ | voice | facebook | zalo | email | api | chat |
requester | string | ✅ | ID of the contact/customer who raised the request |
requester_type | string | ✅ | contact | agent |
created_at | string | ✅ | YYYY-MM-DD HH:mm:ss, in GMT+7 (no timezone marker) |
updated_at | string | ✅ | YYYY-MM-DD HH:mm:ss, in GMT+7 |
tickets_detail | array<object> | ❌ | List of messages in this forward. Each element with content → 1 comment. Empty/absent list = status-only forward (see rules below) |
fullname | string | ❌ | Contact’s full name |
email | string[] | ❌ | Contact’s email addresses. Stored as JSONB verbatim |
phone | string[] | ❌ | Contact’s phone numbers. Stored as JSONB verbatim |
Each tickets_detail[] element (object):
| Field | Type | Required | Description |
|---|---|---|---|
content | string | null | ❌ | Comment content. Empty/null = this item is skipped (no comment created) |
type | string | null | ❌ | Message type (e.g. comment, note) |
private | boolean | ❌ | Internal comment (not shown to the customer). Defaults to false |
attachments | array | ❌ | Comment attachments. Stored as JSONB verbatim |
created_by | string | null | ❌ | ID of the message author (agent/contact) |
Processing rules:
- Each
tickets_detail[]element withcontent→ creates 1 comment. Items with empty/nullcontentare skipped. tickets_detailis an empty list or absent → the ticket is updated but NO comment is created (status-only forward, e.g. an agent flipsopen→solved).- Unknown fields outside the spec → not rejected; a warning is logged and they are kept intact in the raw payload (forward-compatible).
created_at/updated_atare parsed asAsia/Ho_Chi_Minh(GMT+7) and stored astimestamptz(UTC). E.g.2026-07-01 09:15:00→2026-07-01T02:15:00Z.- A ticket may be forwarded multiple times (each time with 0..N comments or a status change). Tickets and comments are stored separately.
Idempotency
Section titled “Idempotency”Duplicates are prevented at 2 levels:
- Event level —
dedupe_hash = sha256(ticket_id | updated_at | content-of-all-items). Sending the exact same payload repeatedly → only 1 event is created. The response returns the sameevent_idas the first delivery. - Comment level — each comment has its own hash from
ticket_id + created_by + type + private + content. The same message resent (even inside a different forward) → no duplicate comment; a different message → its own comment.
- Same
ticket_idbut with a new message intickets_detail/a newupdated_at→ the ticket is updated and the new comment is added. - A stale snapshot (late retry, out-of-order delivery) does not overwrite a newer ticket state.
Responses
Section titled “Responses”200 OK
Section titled “200 OK”The payload is valid and the event was written successfully. Returned even when the payload is a duplicate (idempotent — see event_id below).
{ "received": true, "event_id": "3f1c8e9a-2b7d-4c6e-9a1f-8d0e5b2c4a6f"}| Field | Type | Description |
|---|---|---|
received | boolean | Always true |
event_id | string (uuid) | Record ID in webhook_events. For a duplicate payload, the event_id of the original event is returned. |
400 Bad Request
Section titled “400 Bad Request”The body is not valid JSON, or the JSON is well-formed but fails the schema (missing required field, wrong type, status/channel outside the enum, malformed created_at/updated_at…). Nothing is stored. message lists the validation details.
{ "statusCode": 400, "message": "Payload validation failed: status must be one of the following values: new, open, pending, solved, closed | created_at must be \"YYYY-MM-DD HH:mm:ss\"", "requestId": "9b2f1c7e-4a3d-4e8b-9c1a-2d5f6b8e0a4c"}Unknown fields outside the spec do not cause a
400— they are logged as a warning and kept intact in the raw payload (forward-compatible). Only fields with the wrong type / missing / outside the enum are rejected.
401 Unauthorized
Section titled “401 Unauthorized”Invalid or missing HMAC signature. Nothing is stored.
{ "statusCode": 401, "message": "Invalid signature", "requestId": "33438fc2-78a1-48cf-ad15-fe19b6d28004"}429 Too Many Requests
Section titled “429 Too Many Requests”Rate limit exceeded (default 60 requests / 10 seconds).
{ "statusCode": 429, "message": "ThrottlerException: Too Many Requests", "requestId": "408298b3-c37f-45d9-826c-39955d8d6ac5"}Common error shape
Section titled “Common error shape”Every error response follows this format:
| Field | Type | Description |
|---|---|---|
statusCode | number | HTTP status |
message | string | Error description |
requestId | string | null | Request id (from the x-request-id header, or generated) |
Examples
Section titled “Examples”curl (self-signing the HMAC with openssl)
Section titled “curl (self-signing the HMAC with openssl)”SECRET="your-midesk-secret"BODY='{"ticket_id":"#3668890","title":"Khách hỏi về đơn hàng","priority":2,"status":"open","channel":"facebook","requester":"ct_10293","requester_type":"contact","created_at":"2026-07-01 09:15:00","updated_at":"2026-07-01 09:20:11","tickets_detail":[{"content":"Shop ơi đơn của mình tới đâu rồi?","type":"comment","private":false,"attachments":[],"created_by":"ct_10293"}],"fullname":"Nguyễn Văn A","email":["vana@example.com"],"phone":["0901234567"]}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $2}')
curl -s -X POST http://localhost:3000/api/v1/webhooks/midesk \ -H "Content-Type: application/json" \ -H "X-Midesk-Signature: $SIG" \ --data-binary "$BODY"Use
--data-binary(not-d) so the body is sent byte-for-byte identical to the body that was signed — otherwise the signature will not match.
Sample request body
Section titled “Sample request body”{ "ticket_id": "#3668890", "title": "Khách hỏi về đơn hàng", "priority": 2, "status": "open", "channel": "facebook", "requester": "ct_10293", "requester_type": "contact", "created_at": "2026-07-01 09:15:00", "updated_at": "2026-07-01 09:20:11", "tickets_detail": [ { "content": "Shop ơi đơn của mình tới đâu rồi?", "type": "comment", "private": false, "attachments": [], "created_by": "ct_10293" } ], "fullname": "Nguyễn Văn A", "email": ["vana@example.com"], "phone": ["0901234567"]}Sample response
Section titled “Sample response”{ "received": true, "event_id": "3f1c8e9a-2b7d-4c6e-9a1f-8d0e5b2c4a6f"}Lifecycle after receipt (reference)
Section titled “Lifecycle after receipt (reference)”200 only means the event was stored (and the payload was valid). Processing runs async; track its state in the status column of webhook_events:
| Status | Meaning |
|---|---|
received | Just stored, awaiting processing |
processed | Ticket/contact/comment upserted successfully |
failed | Processing error (transient DB error, transaction failure…), will retry. The payload was already validated at the receive step, so schema-related failures are rare — except when replaying/reprocessing an old event after a schema change (validation is re-run as a defensive layer) |
dead | Retried more than 5 times, needs manual handling |
Internal retries use increasing backoff: 30s → 2m → 10m → 30m → 2h. This is the app’s own retry and is unrelated to MiDesk.