Implement a webhook receiver
This guide walks through building a webhook receiver that handles RCM events correctly under production conditions: signature verification, idempotency, fast acknowledgement, and async processing. The naive "verify and process inline" approach works in dev but breaks the moment something downstream is slow.
By the end, you'll have:
- A receiver endpoint that returns 2xx in under a second.
- Dedup guarantees against retried events.
- A clean separation between webhook ingestion and your business logic.
This guide covers the receiving side. To register the URL RCM should POST to — and to choose which event types it sends — see Managing subscriptions.
Recommended architecture
Two things matter:
- The HTTP handler is dumb on purpose. All it does is verify authentication, write the event to a durable queue (or a log table), and ack with 200. No business logic. This way you ack quickly regardless of how slow downstream is.
- The worker is idempotent. It reads events from the queue and applies them to your app store, keyed on
event_id.
If you only have one process today (no queue), the same shape applies: write to a webhook_events table with event_id as primary key, ack, and have a separate cron/poller process the unprocessed rows.
Register your endpoint with RCM
Before any of the code below runs, RCM needs to know where to POST. You do this yourself — it is a self-service endpoint, not a support request:
curl -X POST https://sandbox.osigu.com/rcm/v1/integration/webhooks \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"webhook_url": "https://your-host/webhooks/osigu-rcm",
"subscribed_event_types": ["DOCUMENT_VALIDATION_COMPLETED", "DOCUMENT_VALIDATION_REJECTED"]
}'
Returns 201 Created with the subscription id. Three things to know before you send it:
- Your OAuth2 client must be enabled to manage webhook subscriptions; if the call returns
403, ask Integraciones to enable it. - An empty or omitted
subscribed_event_typesmeans every event type, not none — including account, charge and invoice events. List the ones you want. auth_typedefaults toHMAC. The signing secret is generated server-side and never returned by the API; request it from Integraciones referencing the subscriptionid. ForBASIC, you supplybasic_auth_client_idandbasic_auth_client_secretin this same call.
Sandbox and production are independent subscriptions. See Managing subscriptions for the full contract, the retry and timeout policy, and how to list, update, pause or delete a subscription.
Step-by-step
1. Receive the request
Use the URL you registered above. Going to production means creating a second subscription against the production host — subscriptions do not carry across environments.
2. Read the raw body before parsing
This is the #1 thing developers get wrong. The HMAC is computed over the bytes of the body as received, not over a re-serialised JSON. Most frameworks aggressively auto-parse application/json, which destroys whitespace and changes the bytes.
Framework-specific notes:
| Framework | How to get raw bytes |
|---|---|
| Express (Node.js) | app.use('/webhooks/...', express.raw({type: 'application/json'})) before express.json() |
| FastAPI (Python) | await request.body() — returns bytes |
| Spring Boot (Java) | @RequestBody byte[] rawBody — declare the param as byte[], not as a DTO |
| Rails (Ruby) | request.raw_post |
| Go net/http | io.ReadAll(r.Body) |
| PHP | file_get_contents('php://input') |
3. Verify authentication
For HMAC subscriptions (default), reject with 401 if any of these is wrong:
X-RCM-Signatureis missing or doesn't match the Base64 HMAC-SHA256 oftimestamp + raw_body(concatenated directly, no separator) using your shared secret.X-RCM-Timestamp(ISO-8601) is more than 5 minutes off your server clock.- The comparison was done with
==instead of a constant-time function.
For Basic subscriptions, validate the Authorization: Basic header against the agreed credentials instead.
Full details in Authentication and Signature verification.
4. Persist the event, dedup on event_id
Before doing anything else, write the event to durable storage keyed on event_id:
CREATE TABLE webhook_events (
event_id VARCHAR(40) PRIMARY KEY,
event_type VARCHAR(80) NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
raw_body JSONB NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
processed_at TIMESTAMPTZ
);
The PRIMARY KEY on event_id is the dedup guarantee — if the same event arrives twice, the second INSERT fails on the unique constraint and you safely ack the duplicate without processing it again.
5. Acknowledge with 200 immediately
After the row is written, return 200 OK. No business logic in the handler. Downstream services can be slow, your message broker can be slow, your database can be slow — none of it should affect ack latency.
// Pseudocode
app.post('/webhooks/osigu-rcm', async (req, res) => {
if (!authIsValid(req)) return res.status(401).send('bad auth');
const event = JSON.parse(req.body.toString('utf8'));
try {
await db.query(
'INSERT INTO webhook_events (event_id, event_type, created_at, raw_body) ' +
'VALUES ($1, $2, $3, $4)',
[event.event_id, event.event_type, event.created_at, req.body.toString('utf8')]
);
} catch (err) {
if (err.code === '23505') {
// Unique violation — duplicate. Ack to stop RCM from retrying.
return res.status(200).send('duplicate, already processed');
}
// Real DB error — return 5xx so RCM retries.
return res.status(500).send('persist failed');
}
// Optionally enqueue to a worker queue here for faster pickup.
// await queue.publish('webhook-events', event.event_id);
res.status(200).send('ok');
});
6. Process events from the queue/table
A separate worker reads unprocessed rows and applies the business logic:
// Worker pseudocode — runs on a schedule or consumes from a queue
async function processEvent(eventId) {
const event = await db.query(
'SELECT * FROM webhook_events WHERE event_id = $1 AND processed_at IS NULL',
[eventId]
);
if (!event) return; // already processed by another worker
switch (event.event_type) {
case 'DOCUMENT_VALIDATION_COMPLETED':
await markSupportFileApproved(event.raw_body.payload);
break;
case 'DOCUMENT_VALIDATION_REJECTED':
await markSupportFileRejected(event.raw_body.payload);
await notifyUserOfRejection(event.raw_body.payload);
break;
case 'DOCUMENT_CLASSIFICATION_COMPLETED':
await setDetectedDocumentType(event.raw_body.payload);
break;
case 'DOCUMENT_CLASSIFICATION_FAILED':
await markSupportFileUnclassified(event.raw_body.payload);
break;
default:
// Unknown event type — log and move on. Don't 5xx; new event types
// may be added over time.
log.warn(`unknown event type ${event.event_type}`);
}
await db.query(
'UPDATE webhook_events SET processed_at = now() WHERE event_id = $1',
[eventId]
);
}