Webhooks
Get notified when async OCR jobs complete by providing a callback URL.
How It Works
When you submit an OCR request in async mode with a webhook_url, OpenOCR will POST the results to your URL when processing completes (or fails).
- Submit an async OCR request with
webhook_url. A PDF request of more than 20 pages (page_countover 20, or a longer base64 PDF sent withoutpage_count) on an engine that cannot read PDFs directly runs in the background, so it sends its webhook withoutasyncmode too. So does any PDF sent to a scale-to-zero open model (see Scheduling batches), whatever its page count. - Receive a
202 Acceptedresponse immediately - OpenOCR processes the document in the background
- Results are POSTed to your webhook URL
Exception when credits are short. If your balance is too low for the page_count you sent, OpenOCR lowers the count to what your credits cover. Without page_count, a base64 PDF whose whole document your balance cannot cover is refused with 402 instead, before anything is read. This applies to a PDF submitted without mode: "async" that relied on the over-20-pages rule. When the lowered count is 20 or fewer, it runs synchronously: you get the result in the HTTP response (not a 202) and no webhook is sent. A request with explicit mode: "async" still returns 202 and sends its webhook. Check the response before waiting for a webhook.
OCR history off. mode: "async" needs OCR history on. With history off it is refused with 400 history_disabled before anything is charged. The exception is a scale-to-zero open model given a webhook_url or a PDF. The refusal includes a large PDF sent with mode: "async"; send a large PDF without mode and it is accepted (see History off and large PDFs).
Example Request
curl -X POST https://api.open-ocr.com/v1/ocr \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{
"input": {
"type": "url",
"url": "https://example.com/invoice.pdf"
},
"engine": "mistral-mistral-ocr-4-1",
"mode": "async",
"page_count": 10,
"webhook_url": "https://your-server.com/ocr-callback"
}'Webhook Payload
Your endpoint receives a JSON POST with the full OCR result:
Success Payload
{
"event": "ocr.completed",
"request_id": "req_abc123",
"status": "succeeded",
"engine": "mistral-mistral-ocr-4-1",
"provider_latency_ms": 1250,
"provider_error": null,
"extracted_text": "INVOICE #1234\nDate: 2026-02-23\nTotal: $1,250.00",
"extracted_text_preview": "INVOICE #1234\nDate: 2026-02-23\n...",
"cost_usd": 0.012,
"pages": 3,
"pages_total": 3,
"warning": null,
"timestamp": "2026-02-23T14:05:11.123+00:00"
}Failure Payload
{
"event": "ocr.failed",
"request_id": "req_def456",
"status": "refunded",
"engine": "mistral-mistral-ocr-4-1",
"provider_latency_ms": 60000,
"provider_error": "Engine timeout after 60s",
"extracted_text": null,
"extracted_text_preview": null,
"cost_usd": 0,
"warning": null,
"timestamp": "2026-02-23T14:06:11.123+00:00"
}A failure whose engine never ran carries cost_usd: 0, as above. When the engine did run before failing, the provider bills us for the work its model did and we pass that through at cost — so cost_usd is non-zero. The payload is otherwise identical — a charged failure reports the same status it would have reported for free, and explains itself through provider_error:
{
"event": "ocr.failed",
"request_id": "req_def789",
"status": "refunded",
"engine": "google-gemini-3.1-flash-lite",
"provider_latency_ms": 18400,
"provider_error": "Engine timed out after generating a partial response",
"extracted_text": null,
"extracted_text_preview": null,
"cost_usd": 0.0004,
"warning": "the engine ran and produced billable usage; you were charged the provider's cost for the attempt ($0.0004); actual usage may exceed the initial estimate",
"timestamp": "2026-02-23T14:07:11.123+00:00"
}Full policy on the Error Codes page.
Payload Fields
| Field | Type | Description |
|---|---|---|
| event | string | "ocr.completed" when the request succeeded, "ocr.failed" otherwise. Before November 2026 failures also said "ocr.completed" |
| request_id | string | The original request ID from your submission |
| status | string | 'succeeded' on success. On failure, 'partial' when the preview holds some recovered text, otherwise 'refunded'. 'failed' when the router could not read the request record back from its database, when an engine refused the request for its own rate limit, or when a worker stopped during a backup-engine attempt and the charge was not refunded. 'refunded' describes the outcome of the request, not the amount: check cost_usd, which can be above 0 (see Failed, partial and refunded events) |
| engine | string | Engine ID that processed the request. When a backup engine (request fallback) produced the text, this names the backup engine; when a retired engine's replacement ran, it names the replacement |
| extracted_text | string | null | Full extracted text. Null on most failures. Also null when OCR history is off: a large PDF success then has no text in the webhook (see content_availability). A partial result carries its recovered text here when history is on and the engine stopped at its output allowance or for looping; after a timeout it is null |
| extracted_text_preview | string | null | Truncated preview of extracted text. On a partial result it holds up to 2,000 characters of the recovered text, the only copy after a timeout. Normally null when OCR history is off |
| content_availability | string | "result_not_retained" on a success with no text because OCR history is off: a large PDF, or any request whose history was switched off while it ran (extracted_text is null). Absent when history is on. Scale-to-zero open models always send it, with "retained", "ephemeral" or "result_not_retained" (see below). See History off and large PDFs |
| cost_usd | number | Credits charged in USD. Normally 0 when the engine never ran; the provider's cost for the attempt, passed through at cost, when it ran and then failed. It can also be above 0 on a refunded event if the refund could not be recorded |
| provider_latency_ms | integer | null | Engine processing time in ms |
| provider_error | string | null | Error message if processing failed |
| pages | integer | Success only, when known: pages processed and billed |
| pages_total | integer | Success only, when known: pages in the source document. Larger than pages means only part of it was processed: because of page_count or the engine's max_pages limit, or because a URL input is not counted before it is read |
| warnings | string[] | When there is something to report, e.g. "document has 3 pages; processed 1. A read stops at page_count when one is sent, and at the engine's max_pages; ..." A failed large-PDF job can also list the pages that failed here |
| warning | string | null | A note about the result: an empty or possibly looping answer on a success, the sentence explaining a charge on a failure, or a retired-engine replacement |
| attempts | object[] | Present when a backup engine was tried (the request's fallback). One entry per engine, in order: engine, outcome, error_code and cost_usd. A success by the backup engine is an ocr.completed event |
| stop_reason | string | On a failed or partial result: "output_limit_reached" (partial only) when the engine used its whole output allowance, or "output_loop" when it was stopped for repeating itself |
| output_limit | object | Details of that output cut-off, when there was one |
| replacement | object | Present when you named a retired engine and its designated replacement ran instead |
| cold_start | object | Present when the request woke a scale-to-zero model: the wait and the wake fee charged |
| metadata | object | Extra result details when OCR history is on. With history off it carries only cold_start, if any |
| job_id | string | Large-PDF and scale-to-zero jobs: the background job's ID |
| timestamp | string | ISO 8601 time the webhook was sent. If pages is absent (failures, or a count the router could not determine), fetch GET /v1/ocr/{request_id} |
Scale-to-zero open models send a different body. It carries event, event_id, request_id, status ("succeeded" or "failed"; never "partial" or "refunded"), engine, provider_latency_ms, cost_usd, cost_debited (the same amount), current_balance_usd, content_availability, extracted_text and a receipt object, plus pages, pages_total, pages_failed, warnings, cold_start (with metadata and a warning about the wake), job_id and, on a failure, error_code when known. It has no provider_error, extracted_text_preview or timestamp.
Failed, partial and refunded events
- Partial reads arrive as
ocr.failed. When an engine recovers only some of the text (a timeout, the output allowance or the loop check), the event isocr.failedwithstatus: "partial". You are charged for the work the engine did (cost_usdis the amount debited). Where the text is depends on why the engine stopped. If it used its whole output allowance or was stopped for repeating itself (stop_reasonis set), the recovered text is inextracted_textwhen OCR history is on. If it timed out,extracted_textis null and the recovered text is only inextracted_text_preview, cut to 2,000 characters. With history off, expect both to be null. A receiver that only acceptsocr.completedwill drop that paid text, so handleocr.failedand, whenstatusispartial, readextracted_textand fall back toextracted_text_preview. status: "refunded"does not always meancost_usdis 0. OpenOCR is a pass-through: if the provider billed us for an attempt that then failed, that cost stays charged andcost_usdshows it, as in the second failure payload above. The same happens if the refund itself could not be recorded. Treatcost_usdas the amount charged, andstatusas the outcome.- A large PDF that could not be prepared (before any engine read a page) is refunded when no provider cost was incurred:
ocr.failed,status: "refunded",cost_usd: 0. This event is built by the repair sweep, so it arrives about 30 seconds or more after the failure, not instantly. If the refund itself errors, the request waits for the stale-request sweeper and the event comes later.
History off and large PDFs
If OCR history is off for your account, OpenOCR does not save the text of a large PDF (only its one-time job result, see PDF routing), so a successful webhook for it has extracted_text: null, extracted_text_preview: null and content_availability: "result_not_retained". With history on, the field is absent and the text is present. The request is still charged and reported as succeeded, and GET /v1/ocr/{request_id} returns 410 result_not_retained. Turn history on before you submit large PDFs if you need the text through a webhook or a later fetch. With history off, send the PDF without mode: "async": an explicit async request is refused with 400 history_disabled.
Webhooks for large PDFs, success or failure, are queued by a background repair process with a 30-second grace period, so the first delivery arrives about 30 seconds or more after the job finishes. They carry the job's job_id.
Retry Behavior
OpenOCR makes up to 6 delivery attempts, about 43 minutes in all, waiting 5 seconds, 30 seconds, 2 minutes, 10 minutes and 30 minutes between them, if your endpoint returns a non-2xx status or times out (10s per HTTP attempt). An endpoint that times out waits at least 30 seconds before its next delivery. Because a delivery can arrive twice, use the X-OpenOCR-Event-Id header to ignore one you have already handled. Signing-secret lookups also have a 10-second limit; a failed lookup consumes an attempt and never sends an unsigned callback. Redirects are not followed.
Security
Webhook signing version 2 is active in production following the 2026-10-17T18:10:00.000Z cutover. Callbacks are signed with your account webhook signing secret. Reveal or rotate it in Account Settings. GET https://api.open-ocr.com/v1/health reports webhook_signature_version: 2, and callbacks carry X-OpenOCR-Signature-Version: 2. All API keys and signed-in sessions for that account use the same secret. The X-OpenOCR-Signature header is the lowercase hex HMAC-SHA256 of the exact HTTP body bytes, keyed by the entire whsec_... string. Never use an API key prefix or the word session as the signing key.
- Check the
X-OpenOCR-Request-Idheader matches a request you submitted - Always use HTTPS webhook URLs to prevent payload interception
- Validate the
request_idin the body against your records - Return a 2xx status within 10 seconds to prevent retries
- Process webhooks asynchronously — acknowledge first, process later
// Express.js webhook handler
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';
const secret = process.env.OPENOCR_WEBHOOK_SECRET;
if (!secret) throw new Error('Set your account webhook signing secret');
const app = express();
app.use(express.raw({ type: 'application/json' }));
// Replace with a lookup in your own database of the request_id values you saved when you submitted.
async function isMyRequest(requestId) { /* look up requestId in your DB */ return true; }
async function processOcrResult(payload) { /* store or forward the result */ }
app.post('/ocr-callback', async (req, res) => {
if (req.get('x-openocr-signature-version') !== '2') return res.sendStatus(401);
const signature = req.get('x-openocr-signature') || '';
if (!/^[0-9a-f]{64}$/.test(signature)) return res.sendStatus(401);
const expected = createHmac('sha256', secret).update(req.body).digest();
if (!timingSafeEqual(expected, Buffer.from(signature, 'hex'))) {
return res.sendStatus(401);
}
const payload = JSON.parse(req.body.toString('utf8'));
const requestId = req.headers['x-openocr-request-id'];
if (payload.request_id !== requestId) return res.sendStatus(400);
// Verify this is a request you actually made
if (!(await isMyRequest(requestId))) {
return res.status(404).send();
}
// Acknowledge immediately
res.status(200).send();
// Process asynchronously
processOcrResult(payload).catch(console.error);
});Signing secret rotation and migration
Existing OpenOCR Python and TypeScript SDK webhook helpers use a timestamp-v1 format and do not verify account-v2 callbacks. Use the standalone raw-body verifier above until those SDK helpers are updated and verified.
Rotating immediately replaces the signing secret. Queued jobs and each delivery retry read the current secret. Update every receiver before resuming callbacks. A delivery already in transit can use the previous secret for up to the 10-second delivery timeout; if needed, accept that previous random secret only for this bounded interval. Reject replays by recording request IDs and processing each completion once.
The former API-prefix/session signing scheme is insecure and has no compatibility grace period. If your receiver has not migrated, pause submissions with webhook_url, update its verifier to use your account secret, and poll GET /v1/ocr/{request_id} for requests already running. Resume callbacks after your receiver verifies the new secret. Never accept both the old predictable scheme and the new secret.
Dashboard endpoint test pings use the separate endpoint secret returned when that endpoint is created and a sha256= header prefix. Those test pings do not change the account secret used by OCR callbacks.
Full Text Retrieval
The webhook payload includes a preview of the extracted text, and the full text in extracted_text when the router has it (see History off and large PDFs). When extracted_text is null, poll the status endpoint for the full text, which works only while OCR history is on. A partial result's text is in the webhook when history is on, so there is nothing more to fetch for it:
curl https://api.open-ocr.com/v1/ocr/req_abc123 \
-H "Authorization: Bearer YOUR_API_KEY"Diagnostic endpoints (Dashboard API)
Registered endpoints receive only diagnostic test.ping requests; OCR callbacks use each OCR request’s webhook_url and the account secret from Settings. Endpoint URLs, labels, and stored event preferences can be managed through dashboard API routes. These endpoints live on open-ocr.com/api/webhooks (the webapp), not api.open-ocr.com/v1/webhooks (which 404s — that surface isn't routed by the OCR router).
Auth: these routes require a logged-in dashboard session cookie (Supabase auth), not an API key. They're intended to back the webhooks UI in the dashboard, not for headless CLI automation. If you need programmatic management, open an issue.
Endpoint Reference
| Method | Path | Purpose |
|---|---|---|
| GET | /api/webhooks | List your webhooks (all fields except secret). |
| POST | /api/webhooks | Create a webhook. Body: { url, label?, events? }. Returns secret exactly once. Max 10 per user. |
| PATCH | /api/webhooks/{id} | Update url, label, events, or is_active. All fields optional. |
| DELETE | /api/webhooks/{id} | Permanently remove a webhook. |
| POST | /api/webhooks/{id}/test | Send a synthetic test.ping ping; recorded in delivery log. |
| GET | /api/webhooks/{id}/deliveries | Recent delivery attempts (status, response code, latency, payload). |
Example: Create a diagnostic endpoint
# From a browser session (or with a Supabase access-token cookie set)
curl -X POST https://open-ocr.com/api/webhooks \
-H "Content-Type: application/json" \
-H "Cookie: $YOUR_SESSION_COOKIE" \
-d '{
"url": "https://yourapp.example.com/diagnostic-ping",
"label": "diagnostic"
}'
# Response includes the test-ping secret, NOT the OCR callback signing secret.
# Store it now; it is shown once. OCR callbacks use the account secret in Settings.
# {"id":"…","url":"…","label":"diagnostic","secret":"whsec_…","events":[…],"is_active":true,"created_at":"…"}