Skip to content

Webhooks

Instead of polling, register an HTTPS endpoint and EmiteCR pushes invoice lifecycle events — and the state of the tenant’s Hacienda credentials — to you.

Event Fires when
invoice.submitted The document was accepted by ATV for processing (recibido)
invoice.accepted Hacienda accepted it (aceptado)
invoice.rejected Hacienda rejected it (rechazado)
invoice.error The pipeline errored (poll timeout, submit timeout, cert, XML)
credentials.rejected Hacienda refuses the tenant’s stored ATV username and password for environment
credentials.restored Those credentials work again; the documents that waited are on their way

An endpoint receives only the types it subscribed to — a type added later never reaches an endpoint registered before it existed. There is also one event nobody subscribes to, webhook.test, which arrives only when someone asks to test the endpoint (see Test an endpoint).

For async emissions this stream is the ONLY verdict channel — invoice.error includes the case where a signed document could not be submitted to ATV within 24h (SUBMIT_TIMEOUT_24H) or hit a permanent error (e.g. expired certificate).

Payloads are thin — ids and status only, never the document body:

{
"id": "019a0c91-6f3e-7a2b-9c41-5d8e2f0a7b13",
"type": "invoice.accepted",
"occurredAt": "2026-05-13T12:00:03Z",
"tenantId": "…",
"environment": "production",
"data": {
"invoiceId": "…",
"clave": "506…",
"docType": "01",
"status": "accepted",
"haciendaStatus": "aceptado",
"detail": "Comprobante recibido satisfactoriamente",
"externalReference": "ticket-9f3b8c1d"
}
}

data depends on type — branch on it before reading fields.

While Hacienda refuses the stored ATV credentials, the tenant’s documents keep their number and wait signed — none is marked error — and EmiteCR makes no further login attempts with them (each refused one counts toward the account’s lockout at Hacienda). credentials.rejected is how an integration learns that someone has to update them; for a partner-managed tenant, that someone is the partner’s customer, and this event is the only notice (such a tenant has no members to email).

{
"id": "019a0c92-0b7d-7e11-8a52-1c9f3d6e4a20",
"type": "credentials.rejected",
"occurredAt": "2026-10-05T16:00:00Z",
"tenantId": "…",
"environment": "production",
"data": {
"rejectedAt": "2026-10-05T16:00:00.000Z",
"detail": "invalid_grant: Invalid user credentials"
}
}

credentials.restored carries the same rejectedAt (so the pair matches up in any arrival order) and detail: null. By the time it arrives, the documents that waited have been handed back to the pipeline; their verdicts follow as the usual invoice.* events.

Register the endpoint in Developers → Webhooks, in the app, or over the API with a key that has the webhooks:manage scope; in the app the owner and the administrators hold it. Every plan includes webhooks.

Ventana de terminal
curl -X POST https://api.emite.cr/v1/webhooks \
-H "x-api-key: $EMITECR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"environment": "production",
"url": "https://your-system.example.com/webhooks/emitecr",
"events": ["invoice.accepted", "invoice.rejected", "invoice.error"],
"description": "Point of sale"
}'

201 returns the endpoint and its signing secret — shown once; keep it like the API key:

{
"id": "019a0c95-…",
"environment": "production",
"url": "https://your-system.example.com/webhooks/emitecr",
"events": ["invoice.accepted", "invoice.rejected", "invoice.error"],
"description": "Point of sale",
"status": "active",
"consecutiveFailures": 0,
"failingSince": null,
"lastSuccessAt": null,
"lastFailureAt": null,
"pausedAt": null,
"nextProbeAt": null,
"heldDeliveries": 0,
"disabledAt": null,
"disabledReason": null,
"previousSecretExpiresAt": null,
"createdAt": "2026-10-21T15:20:00.000Z",
"secret": "whsec_…"
}
  • GET /v1/webhooks lists the endpoints with their delivery health (never the secret), and failingSince says since when one has been failing; DELETE /v1/webhooks/:id removes one, and GET /v1/webhooks/catalog returns the event types an endpoint may subscribe to and the delivery rules: the retry window, the pause and the disable.
  • An endpoint receives the events of one environment, sandbox or production: the one environment says when it is registered, which cannot be changed later. Without it, it is the environment of the key that registers it; in the app, you choose it. To receive both environments, register one endpoint in each: each has its own secret, and every event it receives carries that same environment.
  • An API key reaches only the endpoints of its environment: it registers them, lists them, tests them, reads their deliveries, rotates their secret and deletes them. A sandbox key cannot register a production one (403 WEBHOOK_ENVIRONMENT_NOT_ALLOWED), and to it the other environment’s endpoints do not exist (404 WEBHOOK_ENDPOINT_NOT_FOUND). The app shows those of both environments.
  • There is no “edit”: to change the URL or the events, register a new endpoint in the same environment, switch your receiver to its secret, then delete the old one. A URL registered twice in one environment receives every event twice. The secret, on the other hand, is rotated without changing endpoints (see Rotate the secret).

