Skip to Content
SelloDeveloper docs
Guides

Issuing documents

The seven document types and the tipo discriminator.

Every comprobante you issue goes through the same endpoint — POST /v1/documents — and is discriminated by its tipo field. tipo selects both the document semantics and the request shape.

The document types

tipoDocumentNotes
FEFactura ElectrónicaStandard sales invoice with an identified receptor.
TETiquete ElectrónicoTicket / receipt — no identified receptor required.
NCNota de CréditoCredit note. Must reference the document it corrects.
NDNota de DébitoDebit note. Must reference the document it corrects.
FECFactura Electrónica de CompraPurchase invoice (self-billing). Must carry a reference. Non-domiciled supplier only — see below.
FEEFactura Electrónica de ExportaciónExport invoice. Requires a foreign receptor.
REPRecibo Electrónico de PagoPayment receipt. Must carry a reference.

The tipo discriminator

The request body is a discriminated union on tipo. The engine picks the right schema from the value you send:

{
  "tipo": "FE",
  "emisor": { "…": "…" },
  "receptor": { "…": "…" },
  "condicionVenta": "01",
  "medioPago": ["01"],
  "detalleServicio": [ /* line items */ ],
  "resumenFactura": { /* totals */ }
}

Type-specific rules the engine enforces:

  • NC / ND / FEC / REP must carry informacionReferencia — the reference to the document they relate to.
  • FEE requires a foreign receptor.
  • FEC supports a non-domiciled supplier — the supplier is the emisor with identificacion.tipo 05, and you are the receptor who signs. A supplier inside Costa Rica who is not obliged to issue electronically — the régimen simplificado and the régimen especial agropecuario — needs an emisor ubicacion and a codigoActividadReceptor that the engine does not yet require or verify. Do not send that shape: Hacienda rejects it and the consecutivo is spent.
  • clave, numeroConsecutivo, fechaEmision are server-allocated — never send them on create. They are refused with a 422, not ignored, and so is any other field the request does not define: a misspelled key is named in errors[].path instead of being dropped.
  • Limits: at most 1000 lines in detalleServicio (Hacienda's maximum) and a body of at most 2 MiB. For very large lines the byte limit is the one you reach first.

Common fields

Every type shares a common core:

  • emisor — the issuing taxpayer.
  • receptor — the recipient (optional for TE).
  • condicionVenta — sale condition (01 contado, 02 crédito, …).
  • medioPago — an array of payment methods (01 efectivo, 02 tarjeta, …). Send exactly one. The engine writes the per-method amount only for a single method, so a split payment builds a document Hacienda rejects.
  • detalleServicio — the line items (each with its CABYS code and IVA — see CABYS and IVA rates).
  • resumenFactura — the totals block, all monetary values as exact-decimal strings (see Money and decimals).
  • sucursal and terminal — which series the document is numbered on: the branch (3 digits) and the till / punto de venta (5 digits) that open the 20-digit numeroConsecutivo. Hacienda keeps a separate consecutivo series per emisor, sucursal, terminal and document type, and so does Sello. Both are optional and default to 1 (001 / 00001). If you moved to Sello from another system, seed each series with the last number Hacienda accepted in the onboarding wizard (step 3, Numeración) before issuing on it — a series that was never seeded starts at 1, and Hacienda rejects a number it has already accepted.

With the SDK, tipo is the discriminant on documents.create:

const accepted = await sello.documents.create(
  {
    tipo: 'FE',
    emisor: { /* … */ },
    receptor: { nombre: 'Cliente' },
    condicionVenta: '01',
    medioPago: ['01'],
    detalleServicio: [ /* … */ ],
    resumenFactura: {
      totalVenta: '1000.00',
      totalImpuesto: '130.00',
      totalComprobante: '1130.00',
    },
  },
  `order-${order.id}:FE`, // the Idempotency-Key — required
);

The second argument is the Idempotency-Key, and the SDK refuses a call without one. Derive it from the business event — the order, the sale — and store it with that event. Send the same key every time your code retries that event, whether a queue redelivers it, a job runs again or someone clicks twice, and pass it to createAndWait the same way. Sello then returns the original document instead of issuing a second one. Never derive the key from the document's content: two real sales can carry the same lines and totals. A separate document for the same order, such as an NC that credits it, is a new event and gets its own key (order-${order.id}:NC-1). See Idempotency.

The create returns 201 (a 200 on an idempotent replay) with the allocated clave and the document already signed; see Async issuance for what happens next.

The response may also carry an advisory warnings[] array — non-blocking findings (an unknown CABYS code, or an IVA rate that diverges from the catalog) surfaced without failing the create. It's omitted when there are none. Each RuleWarning has a code (cabys_not_in_catalog | iva_rate_divergence), a human-readable message, and, when known, a 0-based line index into your line items. On an idempotent replay the warnings reproduce verbatim.

Desde el portal

Quien no programa puede emitir desde el portal. Una factura o un tiquete, en Documents → Emitir factura. Una nota de crédito o de débito, desde la página de una factura o un tiquete aceptado: Emitir nota de crédito o Emitir nota de débito. El formulario pasa por el mismo createDocument y la misma matriz de escenarios publicada que POST /v1/documents, así que admite y rechaza exactamente lo mismo, y un rechazo no gasta ningún consecutivo.

Lo que el portal emite hoy:

  • Factura electrónica (FE), en colones (CRC) o dólares (USD). En USD el formulario sugiere el tipo de cambio de venta del BCCR y muestra su fecha; usted puede cambiarlo, y si la consulta falla lo ingresa usted. Un tipo de cambio cambiado o ingresado a mano se marca ingresado manualmente.
  • Tiquete electrónico (TE), en colones (CRC). En un tiquete el receptor es opcional: puede ir sin receptor, con solo el nombre o completo.
  • Nota de crédito (NC) y nota de débito (ND), en colones (CRC), sobre una FE o un TE que la cuenta emitió por Sello, para el mismo emisor. El formulario trae el receptor, la venta y las líneas del original, y pide el código de referencia y la razón; Sello toma el tipo, la clave y la fecha del original de lo que guardó. Los códigos 01 y 13 anulan el comprobante completo y llevan sus mismas líneas; un ajuste parcial usa 02 o 14. Una nota de crédito que pase lo que le queda por acreditar al original se avisa antes de enviarla, y Sello la rechaza.
  • Líneas con IVA a una de las tarifas 13 %, 4 %, 2 %, 1 % o exento, con su código CABYS de 13 dígitos. Son las que asigna el catálogo CABYS vigente; 8 % y 0,5 % no las asigna ningún código, así que van por /v1.
  • Cantidad con 3 decimales como máximo y precio unitario con 5 decimales como máximo.
  • Condición de venta contado (01) o crédito (02, con el plazo en días).
  • Un medio de pago, del 01 al 07.
  • La serie (sucursal y caja) que el cliente elige entre las que ya numeró para ese tipo de comprobante; 001 / 00001 si no elige otra.
  • En una FE, un descuento por línea, opcional, por monto o por porcentaje, con código de descuento 01 a 09 o 99.
  • En una FE, exoneración por línea gravada, de tipo 08 o 99. Para una autorización AL- puede usar Consultar autorización, que completa los datos del registro. También puede ingresar los datos usted (por ejemplo, si la consulta falla); esa exoneración queda marcada ingresado manualmente.
  • En una FE, hasta diez otros cargos del documento, de tipo 01 a 10 o 99, por monto o por porcentaje sobre la venta neta.

El formulario muestra el neto de cada línea y el monto de cada cargo, pero no calcula el IVA ni los totales fiscales: aparecen como calculado al emitir.

Un TE, una NC o una ND del portal van en colones, sin descuento, exoneración ni otros cargos. Una nota solo cita un comprobante que Hacienda aceptó. Si el original lleva algo que el portal no pone en una nota (otra moneda que el colón, un descuento, una exoneración, otros cargos o algo de la lista de abajo), su página lo dice y la nota va por /v1.

Los datos del emisor —nombre, cédula, correo, ubicación y actividad económica— salen de su registro en Sello, no del formulario. Un emisor sin actividad registrada no puede emitir hasta completarla en el paso 1.

Lo que el portal no emite, y sigue yendo por /v1:

  • Otros tipos: FEC, FEE y REP.
  • Una nota sobre una NC, una ND o un comprobante que la cuenta no emitió por Sello, o con más de una referencia.
  • Monedas distintas de CRC y USD.
  • Exoneraciones de tipos distintos de 08 y 99, impuestos específicos e IVA cobrado a nivel de fábrica.
  • Varios medios de pago, o el medio de pago 99 (otros).
  • Códigos CABYS que piden campos de sector (por ejemplo VIN o medicamentos) o surtidos.

Si el comprobante que necesita está en esa lista, emítalo con la API.

En producción, Emitir (o Enter en un campo) todavía no envía nada: abre Revise antes de emitir, con un resumen fijo del comprobante tal como va a salir: Emisor (nombre e identificación del emisor a cuyo nombre sale), Tipo, Receptor, Identificación, Moneda y Total. Debajo, una frase recuerda que no hay vuelta atrás: «Hacienda no permite anular un comprobante emitido. Para revertirlo hay que emitir una nota de crédito.» En una nota de crédito la frase termina en «una nota de débito», porque lo que elimina una NC es una ND. El botón que emite se habilita cuando el portal calculó el total de ese mismo cuerpo; mientras tanto el total dice Calculando…. Si un dato cambia con la revisión abierta (por ejemplo, llega la respuesta del tipo de cambio o del nombre del receptor), la revisión queda desactualizada: el portal lo avisa, deshabilita el botón y ofrece Actualizar resumen para revisar los datos nuevos. Cancelar cierra la revisión sin enviar nada y deja el formulario como estaba. En sandbox, Emitir emite con un solo clic, sin revisión.

Si Sello firma la factura con advertencias (warnings[], por ejemplo una tarifa de IVA distinta de la que el catálogo asigna al código CABYS), el portal no lo lleva directo a la factura: le muestra cada advertencia y un enlace a ella.

Preview the totals before issuing

POST /v1/documents/calculate takes the exact POST /v1/documents body and answers what a fresh create would sign: each line's amounts and taxes, the ResumenFactura totals and the advisory warnings. The same engine code that issues computes them, so the totals are the ones the issued XML carries.

Nothing is issued. No consecutivo or clave is allocated, nothing is signed, stored or sent to Hacienda, and the call is not counted as a document. The Idempotency-Key and Sello-Replay-Only headers are ignored.

curl https://api.sello.cr/v1/documents/calculate \
  -H "Authorization: Bearer $SELLO_KEY" \
  -H "Sello-Emisor-Id: $EMISOR_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "tipo": "FE",
    "emisor": {
      "nombre": "Emisor de Prueba S.A.",
      "identificacion": { "tipo": "02", "numero": "3101123456" },
      "ubicacion": { "provincia": "1", "canton": "01", "distrito": "01", "otrasSenas": "Oficentro 200m norte" },
      "correoElectronico": "emisor@example.com"
    },
    "receptor": {
      "nombre": "Cliente de Prueba",
      "identificacion": { "tipo": "01", "numero": "112345678" },
      "correoElectronico": "cliente@example.com"
    },
    "condicionVenta": "01",
    "medioPago": ["01"],
    "detalleServicio": [{
      "numeroLinea": 1, "codigo": "8511000000000", "cantidad": "2.000", "unidadMedida": "Sp",
      "detalle": "Servicio de prueba", "precioUnitario": "5000.00000", "montoTotal": "10000.00000",
      "subtotal": "10000.00000",
      "impuesto": [{ "codigo": "01", "codigoTarifa": "08", "tarifa": "13.00", "monto": "1300.00000" }],
      "montoTotalLinea": "11300.00000"
    }]
  }'

