NF-e webhooks: authorization, rejection and cancellation without polling
Register an HTTPS endpoint and receive invoice.authorized, rejected, cancelled and corrected: the payload, HMAC signature in Python and Node, retries and idempotency.

An NF-e webhook is a URL in your application that Stackin calls when something happens to a fiscal document, instead of you polling the API until the outcome shows up. You register an HTTPS endpoint and receive four events: invoice.authorized, invoice.rejected, invoice.cancelled and invoice.corrected. Each notice is a JSON POST, signed with HMAC-SHA256, and resent with growing waits until your server answers 2xx.
It is not instant, which is worth knowing before you design the flow. The event is written in the same request that changed the document, and a job that runs every minute sends whatever is queued: the notice arrives in about a minute, not in milliseconds. In exchange, a webhook problem never fails an issuance. The document type, nfe or nfse, is in the payload itself, in document_type.
Which events exist and when each one fires
invoice.authorized: the authority authorized the document. It goes out on issuing and on reissuing, and also when a consult finds that a document recorded as rejected was in fact authorized.invoice.rejected: the authority refused the document. The reason is not in the notice; read it atGET /invoices/{invoice_id}/rejection. A local configuration error, such as the certificate, raises no event.invoice.cancelled: the cancellation was accepted, whether it came from your API, from another system of the company or from an assistant connected through MCP.invoice.corrected: a correction letter was registered. It exists for NF-e only, because an NFS-e has no correction letter.
An endpoint registered with events empty or omitted receives all of them. An unknown event name is refused at registration with 422, rather than leaving you to wait forever for an event that never fires.
How to register the webhook endpoint
Use an API key (see environments). The URL must be https and point at the public internet: private addresses and localhost are refused, so use a tunnel during local development. The secret is 16 to 255 characters, signs every delivery and is never returned again by any route, so keep it in your secrets store.
curl -X POST https://api.stackin.io/api/v1/webhooks \
-H "Authorization: Bearer $STACKIN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://erp.example.com.br/stackin",
"secret": "um-segredo-longo-e-aleatorio",
"events": ["invoice.authorized", "invoice.rejected", "invoice.cancelled"]
}'{
"id": "3b0e5f64-8a1c-4d7e-9c52-6f1a2b3c4d5e",
"url": "https://erp.example.com.br/stackin",
"events": ["invoice.authorized", "invoice.rejected", "invoice.cancelled"],
"environment": "homologation",
"is_active": true,
"created_at": "2026-11-22T14:03:11"
}The Python and Node SDKs do the same, checking the URL, the secret length and the event names before calling the API. delete only deactivates the endpoint and keeps the history of what was already sent.
import os
from stackin import Webhooks
hooks = Webhooks(api_key=os.environ["STACKIN_API_KEY"])
endpoint = hooks.create(
url="https://erp.example.com.br/stackin",
secret=os.environ["STACKIN_WEBHOOK_SECRET"],
events=["invoice.authorized", "invoice.rejected", "invoice.cancelled"],
)
hooks.list()
hooks.deliveries(limit=20)
hooks.delete(endpoint["id"])import { Webhooks } from "@stackin-io/stackin-node-sdk";
const hooks = new Webhooks({ apiKey: process.env.STACKIN_API_KEY });
const endpoint = await hooks.create({
url: "https://erp.example.com.br/stackin",
secret: process.env.STACKIN_WEBHOOK_SECRET,
events: ["invoice.authorized", "invoice.rejected", "invoice.cancelled"],
});
await hooks.list();
await hooks.deliveries({ limit: 20 });
await hooks.delete(String(endpoint.id));What reaches your server
Each delivery is a POST with the body below and three headers that matter: Stackin-Signature, Stackin-Delivery-Id and the JSON Content-Type. The envelope carries company_id, tax_id and environment beside event, so one receiver can serve several companies and both environments. In data, status uses the document vocabulary (issued, rejected, cancelled) and external_reference returns the id you sent on issuing, or null if you sent none.
{
"event": "invoice.authorized",
"company_id": "6f1c2a9e-3b7d-4c21-9a8e-2d5f0b6c7e14",
"tax_id": "11222333000181",
"environment": "production",
"data": {
"invoice_id": "9f2c1e3a-4b5d-4e7f-8a9b-0c1d2e3f4a5b",
"document_type": "nfe",
"access_key": "35261111222333000181550010000000421000000427",
"status": "issued",
"amount": 1500.0,
"external_reference": "pedido-1042"
}
}POST /stackin HTTP/1.1
Content-Type: application/json
Stackin-Signature: t=1795356191,v1=5c1d0e8f...
Stackin-Delivery-Id: 7d9a4c1e-2b3f-4a6d-8e0c-1f2a3b4c5d6e
User-Agent: stackin-webhooks/1On a rejection, access_key is usually null: use invoice_id as the document identifier, never the access key.
How to verify the HMAC signature
The Stackin-Signature header has the form t=<epoch>,v1=<hex>. v1 is the HMAC-SHA256, in hexadecimal, of {t}.{body}, with your secret as the key, where body is exactly the bytes received. Redo the computation, compare in constant time and refuse if t is more than 5 minutes from your clock, because the timestamp is part of what is signed precisely so that a captured delivery cannot be replayed later.
Two common mistakes: verifying over JSON that was already parsed and reserialized (one extra space changes the HMAC; read the raw body) and comparing with == instead of a constant-time function. Every retry is signed again with a fresh timestamp, so a delivery repeated hours later passes the 5-minute window as usual.
import hashlib
import hmac
import json
import os
import time
SECRET = os.environ["STACKIN_WEBHOOK_SECRET"]
TOLERANCE = 300
def is_valid(secret: str, body: bytes, header: str) -> bool:
parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
try:
timestamp = int(parts["t"])
received = parts["v1"]
except (KeyError, ValueError):
return False
if abs(time.time() - timestamp) > TOLERANCE:
return False
signed = f"{timestamp}.".encode() + body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received)
from flask import Flask, abort, request
app = Flask(__name__)
@app.post("/stackin")
def stackin():
body = request.get_data()
if not is_valid(SECRET, body, request.headers.get("Stackin-Signature", "")):
abort(401)
process(request.headers["Stackin-Delivery-Id"], json.loads(body))
return "", 204const crypto = require("node:crypto");
const express = require("express");
const SECRET = process.env.STACKIN_WEBHOOK_SECRET;
const TOLERANCE = 300;
function isValid(secret, rawBody, header) {
const parts = Object.fromEntries(
header.split(",").map((piece) => piece.split("="))
);
const timestamp = Number(parts.t);
const received = parts.v1;
if (!Number.isInteger(timestamp) || !received) return false;
if (Math.abs(Date.now() / 1000 - timestamp) > TOLERANCE) return false;
const expected = crypto
.createHmac("sha256", secret)
.update(`${timestamp}.`)
.update(rawBody)
.digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(received);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
const app = express();
app.post("/stackin", express.raw({ type: "application/json" }), (req, res) => {
if (!isValid(SECRET, req.body, req.get("Stackin-Signature") ?? "")) {
return res.sendStatus(401);
}
handle(req.get("Stackin-Delivery-Id"), JSON.parse(req.body));
res.sendStatus(204);
});Answer 401 to an invalid signature: whoever sent it was not Stackin, and the 401 only matters to them.
Retries, backoff and the delivery log
A delivery only counts as done when your server answers 2xx within 10 seconds. Anything else, be it 4xx, 5xx, a timeout, a connection failure or a redirect (which Stackin does not follow), fails the attempt. There are at most 6 attempts, waiting 30 seconds, 2 minutes, 10 minutes, 1 hour and 6 hours between them; since the queue is swept every minute, the new attempt goes out in the first minute after each wait ends. After a little over seven hours of failing, the delivery becomes failed.
The log is the route GET /webhooks/deliveries, paginated and newest first (also Webhooks.deliveries() in the SDKs and the list_webhook_deliveries tool of MCP). Each row has event, status (pending, delivered or failed), attempts, response_status, last_error (the start of your response or the connection error), next_attempt_at and delivered_at.
curl "https://api.stackin.io/api/v1/webhooks/deliveries?limit=20" \
-H "Authorization: Bearer $STACKIN_API_KEY"{
"total": 1,
"page": 1,
"per_page": 20,
"total_pages": 1,
"next_page": null,
"prev_page": null,
"has_more": false,
"data": [
{
"id": "7d9a4c1e-2b3f-4a6d-8e0c-1f2a3b4c5d6e",
"endpoint_id": "3b0e5f64-8a1c-4d7e-9c52-6f1a2b3c4d5e",
"event": "invoice.authorized",
"status": "pending",
"attempts": 2,
"response_status": 503,
"last_error": "Service Unavailable",
"next_attempt_at": "2026-11-22T14:12:40",
"delivered_at": null,
"created_at": "2026-11-22T14:03:11"
}
]
}There is no route to resend a failed delivery. If your server was down for more than seven hours, reconcile by state: GET /invoices?external_reference= and the document consult return the current situation.
One endpoint per environment
The environment is a property of the key. An endpoint registered with a homologation key only receives homologation events, and a production one only production; listing and removing are also limited to the key's environment, so a homologation key can neither see nor delete a production endpoint. Register an endpoint with each key, preferably with different URLs and secrets, and check environment in the envelope if one URL serves both. More in `/api#environments`.
How to handle a delivery idempotently
The guarantee is at least once: if your 2xx is lost on the way, the same delivery arrives again. Every attempt of the same delivery carries the same Stackin-Delivery-Id, so store the id in the same transaction as the effect and ignore what you have seen. That alone is not enough, because different deliveries can concern the same document: a consult that finds an authorization the issuance had recorded as rejected produces an invoice.authorized for the invoice_id that earlier had an invoice.rejected, and there is no ordering guarantee between them if one needs retries.
So the effect must also depend on state: move the document only to a later state than the one you already have (rejected, then issued, then cancelled) and find the order by external_reference. If the order does not exist in your database yet, raise an error and answer non-2xx: the rollback undoes the id record, and Stackin's retry finds the order saved.
import sqlite3
RANK = {"rejected": 0, "issued": 1, "cancelled": 2}
db = sqlite3.connect("receiver.db")
db.executescript(
"""
CREATE TABLE IF NOT EXISTS seen (delivery_id TEXT PRIMARY KEY);
CREATE TABLE IF NOT EXISTS orders (
reference TEXT PRIMARY KEY,
invoice_id TEXT,
access_key TEXT,
invoice_status TEXT
);
"""
)
def process(delivery_id: str, envelope: dict) -> None:
data = envelope["data"]
with db:
first_time = db.execute(
"INSERT OR IGNORE INTO seen (delivery_id) VALUES (?)", (delivery_id,)
).rowcount
if not first_time:
return
row = db.execute(
"SELECT invoice_status FROM orders WHERE reference = ?",
(data["external_reference"],),
).fetchone()
if row is None:
raise LookupError(data["external_reference"])
if RANK.get(row[0], -1) >= RANK.get(data["status"], -1):
return
db.execute(
"UPDATE orders SET invoice_id = ?, access_key = ?, invoice_status = ? "
"WHERE reference = ?",
(
data["invoice_id"],
data["access_key"],
data["status"],
data["external_reference"],
),
)Answer fast and leave the heavy work to a queue of your own: the limit is 10 seconds per attempt. The full contract is in `/api#webhooks`, and anyone issuing through the API finds the same external_reference in the SDKs and in the REST API guide.