Registration and every delivery are SSRF-guarded: HTTPS only, DNS is resolved and private / loopback / metadata ranges are rejected, and redirects are not followed. For local development use a tunnel (ngrok, webhook.site) or fall back to polling.

To confirm your receiver gets and verifies the deliveries, send it a test event: with Send test, in Developers → Webhooks, or over the API.

Ventana de terminal
curl -X POST https://api.emite.cr/v1/webhooks/019a0c95-…/test \
-H "x-api-key: $EMITECR_API_KEY"

EmiteCR sends it a webhook.test event right then, signed with the endpoint’s secret like any delivery, and answers what happened:

{
"delivered": false,
"resumed": false,
"eventId": "019a0c97-…",
"eventType": "webhook.test",
"statusCode": 401,
"durationMs": 184,
"failure": "http_status",
"failureDetail": null,
"responseExcerpt": "invalid signature",
"sentAt": "2026-10-22T18:00:00.000Z"
}
  • A failed delivery is an answer (200 with delivered: false), not an error. failure says why: url_invalid (the URL no longer passes the safety check and nothing was sent), timeout, tls, connection or http_status. failureDetail carries the reason or the system code (ECONNREFUSED, CERT_HAS_EXPIRED), and responseExcerpt, the beginning of what your server answered.
  • The test is not retried, and on an active endpoint it does not count towards the pause: it leaves consecutiveFailures, lastSuccessAt and lastFailureAt as they were.
  • On a paused or disabled endpoint, a test that gets through brings it back (resumed: true): a paused one resumes and the events that waited go out, and a disabled one is reactivated. It is how you say your server responds again.
  • Each company has 10 tests every 10 minutes (429 WEBHOOK_TEST_RATE_LIMITED, with Retry-After).

The event carries the endpointId and a fixed message in data, and in environment, the endpoint’s environment, like every event it receives. It describes no document: verify its signature, answer 2xx and do nothing else with it.

{
"id": "019a0c97-…",
"type": "webhook.test",
"occurredAt": "2026-10-22T18:00:00.000Z",
"tenantId": "…",
"environment": "sandbox",
"data": {
"endpointId": "019a0c95-…",
"message": "This is a test event sent from EmiteCR on request. It describes no document: answer 2xx and do nothing else with it."
}
}

Each delivery carries two headers:

  • X-Emitecr-Signature: t=<unix-seconds>,v1=<hex> — v1 is HMAC-SHA256(secret, "<t>.<rawBody>") in hex
  • X-Emitecr-Event-Id: <id> — the event’s id, the same on every retry and redelivery

The HMAC key is the whole secret, whsec_ included. Verify against the raw body — the exact bytes received, before any JSON parsing: re-serialized JSON does not match byte for byte. In Node.js with Express:

import crypto from 'node:crypto';
import express from 'express';
const SECRET = process.env.EMITECR_WEBHOOK_SECRET; // whsec_…
const TOLERANCE_SECONDS = 300;
function verify(rawBody, header) {
if (!header) return false;
// t=<seconds>,v1=<signature>[,v1=<signature>]
let t = null;
const signatures = [];
for (const part of header.split(',')) {
const [key, value] = part.trim().split('=');
if (key === 't') t = value;
else if (key === 'v1') signatures.push(value);
}
if (!t || !/^\d+$/.test(t) || signatures.length === 0) return false;
// Reject old deliveries: a captured request can't be replayed later.
if (Math.abs(Date.now() / 1000 - Number(t)) > TOLERANCE_SECONDS) return false;
const expected = crypto.createHmac('sha256', SECRET).update(`${t}.`).update(rawBody).digest('hex');
return signatures.some(
(signature) =>
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)),
);
}
const app = express();
app.post('/webhooks/emitecr', express.raw({ type: 'application/json' }), (req, res) => {
if (!verify(req.body, req.get('x-emitecr-signature'))) return res.status(400).end(); // bad signature or stale timestamp — do NOT process
const event = JSON.parse(req.body.toString('utf8'));
enqueue(event); // ack fast, process async
res.status(200).end();
});

The same recipe in any language: split t and the v1 values out of the header, compute HMAC-SHA256(secret, "<t>.<raw body>") as lowercase hex and compare it in constant time against each v1; the delivery is valid if any matches. The header may carry more than one v1, and ignore the keys you do not know: that way a new version of the signature does not break your receiver.

If someone may have seen the secret, or you change it as a routine, rotate it: with Rotate secret, in the endpoint’s detail, or over the API.

Ventana de terminal
curl -X POST https://api.emite.cr/v1/webhooks/019a0c95-…/rotate-secret \
-H "x-api-key: $EMITECR_API_KEY"

201 returns the endpoint with its new secret, shown only once, and previousSecretExpiresAt. Until then (24 hours), every delivery carries two v1 in X-Emitecr-Signature, one per secret, the new one first: your receiver keeps verifying with the previous one while you swap in the new one, without missing a delivery. Until those 24 hours are over it cannot be rotated again (409 WEBHOOK_SECRET_ROTATION_IN_PROGRESS). The deprecated X-Futura-Signature header carries only the new secret’s signature: a receiver that still verifies it has to change the secret right after rotating.

