Skip to content

Webhooks ​

Recibe, verifica y rutea los webhooks de SmartDoc.

Constructors ​

Constructor ​

ts
new Webhooks(options): Webhooks;

Parameters ​

ParameterType
optionsstring | WebhooksOptions

Returns ​

Webhooks

Methods ​

on() ​

ts
on(eventTypes, handler): this;

Registra un handler para uno o varios tipos de evento.

ts
webhooks.on('invoice.approved', (evento) => {
  console.log(evento.entityId, evento.cdc);
});

webhooks.on([Event.INVOICE_ERROR, Event.CREDIT_NOTE_ERROR], (evento) => {
  avisar(evento.errorMessage);
});

Parameters ​

ParameterType
eventTypesstring | readonly string[]
handlerHandler

Returns ​

this


onAny() ​

ts
onAny(handler): this;

Registra un handler que recibe todos los eventos.

Parameters ​

ParameterType
handlerHandler

Returns ​

this


onAnyError() ​

ts
onAnyError(handler): this;

Registra un handler para los cinco eventos *.error.

Son cinco y no seis: receipt.error no existe, porque un recibo que falla queda en pending y se reintenta.

Parameters ​

ParameterType
handlerHandler

Returns ​

this


handlersFor() ​

ts
handlersFor(eventType): Handler[];

Los handlers que aplican a un tipo de evento.

Parameters ​

ParameterType
eventTypestring

Returns ​

Handler[]


signatureFor() ​

ts
signatureFor(body): string;

La firma esperada para un cuerpo, con el formato del encabezado.

Parameters ​

ParameterType
bodystring | Buffer<ArrayBufferLike>

Returns ​

string


verify() ​

ts
verify(body, headers): WebhookEvent;

Verifica la firma y devuelve el evento.

Parameters ​

ParameterTypeDescription
bodystring | Buffer<ArrayBufferLike>El cuerpo crudo de la solicitud. Si se pasa el JSON reserializado, la firma no va a validar.
headersHeadersLos encabezados. La búsqueda no distingue mayúsculas.

Returns ​

WebhookEvent

Throws ​

si falta la firma, no coincide, o el evento es demasiado viejo.


isDuplicate() ​

ts
isDuplicate(event): boolean;

Si esta entrega ya se procesó, y la marca como vista.

SmartDoc reintenta hasta 5 veces, y una entrega que el servidor procesó pero respondió tarde se vuelve a mandar. Sin esto, un webhook lento genera trabajo duplicado.

Parameters ​

ParameterType
eventWebhookEvent

Returns ​

boolean


dispatch() ​

ts
dispatch(body, headers): Promise<WebhookEvent>;

Verifica, deduplica y corre los handlers.

Si un handler lanza, el error se reporta y no se propaga: reintentar no arregla un bug de código, y SmartDoc solo hace 5 intentos en algo más de un minuto. Lo que corresponde ahí es responder 200 y arreglar el handler.

Parameters ​

ParameterType
bodystring | Buffer<ArrayBufferLike>
headersHeaders

Returns ​

Promise<WebhookEvent>


expressHandler() ​

ts
expressHandler(): (request, response) => Promise<void>;

Un middleware de Express.

Hay que montarlo con el parser de cuerpo crudo, porque la firma se calcula sobre los bytes tal como llegaron:

ts
app.post('/webhooks', express.raw({ type: 'application/json' }), webhooks.expressHandler());

Returns ​

(request, response) => Promise<void>


fastifyHandler() ​

ts
fastifyHandler(): (request, reply) => Promise<void>;

Un handler de Fastify.

Necesita que la ruta reciba el cuerpo sin parsear; ver fastify.addContentTypeParser.

Returns ​

(request, reply) => Promise<void>


fetchHandler() ​

ts
fetchHandler(): (request) => Promise<Response>;

Un handler con la interfaz web estándar: recibe un Request y devuelve un Response. Sirve para Hono, Next.js, Deno y Bun.

ts
export const POST = webhooks.fetchHandler();

Returns ​

(request) => Promise<Response>


serve() ​

ts
serve(options?): Promise<WebhookServer>;

Levanta un servidor mínimo, para desarrollo.

SmartDoc exige que la URL del endpoint sea https:// y alcanzable desde internet, así que localhost no sirve como endpoint: hay que exponer el puerto con un túnel (ngrok, cloudflared, smee.io) y registrar la URL pública que devuelva.

Parameters ​

ParameterType
options{ port?: number; host?: string; path?: string; }
options.port?number
options.host?string
options.path?string

Returns ​

Promise<WebhookServer>