Skip to content

MiDesk Webhook API

Documentation for the endpoint that receives webhooks forwarded by MiDesk.

POST /api/v1/webhooks/midesk

MiDesk does not retry on a non-2xx response. The endpoint processes in this order:

  1. Verify the HMAC signature on the raw body.
  2. Parse JSON + validate the payload against the schema — synchronously, BEFORE storing.
  3. Valid → write to the webhook_events table, return 200, then upsert ticket/contact/comment asynchronously.
  4. 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 400 is 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 (always 200, validate async) — the opposite of the current design.

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):

EnvDefaultMeaning
MIDESK_HMAC_SECRET— (required)Secret used to sign/verify
MIDESK_SIGNATURE_HEADERx-midesk-signatureHeader carrying the signature
MIDESK_SIGNATURE_ENCODINGhexhex 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.

HeaderRequiredNotes
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.

FieldTypeRequiredDescription
ticket_idstring✅Ticket code, includes the #, e.g. #3668890. Stored in the DB after stripping the #.
titlestring✅Ticket title/summary
prioritynumber✅0 = Unset, 1 = Low, 2 = Medium, 3 = High, 4 = Urgent
statusstring✅new | open | pending | solved | closed
channelstring✅voice | facebook | zalo | email | api | chat
requesterstring✅ID of the contact/customer who raised the request
requester_typestring✅contact | agent
created_atstring✅YYYY-MM-DD HH:mm:ss, in GMT+7 (no timezone marker)
updated_atstring✅YYYY-MM-DD HH:mm:ss, in GMT+7
tickets_detailarray<object>❌List of messages in this forward. Each element with content → 1 comment. Empty/absent list = status-only forward (see rules below)
fullnamestring❌Contact’s full name
emailstring[]❌Contact’s email addresses. Stored as JSONB verbatim
phonestring[]❌Contact’s phone numbers. Stored as JSONB verbatim

Each tickets_detail[] element (object):

FieldTypeRequiredDescription
contentstring | null❌Comment content. Empty/null = this item is skipped (no comment created)
typestring | null❌Message type (e.g. comment, note)
privateboolean❌Internal comment (not shown to the customer). Defaults to false
attachmentsarray❌Comment attachments. Stored as JSONB verbatim
created_bystring | null❌ID of the message author (agent/contact)

Processing rules:

  • Each tickets_detail[] element with content → creates 1 comment. Items with empty/null content are skipped.
  • tickets_detail is an empty list or absent → the ticket is updated but NO comment is created (status-only forward, e.g. an agent flips open → 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_at are parsed as Asia/Ho_Chi_Minh (GMT+7) and stored as timestamptz (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.

Duplicates are prevented at 2 levels:

  1. 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 same event_id as the first delivery.
  2. 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_id but with a new message in tickets_detail/a new updated_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.

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"
}
FieldTypeDescription
receivedbooleanAlways true
event_idstring (uuid)Record ID in webhook_events. For a duplicate payload, the event_id of the original event is returned.

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.

Invalid or missing HMAC signature. Nothing is stored.

{
"statusCode": 401,
"message": "Invalid signature",
"requestId": "33438fc2-78a1-48cf-ad15-fe19b6d28004"
}

Rate limit exceeded (default 60 requests / 10 seconds).

{
"statusCode": 429,
"message": "ThrottlerException: Too Many Requests",
"requestId": "408298b3-c37f-45d9-826c-39955d8d6ac5"
}

Every error response follows this format:

FieldTypeDescription
statusCodenumberHTTP status
messagestringError description
requestIdstring | nullRequest id (from the x-request-id header, or generated)
Terminal window
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.

{
"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"]
}
{
"received": true,
"event_id": "3f1c8e9a-2b7d-4c6e-9a1f-8d0e5b2c4a6f"
}

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:

StatusMeaning
receivedJust stored, awaiting processing
processedTicket/contact/comment upserted successfully
failedProcessing 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)
deadRetried 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.