Delivering the comprobante to your buyer
The three artifacts your buyer is owed, how to fetch them once Hacienda accepts, and why your own system sends the email.
The law requires that the buyer receives the comprobante. It does not say by email, and it does not say by whom. Sello's position is settled: your application sends it, not Sello. Your ERP, shop or accounting app already owns the buyer's address, the sent log, bounces and the "did you get my invoice?" conversation. A second sender would mean a second mailbox to debug that neither you nor Sello can see into, and a per-message cost that would end up on your bill.
So Sello's job ends where yours begins: once Hacienda answers aceptado, three
artifacts are ready for you to attach to whatever you already send.
What the buyer is owed
| Artifact | Where | Format |
|---|---|---|
| The signed comprobante — the legal document Hacienda accepted | GET /v1/documents/{clave}/xml | application/xml, verbatim XAdES |
Hacienda's acceptance message (MensajeHacienda) | GET /v1/documents/{clave}/respuesta (or respuesta-xml in GET /v1/documents/{clave}, as Base64) | application/xml, decoded, served as <clave>-respuesta.xml; 404 until Hacienda has answered |
| The representación gráfica | GET /v1/documents/{clave}/pdf | application/pdf |
The XML is the authority; the PDF is rendered from it, so the amounts match to
the last digit. Both /xml and /pdf answer 409 while the document has no
signed XML yet, so fetch them after acceptance, not after POST.
When to send
Do not poll. Register a webhook and act on
document.accepted. Its data carries the clave; that is the only key you
need for all three fetches. A document.rejected event means there is nothing
to deliver — the customer sees the reason and the fix in their Sello dashboard.
Acknowledge only after your application has durably queued the delivery. Acknowledging first and then fetching or sending loses the work if the process stops or a request fails: Sello has already received its success response.
This example is for one Sello account. deliveryQueue, yourMailer and
buyerEmailFor are adapters you implement in your own application, not SDK
methods. enqueueUnique must atomically persist both the event ID and the job,
return only after commit, and leave an existing job intact on duplicate delivery.
An in-memory queue or a separate “seen event” insert is insufficient.
import { verifyWebhook, parseWebhookEvent, WEBHOOK_SIGNATURE_HEADER } from '@magiios/sdk';
app.post('/webhooks/sello', express.raw({ type: 'application/json' }), async (req, res) => {
const raw = req.body.toString('utf8');
if (!verifyWebhook(raw, req.header(WEBHOOK_SIGNATURE_HEADER) ?? '', process.env.SELLO_WEBHOOK_SECRET!)) {
return res.sendStatus(400);
}
let event: ReturnType<typeof parseWebhookEvent>;
try {
event = parseWebhookEvent(raw);
} catch {
return res.sendStatus(400);
}
if (event.type !== 'document.accepted') return res.sendStatus(200);
try {
await deliveryQueue.enqueueUnique({
key: event.id,
payload: { clave: event.data.clave },
});
} catch {
return res.sendStatus(503); // nothing acknowledged; Sello can retry
}
return res.sendStatus(200); // the durable job now owns delivery and retries
});Every other event type is acknowledged and ignored here. If you also want to know
when a document will not reach a verdict — so there is no invoice to send — handle
document.failed; see Webhooks.
Run the following work from your queue consumer. The queue must retry failures and retain exhausted jobs for investigation. Mark a job complete only after sending succeeds; alert on exhausted retries so a missing invoice has an owner.
async function deliverAcceptedDocument(job: { key: string; payload: { clave: string } }) {
const { clave } = job.payload;
const headers = { Authorization: `Bearer ${process.env.SELLO_API_KEY}` };
const base = 'https://api.sello.cr/v1/documents/' + clave;
const [statusResponse, xmlResponse, pdfResponse] = await Promise.all([
fetch(base, { headers, signal: AbortSignal.timeout(30_000) }),
fetch(base + '/xml', { headers, signal: AbortSignal.timeout(30_000) }),
fetch(base + '/pdf', { headers, signal: AbortSignal.timeout(30_000) }),
]);
for (const response of [statusResponse, xmlResponse, pdfResponse]) {
if (!response.ok) throw new Error(`Artifact fetch failed: HTTP ${response.status}`);
}
const [status, xml, pdf] = await Promise.all([
statusResponse.json(), xmlResponse.text(), pdfResponse.arrayBuffer(),
]);
if (status['ind-estado'] !== 'aceptado' ||
typeof status['respuesta-xml'] !== 'string' || !status['respuesta-xml']) {
throw new Error('The accepted document and Hacienda response are not available yet');
}
const respuesta = Buffer.from(status['respuesta-xml'], 'base64');
await yourMailer.send({
// Your adapter must pass this through to a sender with idempotency support.
idempotencyKey: job.key,
to: await buyerEmailFor(clave), // from YOUR account's records
subject: `Factura electrónica ${clave.slice(21, 41)}`,
attachments: [
{ filename: `${clave}.xml`, content: xml, contentType: 'application/xml' },
{ filename: `${clave}-respuesta.xml`, content: respuesta, contentType: 'application/xml' },
{ filename: `${clave}.pdf`, content: Buffer.from(pdf), contentType: 'application/pdf' },
],
});
}Deduplicate webhook delivery on the event id, and reuse that ID when retrying
the send. Queue deduplication alone cannot prevent duplicate email if the sender
accepts a message and your worker stops before recording success. Use your
sender's idempotency facility where available. Otherwise retain its message ID
and reconcile ambiguous sends with its delivery log before resending; do not
claim exactly-once email from a database “sent” flag alone.
For a multi-account application, resolve the account from your trusted webhook endpoint configuration, carry it on the job, and use that account's API key and buyer records. Do not choose credentials or recipients from untrusted request fields.
If you are on Odoo
Nothing to build. The Sello connector attaches all three files to the
originating invoice in Odoo (<clave>.xml, <clave>-hacienda-respuesta.xml,
<clave>.pdf) and posts a note in the chatter with the clave. Send the invoice
from Odoo exactly as you did before; the legal files ride along.
Download the PDF by hand
curl https://api.sello.cr/v1/documents/<clave>/pdf \
-H "Authorization: Bearer $SELLO_API_KEY" \
-o comprobante.pdfThe per-state legend on the PDF reflects the document's current state. The QR field is implemented but disabled while the v4.4 QR obligation remains suspended.
Sello's own email path — opt-in, and not the recommended route
The engine still has an opt-in email path: with delivery enabled on the emisor,
POST /v1/documents/{clave}/email queues the signed XML and the PDF to the
receptor's address on Sello's outbox, idempotent per (document, recipient).
It is off by default, the onboarding wizard never turns it on, and it is not
being extended. It exists for the smallest merchant with no system of their own.
If you have a system that can send an email, use it: you will be the one asked
where the invoice went, and you should be the one who can look.
When Sello sends, Sello's sending domain and reputation are on the message, not yours, and the only delivery log is one your buyer cannot see and you cannot open. Prefer your own sender.
Recipient limits
Sello's sender is shared by every customer, so this path caps how many distinct
addresses it mails. Addresses are compared after trimming surrounding
whitespace and ignoring letter case. An address a document was already sent to
is never refused, whatever the state of its earlier send, and resending to it
with the same spelling while that send is live returns deduped: true.
- Per document. One document can be sent to at most 5 distinct addresses.
A sixth is refused with
422and the problem typehttps://sello.cr/problems/email-document-recipient-limit, with the limit inlimit. The refusal is permanent for that document. - Per account per day. An account can mail a limited number of distinct
addresses in any rolling 24 hours, set by its plan. A new address past it is
refused with
429, the problem typehttps://sello.cr/problems/email-daily-recipient-limit, the limit inlimit, and aRetry-Afterheader with the seconds until the oldest counted address leaves the window.
Sends Sello makes on its own when a document is accepted are never refused, and they count toward both limits.
On the daily limit, Retry-After can be up to 24 hours. A client that waits
for Retry-After, such as the SDK with its default retry, can hang for that
long: pass an abort signal or turn retry off for this call.