Webhooks
Register an endpoint, verify the HMAC signature, dedupe, and ack.
Instead of (or alongside) polling, register a webhook endpoint and Sello POSTs a
signed event when a document reaches a verdict (document.accepted,
document.rejected) or fails (document.failed), when an issued line's IVA rate
disagrees with the CABYS catalog, when a 90-day deferred-IVA sale lapses with a
balance outstanding (deferral.lapsed), and when your account crosses a usage
threshold. Deliveries ride the same at-least-once outbox as everything else.
Event types
Every event has the same envelope — id, type, createdAt, apiVersion,
data — and a data shape of its own. Switch on type.
apiVersion is the event schema version the body was created under (today
2026-06-15). It is fixed when the event is created, so a retry or a resend
carries the same value. Events created before it existed have no apiVersion;
treat it as optional.
type | When | data fields |
|---|---|---|
document.accepted | Hacienda accepted the document. | documentId, accountId, emisorId, clave, status: "accepted" |
document.rejected | Hacienda rejected the document. | documentId, accountId, emisorId, clave, status: "rejected" |
document.failed | The document was parked without a verdict (see below). | documentId, accountId, emisorId, clave, state, recoverable, reason |
document.iva_rate_divergence | The document issued, but a line's IVA rate disagrees with the CABYS catalog. | documentId, accountId, emisorId, clave, catalogVersion, divergences[] (line, cabys, appliedRate, catalogRate) |
deferral.lapsed | Day 90 of a condición-10 sale ended with a balance outstanding (see below). | documentId, accountId, emisorId, clave, outstanding |
usage.approaching_limit | Usage reached 80% of the plan's included allowance. | accountId, period, metric, count, limit, remaining, issuanceBlocked |
usage.limit_reached | Usage reached the included allowance. Issuance continues if the plan allows overage. | same as above |
usage.limit_exceeded | Usage reached the hard stop. Issuance is refused with a 402; issuanceBlocked is true. | same as above |
webhook.test | Someone pressed Send test event in the portal. Sent once, never retried. id starts with evt_test_. | test: true |
Each usage.* event fires at most once per calendar month and describes the
account, so it carries no documentId, emisorId or clave.
deferral.lapsed fires once per condición-10 sale (the 90-day deferred-IVA
régimen, LIVA art. 27) when day 90 ends with a balance outstanding. Day 1 is the
day after the sale's FechaEmision, counted in Costa Rica time. documentId and
clave name the sale, and outstanding is the balance left, a decimal string in
CRC. Sello issues no document and computes no IVA at the lapse, and a code-11 REP
against the sale is still accepted after it. A sale Hacienda accepts after its
day 90 lapses on the next pass. GET /v1/documents/{clave} on the sale returns
the same balance under deferral.
Sello may add event types and fields. Answer 2xx to a type you do not
handle, and ignore fields you do not recognise. Any other status counts as a
failed delivery: it is retried on the schedule below and, after twelve
attempts, dead-lettered.
When a document fails
document.failed tells you a document will not reach a verdict through the
normal path. data.state says where Sello parked it and data.reason says why:
reason: "submission_failed",state: "error"— the submission spent its retries or Hacienda refused it outright. This does not prove Hacienda lacks the comprobante: a slow submission can still land, and Sello then corrects the document on its own.reason: "verdict_timeout",state: "dead_letter"— Sello stopped waiting for Hacienda's verdict. Its fate at Hacienda is unknown, so contact support before you reissue it.
data.recoverable is true exactly when state is error. It means Sello can
still move the document out of that state — after an operator redrive, or with no
human involved when Hacienda turns out to hold it — not that a retry will
work. So a document.failed with state: "error" may later be followed by
document.accepted or document.rejected for the same documentId, and a
second failure after a redrive sends a second document.failed with a new id.
dead_letter is final.
A document Sello cannot place in a single account (its emisor belongs to another account) sends no event; Sello's operators handle it.
Register an endpoint
PUT /v1/webhooks/endpoint with your HTTPS url and an HMAC signing secret.
There is one endpoint per account, and a PUT registers it or replaces it. It
is scoped to your API key's account (the account is never taken from the body).
The endpoint receives every emisor's events, so it takes an account-wide key: a
key pinned to one emisor gets a 403 and nothing is written.
curl -X PUT https://api.sello.cr/v1/webhooks/endpoint \
-H "Authorization: Bearer $SELLO_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "url": "https://example.com/webhooks/sello", "secret": "whsec_…" }'The response returns the registered url and enabled flag and never echoes
the secret. POST to the same path still works and does the same thing; it is
deprecated in favour of PUT.
Read what is registered with GET /v1/webhooks/endpoint: url, enabled,
createdAt, updatedAt and managedBy, never the secret, or a 404 when
nothing is registered. Remove it with DELETE /v1/webhooks/endpoint, which
answers 204 and stops every delivery.
Sello server-fetches your url with your secret attached, so it is validated
against an SSRF blocklist at registration: a non-https scheme or a
private / loopback / link-local / metadata host is a 422 and is never stored.
Webhooks and Odoo
An Odoo connection receives its verdicts on its own channel: its own callback destination and its own signing secret, separate from your endpoint. Creating, editing, disabling or deleting your endpoint, rotating its secret and expiring the previous secret early never change where Odoo is called back or the secret it verifies with. You can connect Odoo while you have an endpoint, and keep your endpoint while Odoo is connected.
This channel is being rolled out. An account connected before the rollout
still has the Odoo callback registered as its endpoint until Sello moves it to
the connection's own channel. Until then, GET answers
managedBy: "odoo-connection", and PUT, POST, DELETE, the previous-secret
expiry and the portal's Save and Rotate answer 409 with type
https://sello.cr/problems/webhook-slot-owned-by-odoo-connection and change
nothing. Writing over that callback would stop Odoo write-back with no error
anywhere, so Sello refuses it. Once the rollout reaches your account, the
next endpoint change you make first moves the Odoo callback to its own channel.
After that the endpoint is yours: PUT or POST registers it, and a rotation,
an expiry or a DELETE answers 404 until you have registered one.
Rotate your secret
A real secret change at an unchanged URL starts a 24-hour overlap: for 24 hours after the change commits, every delivery attempt is signed with BOTH the current secret and the immediately previous one, and the header carries the current signature first and the previous one last:
Sello-Signature: t=1234567890,v1=<current-hmac>,v1=<previous-hmac>- A receiver holding either secret verifies during the window. Verify with
a helper that accepts a matching
v1in ANY position —verifyWebhookin the TypeScript SDK (thewebhooksmodule) and the engine'sverifySignaturedo. If you verify by hand, compare your expected HMAC against everyv1value, not just the last one: during the window the last value is the PREVIOUS secret's signature. - Last-signature-only receivers must upgrade before switching to the new
secret during the window. An unupgraded hand-rolled verifier keeps working
as long as it still holds the OLD secret (the last
v1is that secret's signature); it rejects deliveries the moment it adopts the new one. Upgrade first, then swap. - Rotating again retires the oldest secret immediately. Rotating A to B
keeps B as the previous secret and drops A outright, so a second rotation can
end the first window early — the response's
previousSecretExpiresAtis what stands. - Re-saving the same secret changes nothing, and saving a new URL clears the window: a different destination owes the old receiver's secret nothing.
GET, PUT and POST /v1/webhooks/endpoint return previousSecretExpiresAt:
when the previous secret stops signing, or null when no window is open. The
portal shows the same time in your local time zone. Neither secret is ever
returned.
Retire the previous secret immediately when you should not wait — you suspect a
leak, or you have already upgraded every receiver — with
POST /v1/webhooks/endpoint/expire-previous-secret (API key with
webhooks:write) or the portal's Expire previous secret now action. It is
idempotent, changes neither the current secret nor the URL nor enabled, and
404s when no endpoint is registered. The portal's Rotate also offers
Expire previous secret now so a rotation can skip the window entirely, and a
PUT takes "expirePreviousSecret": true for the same effect. In the
TypeScript SDK these are webhooks.expirePreviousSecret() and
webhooks.register({ url, secret, expirePreviousSecret: true }).
Early expiry stops NEW signing only. It does not revoke a request that was
already signed and sent: a receiver that still trusts the retired secret keeps
accepting it until its own replay tolerance (the t check) runs out. Treat
expiry as a deadline for your own cut-over, not as a kill switch.
Two timing rules to plan around:
- Queued jobs follow the endpoint. A delivery already waiting in the queue keeps its body and event id, and each attempt POSTs to the endpoint's CURRENT URL, signed with its CURRENT secret. After you move the endpoint, the next retry of every queued event goes to the new URL, and its failures count toward the new endpoint's pause. Nothing more goes to the old URL.
- Each attempt reads the secret when it is sent. A new secret applies from the next attempt on, with a fresh signature timestamp, so a retry after your receiver is updated verifies without redelivery.
Verify the signature
Every delivery carries a signature header:
Sello-Signature: t=<unixSeconds>,v1=<hexHmacSha256>v1 is the hex HMAC-SHA256 of the string "{t}.{rawBody}" keyed by your
endpoint secret. Verify over the RAW request body before parsing —
re-serializing the JSON first would break the signature (key order and whitespace
can differ from the wire). Use a constant-time compare and reject deliveries
whose t is outside your tolerance window (replay defense). This is the same
scheme as Stripe/Svix.
The body's createdAt is Unix epoch seconds when the event was created. It is
NOT the signature timestamp: verify against the t in the Sello-Signature
header, which is stamped fresh on each delivery attempt.
The SDK's verifyWebhook does all of that for you:
import { verifyWebhook, parseWebhookEvent, WEBHOOK_SIGNATURE_HEADER } from '@magiios/sdk';
// Express — note express.raw so you get the unparsed bytes.
app.post('/webhooks/sello', express.raw({ type: 'application/json' }), (req, res) => {
const raw = req.body.toString('utf8');
const sig = req.header(WEBHOOK_SIGNATURE_HEADER) ?? '';
if (!verifyWebhook(raw, sig, process.env.SELLO_WEBHOOK_SECRET!)) {
return res.sendStatus(400); // unauthenticated — drop it
}
const event = parseWebhookEvent(raw);
// dedupe on event.id, then branch on event.type — each type has its own data:
switch (event.type) {
case 'document.accepted':
case 'document.rejected':
// event.data: { documentId, clave, status, mensajeHacienda?, … }
break;
case 'document.failed':
// event.data: { documentId, clave, state, recoverable, reason, … }
break;
default:
// a type this handler does not use — still ack it below
break;
}
res.sendStatus(200); // ack, including types you ignore
});verifyWebhook(rawBody, signatureHeader, secret, opts?) returns a boolean (never
throws) and accepts { toleranceSeconds = 300, now }.
On document.rejected, event.data gains an optional mensajeHacienda —
{ mensaje, detalleMensaje }, Hacienda's own verdict code and reason read from
its response. It is absent when the response is missing or Sello cannot read it,
and document.accepted never carries it.
Dedupe on the event id
Delivery is at-least-once, so the same event can arrive more than once
(retries, redeliveries). The event id is also sent in the Sello-Webhook-Id
header. Dedupe on it — record processed ids and ignore repeats.
Ack, retries, and dead-letter
Respond 2xx to acknowledge — including to an event type you do not handle.
Any other status, or no answer within 10 seconds, is a failed attempt.
Keep your handler fast and idempotent: verify, dedupe, enqueue your own work,
ack.
A failed delivery is retried on this schedule. Each wait starts from the failed attempt, and is at least the step shown and at most 20% longer, so retries from many events do not arrive at once:
| After attempt | Wait |
|---|---|
| 1 | 1 minute |
| 2 | 5 minutes |
| 3 | 30 minutes |
| 4 | 2 hours |
| 5 | 5 hours |
| 6 | 8 hours |
| 7 | 8 hours |
| 8 | 12 hours |
| 9 | 12 hours |
| 10 | 12 hours |
| 11 | 12 hours |
After the twelfth failed attempt the delivery is dead-lettered. The twelve attempts span about 72 to 86 hours, so a receiver that is down over a weekend still gets its events.
That is the normal schedule, not a promise. A delivery whose URL fails the SSRF check is dead-lettered at once, and a delivery a worker was sending when it stopped can use up an attempt without a wait.
Redeliver from the portal
Webhooks → Deliveries lists each delivery and its attempts. Show dead letters
only, fix your receiver, and press Redeliver on a dead-lettered row. Sello
queues it again with a fresh set of twelve attempts, sends it to your current
URL, signs it with your current secret and a fresh t, and keeps the same body
and event id, so your dedupe still works. The list shows the newest deliveries
first; Older deliveries pages back through the rest, dead letters included.
List and resend stored events
Sello stores every event it raises, whether or not it was delivered: one raised
while you had no endpoint, a disabled one or a selection that left it out is
stored too. GET /v1/events lists them newest first (createdAt, then id),
50 per page by default (limit 1 to 100). Pass nextCursor back as cursor
until it is null. Filter with type, documentId and emisorId; a document or
emisor filter leaves out the account-level events (usage.*, webhook.test).
A cursor works only with the same key scope and filters it was issued for. A
query parameter the route does not accept is a 400 of type
urn:sello:problem:unknown-query-parameter; a bad value, a repeated parameter or
a foreign cursor is a 422 of type https://sello.cr/problems/invalid-list-query.
POST /v1/events/{id}/resend with an Idempotency-Key queues a new delivery of
one stored event to your current enabled endpoint, with the same body bytes
(same id, createdAt and apiVersion), a fresh t and a fresh set of twelve
attempts. It answers 202 with eventId and deliveryId. It answers 409
while a delivery of the event is still pending or in flight
(.../webhook-delivery-in-progress), when you have no enabled endpoint
(.../no-webhook-endpoint), or while an Odoo connection holds the endpoint
(.../webhook-endpoint-managed-by-odoo). Within 24 hours the same key returns
the same 202; the same key for another event is a 409
(.../idempotency-key-conflict). An event the key may not see is a 404
(.../webhook-event-not-found).
Both routes take an account-wide key with webhooks:write. A live key sees
every stored event of the account. A test key sees webhook.test and the
events of documents whose emisor is in sandbox, never usage events.
Storage started with this feature: events raised before it cannot be listed. An account's erasure deletes its stored events, except copies of document events a legal hold covers; those go when their document is disposed of at the end of its retention window.
Catch up on a document
If you lost an event for good, read the document itself:
GET /v1/documents/{clave} answers with its current state whatever happened to
the webhook.
Catch up on everything that changed
To find every document whose state changed while your receiver was down, list
them with updatedSince:
GET /v1/documents?updatedSince=2026-09-01T12:00:00Z&state=accepted&limit=200updatedSinceis an RFC 3339 date-time with an offset (Zor-06:00). A date-only or zone-less value is a422.- The boundary is inclusive: a document whose
updatedAtequals it is listed. It is compared at microsecond precision, the resolutionupdatedAtis stored at —12:00:00.123456Zexcludes a document updated at.123000Zand includes one updated at.123456Z. More than six fractional digits is a422: the boundary cannot be finer than what is stored. - It filters on the last state change, not on creation, so an invoice created
last month and accepted after the boundary is listed. Each item carries its
updatedAt. - The list is still ordered by creation and paged by cursor. Pass each page's
nextCursorback ascursor, with the sameupdatedSinceand filters, untilnextCursorisnull. - It composes with
tipo,stateandlimit, and an emisor-pinned key still sees only its own emisor.
To run it on a schedule, note the time before the first page; the first
response's Date header is Sello's clock. Start the next run from that time
minus a few minutes. A document that changed while you were paging, or whose
change was committed just after a later one, falls inside the overlap. The
overlap returns some documents twice, so act on each (clave, state) once, as
you already do for webhook events.
When your endpoint is down
If five deliveries in a row to your endpoint fail — a non-2xx answer, a
timeout, or a connection, DNS or TLS error — Sello pauses delivery to your
account for five minutes. Events are not lost and no retry is spent while
the pause lasts: they wait, and go out once it ends. The first delivery after
the pause is a test of your endpoint. If it succeeds, delivery carries on as
normal; if it fails, the pause starts again.
The dashboard's Webhooks page shows the pause and when it ends. Saving the endpoint — a new URL, the same one, or a rotated secret — ends the pause at once, so fix your endpoint, then save it. The pause covers your webhooks only; your invoices keep being filed with Hacienda.