The answer is a DocumentCalculation:

  • lineas[]: per line, montoTotal, subtotal (after the discount), descuento (the discount amount, or a decimal zero; absent on a REP), baseImponible (absent on FEE and REP), each impuesto with its codigo, codigoTarifa, tarifa, monto and, when one is emitted, exoneracion.montoExoneracion, then impuestoNeto (absent on FEE) and montoTotalLinea.
  • resumenFactura: only the totals the XML would carry, in their XML spelling. codigoTipoMoneda is always present.
  • warnings[]: CABYS warnings, then an exchange-rate warning; empty when none apply. catalogVersion names the CABYS edition when rules were in force.
  • exchangeRate, fechaEmision and issuanceGuaranteed: false.

With the SDK, documents.calculate takes the same body you pass to documents.create, and no idempotency key:

const preview = await sello.documents.calculate(body, {
  emisorId, // only for an account-wide key, as on create
  signal,   // optional AbortSignal, e.g. to drop a stale preview
});
preview.resumenFactura.totalComprobante; // '11300.00000'
preview.warnings;                        // [] when nothing applies

The SDK's transport retries send the same body again; nothing is issued, so there is nothing to deduplicate. A non-2xx throws SelloApiError, with the same status, problem and errors a create would raise.

You still send valid derived line amounts. montoTotal, subtotal, each monto and montoTotalLinea stay required, and a wrong one is the same 422 a create returns. Every fiscal refusal (issuer identity and profile, the supported-scenario matrix, CABYS, net totals, line and summary divergence) is the create refusal.