Deliveries also carry X-Futura-Signature: sha256=<hex> (the same signature, prefixed with sha256=) and X-Futura-Timestamp: <unix-seconds> (the same t): the format webhooks were first published with. They are still sent for the receivers that already verify them, but they are deprecated. A new receiver verifies X-Emitecr-Signature, and one that reads X-Futura-Signature today should move to it: we will let you know before we stop sending them.

Consume idempotently — order is not guaranteed

Section titled “Consume idempotently — order is not guaranteed”

Retries reorder deliveries. Treat each event as a state upsert, not a sequence:

  • Dedup by event.id (the same value X-Emitecr-Event-Id carries).
  • Key state by data.invoiceId (or data.externalReference) and keep the row with the newest occurredAt — ignore an older event that arrives late.
function onEvent(event) {
if (seenEventIds.has(event.id)) return; // dedup
seenEventIds.add(event.id);
const row = getByInvoice(event.data.invoiceId);
if (row && row.occurredAt >= event.occurredAt) return; // stale — drop
upsertStatus(event.data.invoiceId, event.data.status, event.occurredAt);
}

Every delivery attempt is recorded for 30 days —the retries, the tests and the redeliveries—, with what was sent and what your server answered. In the app it shows when you open an endpoint in Developers → Webhooks; over the API:

Ventana de terminal
curl "https://api.emite.cr/v1/webhooks/019a0c95-…/deliveries?outcome=failed&limit=25" \
-H "x-api-key: $EMITECR_API_KEY"
{
"items": [
{
"id": "019a0c99-…",
"eventId": "019a0c91-6f3e-7a2b-9c41-5d8e2f0a7b13",
"eventType": "invoice.accepted",
"environment": "production",
"attempt": 6,
"isTest": false,
"redeliveryOf": null,
"outcome": "failed",
"statusCode": 503,
"failure": "http_status",
"failureDetail": null,
"responseExcerpt": "Service Unavailable",
"durationMs": 212,
"nextAttemptAt": "2026-10-22T20:20:00.000Z",
"event": { "id": "019a0c91-6f3e-7a2b-9c41-5d8e2f0a7b13", "type": "invoice.accepted" },
"attemptedAt": "2026-10-22T18:20:00.000Z"
}
],
"nextCursor": "019a0c99-…"
}
  • They go newest first. outcome filters (succeeded or failed), limit goes from 1 to 100, and nextCursor is passed as cursor to ask for the next page.
  • attempt says which attempt each one was, and nextAttemptAt, when the delivery is tried again (null when it is not retried on its own). When a delivery reaches the end of its window without getting through, a record with failure: "expired" is left: nothing was sent at that moment, and it can be resent from there. event is the event exactly as it was sent.

Once your server responds again, send again what did not reach it: with Resend, in the endpoint’s detail, or over the API.

Ventana de terminal
curl -X POST https://api.emite.cr/v1/webhooks/019a0c95-…/deliveries/019a0c99-…/redeliver \
-H "x-api-key: $EMITECR_API_KEY"

It answers 202 with the eventId and queued. The event goes out again with the same id, so your receiver does not process it twice if it drops the repeats by it, and the new attempts show up in the history with redeliveryOf. A resend is a new delivery, with its own window and retries, and its first attempt goes out even while the endpoint is paused: if it gets through, the endpoint resumes. It is not resent to a disabled endpoint (409 WEBHOOK_ENDPOINT_DISABLED: a test that gets through reactivates it first) nor is a test (409 WEBHOOK_TEST_NOT_REDELIVERABLE), and each company has 60 resends every 10 minutes (429 WEBHOOK_REDELIVERY_RATE_LIMITED).

  • Respond 2xx quickly (within 10 seconds); do the work asynchronously. A non-2xx or a timeout triggers a retry.
  • Each delivery is retried with growing waits (1 minute, 5, 30, 2 hours, 6, then every 12) for 72 hours from its first attempt (24 when the endpoint is a sandbox one). If you answer 429 or 503 with Retry-After, the next attempt waits as long as it asks, up to 12 hours (6 in sandbox). One that does not get through within that window stays as expired in the delivery history, from where it can be sent again.
  • After 10 failed attempts in a row, the endpoint is paused: new events and retries wait instead of going out (heldDeliveries), and we try it with the one that has waited longest, after 5 minutes and then further and further apart, at most every hour (nextProbeAt). The first success resumes it and what waited goes out. To resume it right away, use Send test.
  • If the pause lasts more than 30 minutes, we email the company’s owner and administrators, and again when it responds.
  • If it stays paused for 7 days without a single success, it is disabled (disabledReason: "auto_failures") and stops receiving events; we email about that too. Once your server responds, a test that gets through reactivates it.
  • While it fails, GET /v1/webhooks says so with consecutiveFailures and failingSince, and the app shows it as «Failing» and then «Paused».
  • Webhooks complement polling, they don’t replace the record: if your endpoint was down, GET /v1/invoices/:id still has every document’s current state.