Permissions. A key holding documents:read or documents:write may calculate. A key holding neither gets 403 insufficient-permission with requiredPermissions: ["documents:read", "documents:write"]. Suspended and closed accounts cannot calculate.

What a 200 does not prove. Calculation skips the issuance setup: reception credentials, series seeding for a migrating emisor, the signing certificate and the plan's document allowance. A preview can succeed where a create would still refuse, and a later create validates again: time, rules, the emisor profile, references and rates can change in between.

What it does write. Ordinary request bookkeeping only: the rate-limit window (the call spends the account's request budget), an access-denied audit row on a refused key, the throttled lastUsedAt of the API key, and a payload capture when an operator turned capture on.

Desde el portal

El formulario de emisión pide la vista previa al portal (POST /portal/emisores/:emisorId/documents/calculate, con el mismo cuerpo que la emisión y la idempotencyKey opcional) 400 ms después del último cambio, cuando el formulario está completo. Lo hace para una FE, un TE, una NC o una ND: un TE no espera un receptor, y una nota espera su razón. Muestra el subtotal, los descuentos, el IVA por tarifa, los otros cargos, el total y las advertencias, con el aviso «Vista previa. El cálculo no garantiza que la factura pueda emitirse.» (en un TE o una nota, «que el comprobante pueda emitirse»). La vista previa nunca cambia la clave del envío. En sandbox tampoco bloquea Emitir, que emite con un solo clic.

En producción, Emitir (o Enter en un campo) abre Revise antes de emitir con un resumen fijo: Emisor (nombre e identificación), Tipo, Receptor, Identificación, Moneda y Total, y debajo la frase «Hacienda no permite anular un comprobante emitido. Para revertirlo hay que emitir una nota de crédito.» (en una NC, «una nota de débito»). El total es el de la vista previa calculada para ese mismo cuerpo, y el botón que emite espera ese cálculo: mientras no llega, el total dice Calculando…, y si el cálculo falla, muestra el error de la vista previa y el botón sigue deshabilitado. La revisión envía exactamente lo que resume. Si un dato cambia con la revisión abierta, queda desactualizada y hay que pulsar Actualizar resumen antes de emitir. Cancelar no envía nada.

On this page