Offline NFC-e
Embedded SDK tutorial
Embedded SDK quick start: generate a pairing code, add the SDK, initialize and pair, issue your first invoice, print the receipt, receive results, offline behavior and pre-launch checks, with complete Java examples.
This page walks you through adding the embedded SDK to your POS software: while online, the SDK takes a number from the device series, signs the invoice and gets it authorized online through the platform; while offline, an offline contingency invoice is issued on the local machine and printed on the spot, then uploaded automatically once the network is back. By the end you can pair a till, issue and print your first invoice, and receive upload and cancellation results. Prerequisites: you can call the platform's open API to generate pairing codes, and the POS software runs on Windows; the issuing request is the same as the cloud issuing endpoint; item lines that reference a tax class need a connection.
You only work with the SDK, which runs the offline issuing core in the background. The whole integration looks like this:
Prepare: generate a pairing code, add the SDK, ship the runtime│▼Initialize ──► Not paired? ──► Pair (first time only, needs network)│▼Issue ──► Handle the status ──► Print the receipt│└─ Background: issues offline when disconnected, uploads automatically once online, results come as eventsDaily: cancel and query, get the authorized XML, cancellation by substitution, monthly XML export, backup and recovery from a failed computer
Every step gives the Java version. Full descriptions of methods and types are in the SDK reference; terms such as device series, offline contingency invoice and upload are explained in Numbers and series.
1 Preparation
1.1 Generate a pairing code
Each till is paired once, with a pairing code the integrator generates by calling the platform endpoint. This is the endpoint that generates pairing codes:
POST /openapi/v2/empresas/{empresaId}/nfce-offline/codigos-ativacao
The request body can be empty; to name the till and restrict pairing to the SDK only, send:
{ "nomeDispositivo": "Caixa 01", "formaPermitida": "Sdk" }
The first call enables offline issuing for the company; there is no separate enablement step. Fields and errors are in Generate pairing code. The codigoAtivacao in the response (starting with TFA1.) is the pairing code:
- The full text is returned only in this response, so hand it to the store's POS manager right away; it is valid for 72 hours and can be used once.
- It can be handed over as text, or saved as a
.tfafile (UTF-8, a single line whose content is the full pairing code). - If
ambienteis not sent, the company's current environment is used; once paired, the device always issues in that environment.
The POS software does not need to be registered on the platform in advance: pass the POS software name and version at initialization and the platform identifies it automatically.
1.2 Add the SDK
Get the SDK and the runtime from the "Downloads" tab of the "Offline issuance → Offline issuance" page in the console side menu: any signed-in user can download, and the table lists the file size and SHA-256 of each version; check the SHA-256 after downloading.
The SDK is provided as the Maven artifact com.tffiscal:tffiscal-nfce-sdk-java and supports Java 8 and later. Below is the dependency entry for pom.xml (put the published version in version):
<dependency><groupId>com.tffiscal</groupId><artifactId>tffiscal-nfce-sdk-java</artifactId><version>VERSAO_PUBLICADA</version></dependency>
The sample code on this page matches the Java sample projects in the SDK package (five scenarios: quick start, offline and upload, event handling, cancel, query and XML, files and printing).
1.3 Ship the runtime with the installer
The SDK starts a runtime child process in the background to run the offline issuing core. Put the whole tffiscal-runtime directory as is into the POS software installer (about 60 MB); the directory structure is:
tffiscal-runtime/├── tffiscal-nfce.exe├── app/├── runtime/└── VERSION
Point the runtime directory setting to it at initialization; if it is not found, 10029877 is returned. Ship the SDK and the runtime together, in the same version. When Java POS software runs on Java 21 or later, it can also use the in-process mode without shipping the runtime; see the SDK reference.
1.4 Data directory
One data directory per till, for example C:\ProgramData\MinhaLoja\TFFiscal:
- Until they are uploaded, the signed files of offline invoices exist only here and are the only legal originals. Do not delete it when uninstalling or upgrading the POS software.
- The device key is encrypted for the current Windows user: always run the POS software as the same Windows user; the directory cannot be copied to another computer or another user (
10029827). - Only one process can open it at a time (
10029828). If two POS systems are installed on the same computer, use two directories and pair them as two devices. - One directory can pair several companies (several CNPJs). With only one paired,
empresaIdcan be omitted in every method; with several, it is required. - Authorized XMLs and cancellation XMLs are downloaded here automatically after authorization; how many days they are kept is set by
RetencaoXmlDias(see 2.2). Expired ones are cleaned up automatically and fetched online again the next time they are read. - Back it up regularly with
Backup; when the computer fails before the upload can happen, export withExportarPendentesand hand it to the platform, see Backup and recovery from a failed computer.
2 Initialization and pairing
Initialize once when the POS software starts and share that instance for the whole run; the first time it runs on this computer, it also has to be paired once.
2.1 Initialization and pairing
Initialization requires the POS software name and version: the platform uses them to identify your POS software automatically and can manage it by version; if they are missing, 10029874 is returned.
The first time it runs on this computer, Ativado is false; pair with the pairing code and the company's A1 certificate:
- Pairing code: the cashier pastes the text or picks the
.tfafile. First check it locally withInspecionarCodigoAtivacaoand show the environment and expiry for the cashier to confirm; this does not go online and does not consume the code. - Certificate: pick a certificate already in the Windows certificate store (by thumbprint), or import a PFX file with its password. After a PFX import the private key cannot be exported, and the password is not stored; the certificate stays in "Current User > Personal" for permanent use, and if it is deleted the device cannot sign. Retirement and cleanup are in Certificate source.
The code below starts the SDK, attaches the event handler and, when not yet paired, checks the pairing code and pairs. When the store goes online through a proxy, or you want to change how many days XMLs are kept, add the settings from 2.2 to the same configuration.
import com.tffiscal.nfce.sdk.Certificado;import com.tffiscal.nfce.sdk.Configuracao;import com.tffiscal.nfce.sdk.EventoNfce;import com.tffiscal.nfce.sdk.Resultados;import com.tffiscal.nfce.sdk.TfFiscalException;import com.tffiscal.nfce.sdk.TfFiscalNfce;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.util.function.Consumer;public final class NfceInicio {private NfceInicio() {}/** Initializes the SDK; the listener is attached at startup, so events queued before startup are not missed. */public static TfFiscalNfce iniciar(Consumer<EventoNfce> aoEvento) {Configuracao configuracao = Configuracao.builder().diretorioDados(Paths.get("C:/ProgramData/MinhaLoja/TFFiscal")).diretorioRuntime(Paths.get("C:/Program Files/MinhaLoja/tffiscal-runtime")).nomeAplicativo("Caixa Exemplo").versaoAplicativo("1.0.0").idioma("pt-BR").aoReceberEvento(aoEvento).build();return TfFiscalNfce.iniciar(configuracao);}/** Pairs when not paired. codigoOuArquivo can be the pairing code text or a .tfa file path; when senhaPfx is null, the certificate is taken from the certificate store by thumbprint. */public static boolean ativarSeNecessario(TfFiscalNfce nfce, String codigoOuArquivo, String thumbprintOuPfx, String senhaPfx)throws IOException {if (nfce.isAtivado()) {return true;}Path arquivo = Paths.get(codigoOuArquivo);String codigo = Files.isRegularFile(arquivo)? new String(Files.readAllBytes(arquivo), StandardCharsets.UTF_8): codigoOuArquivo;codigo = codigo.replace("\uFEFF", "").trim();Certificado certificado = senhaPfx == null? Certificado.doRepositorio(thumbprintOuPfx, false): Certificado.deArquivoPfx(Files.readAllBytes(Paths.get(thumbprintOuPfx)), senhaPfx);try {Resultados.CodigoAtivacao info = nfce.inspecionarCodigoAtivacao(codigo);System.out.println("Codigo de pareamento: ambiente " + info.getAmbiente() + ", expira em " + info.getExpiraEm());Resultados.Ativacao a = nfce.ativar(codigo, certificado);System.out.println("Pareado: empresa " + a.getEmpresaId() + ", CNPJ " + a.getCnpj() + ", serie do dispositivo " + a.getSerieOffline());return true;} catch (TfFiscalException e) {int c = e.getCodigo();if (c == 10029824 || c == 10029833 || c == 10029839) {// Retryable: check the network and try again with the same pairing codeSystem.out.println("Tente de novo: " + e.getMessage());} else {// A new pairing code or certificate is needed: getMessage() is already translated according to idioma and can be shown directlySystem.out.println("Erro " + c + " " + e.getTipo() + ": " + e.getMessage());}return false;}}}
When pairing or startup fails, handle it by error code:
| Category | Error code | Handling |
|---|---|---|
| Retryable | 10029824 (cannot reach the platform), 10029833 (timeout) | Ask to check the network and retry |
| Retryable | 10029839 (paired on the platform but saving locally failed) | Pair again with the same pairing code |
| Needs a new pairing code | 10029825, 10029205 to 10029209, 10029219, 10029221 to 10029225 | Ask the integrator to generate a new pairing code |
| Needs a new certificate | 10029813, 10029814, 10029213, 10029214 | Use a valid certificate of the company |
| Fails at startup | 10029842 (the data directory was used by a newer SDK version and the local store is newer than the current program, so startup is refused) | Upgrade the SDK and the runtime to at least the version used last time; never delete the data directory |
2.2 Proxy and XML retention days
Outbound proxy: set it when the store's network needs a proxy to reach the internet; if nothing is set, the connection is direct. Three options:
| Option | How to set it | Notes |
|---|---|---|
| Direct | Set none of the proxy settings | Default |
| Manual proxy | Set Proxy to host:porta, for example 10.0.0.1:3128 | An invalid format returns 10029874 |
| System proxy | Set UsarProxyDoSistema to true | Reads the Windows proxy settings, first the machine-wide setting, then the browser proxy setting of the current Windows user; when Proxy is also set, the system proxy wins |
- Proxy authentication: set with
proxyAutenticacao(usuario, senha), usable with both the manual and the system proxy. The password is only kept in memory and handed to the runtime at startup; it is not written to disk or to the logs. If the POS software stores the password itself, store it encrypted. Setting only the authentication, with neither a proxy address nor the system proxy, returns10029874. - Proxy auto-config scripts are not supported: when Windows only has a PAC auto-config script, the SDK connects directly and writes a warning to the log. On such networks use a manual proxy, or configure a fixed proxy in Windows.
- Java in-process mode needs a startup parameter: when the platform is reached over HTTPS, Basic authentication on the proxy requires the JVM to allow Basic on tunnels, and the JVM reads this setting only once, the first time its built-in HTTP client is used; changing it later has no effect. When you use Java in-process mode (
EM_PROCESSO) with proxy authentication, add-Djdk.http.auth.tunneling.disabledSchemes=(nothing after the equals sign) to the POS software's JVM startup parameters. The core also clears it as early as possible when it loads, but if the POS software has already used the JVM's built-in HTTP client, or has itself set the property to disable Basic, clearing it has no effect; in that caseAvisosin Situacao gives a warning, and proxy authentication may fail. In Java subprocess mode the runtime handles this itself and no parameter is needed.
XML retention days: RetencaoXmlDias is how many days authorized XMLs and cancellation XMLs are kept on this machine, from 1 to 3650, 90 days when not set; out of range returns 10029874. Anything past the retention period is cleaned up automatically and fetched online again the next time it is read (see getting the XML). When exporting monthly for the accountant, keep the export range within the retention period, see Monthly XML export for the accountant.
The code below adds a manual proxy, proxy authentication and a 180-day XML retention period to the configuration from 2.1:
// Add to the Configuracao.builder() chain from 2.1: go online through a manual proxy that requires authenticationConfiguracao configuracao = Configuracao.builder().diretorioDados(Paths.get("C:/ProgramData/MinhaLoja/TFFiscal")).diretorioRuntime(Paths.get("C:/Program Files/MinhaLoja/tffiscal-runtime")).nomeAplicativo("Caixa Exemplo").versaoAplicativo("1.0.0").proxy("10.0.0.1:3128").proxyAutenticacao("caixa01", senhaProxy)// Or use the Windows system proxy instead (takes precedence over proxy): .usarProxyDoSistema(true)// Keep authorized and cancellation XMLs on this machine for 180 days.retencaoXmlDias(180).aoReceberEvento(aoEvento).build();
3 Issue your first invoice
3.1 Issuing request
The request body is the request body of Issue NFC-e; that page is the reference for field descriptions, state rules and more scenarios. With the SDK, modoResposta is not needed. Tax classes need a connection: item lines can reference a tax class with classeImposto, which the platform expands before the invoice is issued on the device; when offline or when the platform cannot be reached, the request returns 10029780, asking you to send impostos instead, and no invoice number is used, see Tax classes and connectivity. The tax codes must match the company's tax regime: Simples Nacional uses the three-digit CSOSN, the regular regime uses the two-digit CST. The two requests below are the same as pedido-exemplo.json and pedido-exemplo-regime-normal.json in the SDK package.
Simples Nacional: in-store sale, unidentified consumer, cash payment.
{"id": "EXEMPLO-0001","ambienteEmissao": "Homologacao","pedido": {"presencaConsumidor": "OperacaoPresencial","pagamento": {"formas": [{ "tipo": "Dinheiro", "valor": 50.30 }]}},"itens": [{"cfop": "5102","codigo": "7891000100101","descricao": "ARROZ BRANCO TIPO 1 5KG","ncm": "10063021","quantidade": 2,"unidadeMedida": "UN","valorUnitario": 25.15,"impostos": {"icms": { "situacaoTributaria": "102" },"pis": { "situacaoTributaria": "49" },"cofins": { "situacaoTributaria": "49" }}}]}
Regular regime: the same sale, only the tax codes differ.
{"id": "EXEMPLO-RN-0001","ambienteEmissao": "Homologacao","pedido": {"presencaConsumidor": "OperacaoPresencial","pagamento": {"formas": [{ "tipo": "Dinheiro", "valor": 50.30 }]}},"itens": [{"cfop": "5102","codigo": "7891000100101","descricao": "ARROZ BRANCO TIPO 1 5KG","ncm": "10063021","quantidade": 2,"unidadeMedida": "UN","valorUnitario": 25.15,"impostos": {"icms": { "situacaoTributaria": "00" },"pis": { "situacaoTributaria": "07" },"cofins": { "situacaoTributaria": "07" }}}]}
| Field | Fill | Description |
|---|---|---|
id | Required | POS document number. Up to 64 characters, and the idempotency key: one new id per sale, and retries of the same sale must use the same id |
ambienteEmissao | Required | Issuing environment. Same as the environment the device was paired in |
modoResposta | Do not send | The SDK always waits for the result |
pedido.presencaConsumidor | Required | Presence type. OperacaoPresencial for in-store sales |
pedido.pagamento.formas | Required | Payment details. tipo and valor of each item; the total must cover the invoice total |
pedido.pagamento.troco | Optional | Change. Fill when cash overpays; the payment total minus change must equal the invoice total |
cliente | Optional | Consumer. Omit the whole group when unidentified; when a CPF is given, send only tipoPessoa and cpfCnpj; required above the state identification threshold |
itens[].cfop / codigo / descricao / ncm / quantidade / unidadeMedida / valorUnitario | Required | Basic item line information |
itens[].ean / cest / valorDesconto | Optional | Barcode, CEST, line discount |
itens[].impostos.icms.situacaoTributaria | Required | ICMS tax code. For example 102 in Simples Nacional, 00 in the regular regime |
itens[].impostos.icms.aliquota | Optional | ICMS rate. Percentage |
itens[].impostos.pis / cofins | Required | PIS / COFINS tax codes, for example 49 in Simples Nacional, 07 in the regular regime |
itens[].classeImposto | Optional | Tax class number. When sent, cfop and impostos can be omitted; needs a connection and returns 10029780 when offline, in which case send impostos instead |
All fields are in Issue NFC-e.
3.2 Build the request and issue
The code below reads the request from the JSON file above, sets a new id, issues, and then decides whether to print based on the returned status. Your POS software can build JSON with the same structure in any way.
import com.tffiscal.nfce.sdk.ResultadoEmissao;import com.tffiscal.nfce.sdk.TfFiscalException;import com.tffiscal.nfce.sdk.TfFiscalNfce;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Paths;public final class NfceVenda {private NfceVenda() {}/** Reads the request file and sets a new id (one new id per sale). */public static String lerPedido(String arquivo, String id) throws IOException {String json = new String(Files.readAllBytes(Paths.get(arquivo)), StandardCharsets.UTF_8);return json.replaceFirst("\"id\"\\s*:\\s*\"[^\"]*\"", "\"id\": \"" + id + "\"");}/** Issues and handles the status; returns whether the receipt can be printed. */public static boolean vender(TfFiscalNfce nfce, String pedidoJson) {try {ResultadoEmissao r = nfce.emitir(pedidoJson);System.out.println("Nota " + r.getId() + ": " + r.getStatus() + " | serie " + r.getSerie() + " n. "+ r.getNumero() + " | chave " + r.getChave() + " | protocolo " + r.getProtocolo());switch (r.getStatus()) {case "Autorizada":case "ContingenciaPendente":// Invoices issued offline are printed and handed to the consumer as usual; the upload happens automaticallyreturn true;case "AguardandoAutorizacao":// Accepted online but SEFAZ has not answered: do not print yet, wait for the NOTA_AUTORIZADA (authorized) or NOTA_NEGADA (denied) eventreturn false;default:// Negada: correct according to the SEFAZ result and reissue with a new idSystem.out.println("Rejeitada: " + r.getCStat() + " " + r.getXMotivo());return false;}} catch (TfFiscalException e) {// Request validation failed, offline conditions not met, and so on: getMessage() is already translated and can be shown directlySystem.out.println("Erro " + e.getCodigo() + " " + e.getTipo() + ": " + e.getMessage() + " " + e.getDetalhesJson());return false;}}}
3.3 Returned statuses
Status | What happened | POS screen |
|---|---|---|
Autorizada | Authorized online | Print the receipt and complete the sale |
ContingenciaPendente | Could not reach the platform, issued offline on the local machine | Print and hand it to the consumer as usual; the receipt carries the offline contingency mark; you can show "Offline issuing" in a corner of the screen |
AguardandoAutorizacao | Accepted by the platform, SEFAZ has not answered yet, and offline signing was not possible at that moment | Do not print yet, show "Waiting for authorization"; print after the NOTA_AUTORIZADA event arrives. NOTA_NEGADA means SEFAZ finally denied it: this invoice cannot get a same-number correction; correct the sale data and reissue with a new id |
Negada | Rejected by SEFAZ | Show the SEFAZ result code and message, correct and reissue with a new id |
| Exception thrown | Invalid request, offline conditions not met, and so on | Show the exception message; see Common errors |
Calling Emitir again with the same id does not issue twice; it returns the original invoice. After a network timeout or a program crash, resend with the same id to get the result back.
4 Print the receipt
4.1 Print the receipt
Cupom(id, format) returns the receipt bytes; send them to the printer as is. Offline invoices carry the contingency mark, and the number of copies is set by the platform. Format values:
| Format | Meaning |
|---|---|
ESCPOS_80 | ESC/POS commands for 80mm thermal printers |
ESCPOS_58 | ESC/POS commands for 58mm thermal printers |
TEXTO | Plain text, UTF-8 |
HTML | HTML page, UTF-8, for screen preview or browser printing |
PDF_80 | 80mm-wide PDF, one page per copy, printed through the Windows printer driver, for printers that do not accept ESC/POS directly, see 4.2 |
The code below gets the ESC/POS receipt and sends it to the printer:
- The sample sends the bytes to port 9100 of a network thermal printer.
- A USB printer can be shared in Windows and written to through the share path; a serial printer can receive the same bytes through a serial port library.
import com.tffiscal.nfce.sdk.FormatoCupom;import com.tffiscal.nfce.sdk.TfFiscalNfce;import java.io.IOException;import java.io.OutputStream;import java.net.Socket;public final class NfceImpressao {private NfceImpressao() {}/** Sends the ESC/POS receipt to a network printer. */public static void imprimir(TfFiscalNfce nfce, String id, String ipImpressora) throws IOException {byte[] cupom = nfce.cupom(id, FormatoCupom.ESCPOS_80);try (Socket socket = new Socket(ipImpressora, 9100); OutputStream saida = socket.getOutputStream()) {saida.write(cupom);}}}
4.2 PDF receipt, print options and QR code image
PDF receipt: when the printer only has a Windows driver and cannot take ESC/POS commands directly, get an 80mm PDF with PDF_80 and let the PDF program associated in the system print it through the printer driver. The PDF uses the reader's built-in standard fonts, and Portuguese accents display correctly.
Print options: when the same format has to fit different printers, use the overload with print options cupom(id, format, OpcoesCupom, empresaId). Options not set use their defaults; out-of-range values return 10029874.
| Option | Values | Default |
|---|---|---|
Colunas | Characters per line. 48, 42 or 32 | By format: 48 for 80mm, 32 for 58mm |
PaginaCodigo | Printer code page. CP1252, CP860 (common on Portuguese printers), CP850 or CP437; characters missing from the code page are printed without accents | CP1252 |
ModoQrCode | How the QR code is printed. NATIVO: the printer's own QR code command; IMAGEM: printed as a bitmap, for printers without native QR code support | NATIVO |
TamanhoModuloQr | QR code module size. 1 to 16 dots | 4 |
Cortar | Cut the paper after printing. true cuts, false does not (for printers without a cutter) | true |
Vias | Number of copies. 1 to 9 | Set by the platform |
QR code image: QrCodePng(id, pixels) returns a black-and-white PNG with a quiet zone; pixels from 64 to 2048, passed explicitly; out of range returns 10029817. Use it when the POS software lays out its own documents (for example an A4 receipt).
The code below matches scenario 05 of the sample projects: it writes the PDF receipt and the QR code image to files and sends them to the default printer, then gets an ESC/POS receipt with the options of a 58mm printer (32 columns, CP850, bitmap QR code, 6-dot modules, two copies, no paper cut).
import com.tffiscal.nfce.sdk.FormatoCupom;import com.tffiscal.nfce.sdk.OpcoesCupom;import com.tffiscal.nfce.sdk.TfFiscalNfce;import java.awt.Desktop;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;public final class NfceImpressaoArquivos {private NfceImpressaoArquivos() {}/** Writes the 80mm PDF receipt and the QR code PNG to files and sends them to the default printer. */public static void pdfEQrCode(TfFiscalNfce nfce, String id, Path pasta) throws IOException {Path pdf = pasta.resolve(id + ".pdf");Files.write(pdf, nfce.cupom(id, FormatoCupom.PDF_80, null, null));Path png = pasta.resolve(id + "-qrcode.png");Files.write(png, nfce.qrCodePng(id, 300, null));// The PDF is printed on the default printer by the PDF program associated in the system (through the printer driver)if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.PRINT)) {Desktop.getDesktop().print(pdf.toFile());}}/** 58mm printer: 32 columns, CP850, bitmap QR code, 6-dot modules, two copies, no paper cut. */public static byte[] cupom58mm(TfFiscalNfce nfce, String id) {OpcoesCupom opcoes = new OpcoesCupom().colunas(32).paginaCodigo("CP850").modoQrCode(OpcoesCupom.ModoQrCode.IMAGEM).tamanhoModuloQr(6).vias(2).cortar(false);return nfce.cupom(id, FormatoCupom.ESCPOS_58, opcoes, null);}}
5 Receiving results
Upload results, cancellation results, device deactivation, and license and certificate reminders are pushed to the POS software as events. Events are delivered at least once and in order: returning normally from the handler acknowledges it, and throwing an exception redelivers it after about 30 seconds. Deduplicate by EventoId (the sample uses an in-memory set; in production store it in the POS software's database). The integrator server can also receive the results through webhooks, see How you get the results.
| Event | What the POS software does |
|---|---|
NOTA_AUTORIZADA | Mark the document as authorized; invoices waiting for authorization online (AguardandoAutorizacao) are printed now |
NOTA_NEGADA | An invoice accepted online and waiting for authorization was later denied by SEFAZ. Mark the document as denied and alert the cashier; this invoice cannot get a same-number correction: correct the sale data and reissue with a new id |
NOTA_REJEITADA | SEFAZ rejected the upload of an offline invoice. Alert the administrator and make a same-number correction with Substituir; do not issue a new invoice |
NOTA_RECUSADA_PLATAFORMA | The platform refused the offline invoice; log it and contact the platform |
CANCELAMENTO_CONCLUIDO / CANCELAMENTO_REJEITADO | Update the cancellation result; if rejected, the invoice is still valid |
NUMERO_INUTILIZACAO_RECUSADA | The platform refused the voiding request for unused numbers. When definitivo is false the core retries automatically, so just log it; when true it is final (invalid number range, or invoices already exist in the range), and the range must be checked manually with the integrator |
DISPOSITIVO_DESATIVADO | Show a prominent "This till can no longer issue" |
LICENCA_EXPIRANDO / PRAZO_TRANSMISSAO_PROXIMO | Ask to restore the network soon |
CERTIFICADO_EXPIRANDO | Ask to renew the certificate, then call TrocarCertificado |
All events and data fields are in the SDK reference.
Which thread events arrive on: in subprocess mode, events are called back serially on a dedicated background thread of the wrapper; in in-process mode, they are called back synchronously on the core's delivery thread. Swing screens switch back to the UI thread with SwingUtilities.invokeLater.
Only record in the handler, do not call SDK methods: put the documents to process later (for example the id of a rejected upload) in a queue and let the POS software's main flow take them out and process them.
The code below deduplicates by EventoId, handles each event type, and puts rejected uploads in a queue so that the main flow makes a same-number correction with Substituir:
import com.tffiscal.nfce.sdk.EventoNfce;import com.tffiscal.nfce.sdk.ResultadoEmissao;import com.tffiscal.nfce.sdk.SituacaoNota;import com.tffiscal.nfce.sdk.TfFiscalNfce;import java.util.Map;import java.util.Queue;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentLinkedQueue;public final class NfceEventos {private final Set<String> vistos = ConcurrentHashMap.newKeySet();private final Queue<String> rejeitadas = new ConcurrentLinkedQueue<>();/** Event listener: pass it to Configuracao.Builder.aoReceberEvento. Returning normally acknowledges; throwing causes redelivery. */public void aoReceber(EventoNfce e) {// At-least-once delivery: the same event may arrive more than once, deduplicate by eventoId (in production, store processed eventoId values in the database)if (!vistos.add(e.getEventoId())) {return;}Map<String, Object> d = e.getDados();switch (e.getTipo()) {case "NOTA_AUTORIZADA":System.out.println("Nota " + e.getId() + " autorizada, protocolo " + d.get("protocolo")+ (Boolean.TRUE.equals(d.get("aposCorrecao")) ? " (apos correcao)" : ""));break;case "NOTA_NEGADA":// An invoice waiting for authorization online was later denied by SEFAZ: no same-number correction; correct the sale data and reissue with a new idSystem.out.println("Nota " + e.getId() + " negada pela SEFAZ: " + d.get("cStat") + " " + d.get("motivo")+ " - corrija a venda e emita de novo com um novo id");break;case "NOTA_REJEITADA":// Upload of an offline invoice rejected: put it in a queue; the main flow makes a same-number correction with substituirSystem.out.println("Nota " + e.getId() + " rejeitada pela SEFAZ: " + d.get("cStat") + " " + d.get("motivo"));rejeitadas.add(e.getId());break;case "NOTA_RECUSADA_PLATAFORMA":System.out.println("Nota " + e.getId() + " recusada pela plataforma: " + d.get("codigo") + " " + d.get("mensagem"));break;case "CANCELAMENTO_CONCLUIDO":case "CANCELAMENTO_REJEITADO":System.out.println("Cancelamento da nota " + e.getId() + ": " + e.getTipo() + " " + d.get("cStat") + " " + d.get("motivo"));break;case "NUMERO_INUTILIZACAO_RECUSADA":// definitivo=true: invalid range or invoices already exist in the range, check manually; false: the core retries by itselfSystem.out.println("Inutilizacao recusada: serie " + d.get("serie") + " " + d.get("inicio") + "-" + d.get("fim")+ ": " + d.get("mensagem") + (Boolean.TRUE.equals(d.get("definitivo")) ? " - verificar manualmente" : ""));break;case "DISPOSITIVO_DESATIVADO":System.out.println("Este caixa nao emite mais: " + d.get("situacao") + " " + d.get("motivo"));break;case "LICENCA_EXPIRANDO":case "PRAZO_TRANSMISSAO_PROXIMO":System.out.println("Restabeleca a internet o quanto antes");break;case "CERTIFICADO_EXPIRANDO":System.out.println("Certificado A1 valido ate " + d.get("validoAte") + "; troque com trocarCertificado");break;default:// New event types can be safely ignoredbreak;}}/** Called periodically by the main flow: correct rejected uploads under the same number. */public void corrigirRejeitadas(TfFiscalNfce nfce) {String id;while ((id = rejeitadas.poll()) != null) {SituacaoNota original = nfce.consultar(id);// Fix the matching non-amount fields (such as NCM, CFOP) according to cStat / motivo of NOTA_REJEITADA; amounts and taxes cannot changeString corrigido = original.getPedido();ResultadoEmissao r = nfce.substituir(id, corrigido, null);System.out.println("Substituir " + r.getId() + ": " + r.getStatus() + ", numero " + r.getNumero() + " (mesmo numero)");}}}
Same-number correction can only change content that does not affect amounts or taxes (for example item NCM, CFOP, consumer document); the number, access key and issue time stay the same; a change in amounts or taxes returns 10029821. When the corrected invoice is uploaded and authorized, the NOTA_AUTORIZADA you receive has aposCorrecao set to true.
6 What happens when the network is down
While offline, the cashier issues invoices as usual, and the POS software needs no extra branch. The upload rules themselves (pending upload status, automatic upload, same-number correction after a rejection, upload deadline, which invoices cannot be issued offline) are in Offline invoices and upload; this section only covers what the SDK does:
Emitirtries online first; on wait timeout or when the platform cannot be reached, it issues an offline contingency invoice on the local machine and returnsContingenciaPendente. If the last connection attempt just failed, it issues offline right away without waiting.- The receipt is printed as usual, with the offline contingency mark and a "pending authorization" notice added automatically, and no protocol number.
- Once the network is back, the core uploads automatically with no call needed; to upload immediately, call
SincronizarAgora, for example when you detect that the network is back; it only triggers the next background sync round and returns immediately, so it can be called on the UI thread. - After the upload is authorized you receive the
NOTA_AUTORIZADAevent; when SEFAZ rejects the upload of an offline invoice you receiveNOTA_REJEITADA, and you make a same-number correction withSubstituir; see section 5.
When an invoice cannot be issued offline, Emitir throws an exception:
| Error code | Situation | How it clears |
|---|---|---|
10029804 / 10029807 / 10029810 | License expired / offline deadline passed / the oldest invoice waiting for upload passed the upload deadline | Clears automatically once the network is back |
10029808 | The device series reached number 999999999 | Deactivate the device and pair it again with a new pairing code that sets a new series in serie; the platform does not change the series by itself |
10029811 | The state or company does not allow offline issuing | Online issuing only |
10029812 | Invoice with fuel | Cannot be issued offline; online issuing only |
We recommend that the POS screen read Situacao periodically (for example every 10 seconds) to inform the cashier:
Field in Situacao | Screen message |
|---|---|
Conectado is false | "Offline, invoices will be uploaded once online" |
PendentesTransmissao | "N invoices waiting for upload" |
PrazoTransmissaoAte | "Restore the network before a given time", highlighted as it gets close |
OfflineAte | Ask to go online soon when the offline duration is about to run out |
Avisos is not empty | The runtime environment needs a technician; log the original text or show it to technical support |
7 Pre-launch checklist
- The full flow works in the testing environment: pairing, online issuing (
Autorizada), offline issuing (ContingenciaPendente), andNOTA_AUTORIZADAreceived after the network is back. - Resending the same
iddoes not issue extra invoices; after a crash and restart,Consultargets the result back. - Events are deduplicated by
EventoId, and the deduplication records are persisted;NOTA_NEGADA(reissue with a newid) andNOTA_REJEITADA(same-number correction) are handled separately. - Receipts print clearly on the printers actually used in the store, and the QR code can be scanned; printers that do not accept ESC/POS directly have been tested with
PDF_80. - The installer includes the runtime directory; upgrading and uninstalling do not delete the data directory; the POS software always runs as the same Windows user.
- The POS screen can show the offline status, the number of invoices waiting for upload and the upload deadline.
- Certificate expiry and device deactivation are shown prominently.
XmlAutorizado,XmlCancelamento,ExportarXmls,Backup,RestaurarBackupandExportarPendentesare all called on a background thread, and the UI does not freeze;SincronizarAgorareturns immediately and can be called directly.- When the store goes online through a proxy, pairing and issuing have been tested on the real network.
- There are regular encrypted backups, with the passphrase kept separate from the backup files and not written into the program; restoring from a backup before
Iniciarhas been rehearsed; and the staff know how to export a pending upload package and hand it to the platform when the computer fails, see Backup and recovery from a failed computer. - After the company switches to the production environment, generate new pairing codes in production, pair new devices, and deactivate the test devices.
- With primary/secondary mode, you have rehearsed the primary going down (the secondary returns
10029880and the till moves to the backup machine) and revoking a secondary (it then returns10029882).
Next steps
- Operations and advanced tasks: cancellation, cancellation by substitution, query and receipt reprint, getting and exporting XMLs monthly, backup and recovery from a failed computer, closing and restarting.
- Multiple tills (primary and secondary mode): several tills in one store sharing one device series.
- SDK reference: settings, every method, data types, events and error codes.
Common errors and handling
| Error code | Situation | Handling |
|---|---|---|
| 10029801 / 10029802 | The company is not paired on this machine / several companies are paired but empresaId was not passed | Pair first; pass empresaId |
| 10029804 / 10029807 | Offline and the license expired / offline deadline passed | Restore the network; renewal is automatic |
| 10029808 | Device series numbers used up to 999999999 | Deactivate the device and pair it again with a new pairing code that sets a new series in serie; the platform does not change the series by itself |
| 10029809 | System clock was set back | Correct the system time |
| 10029810 | The oldest invoice waiting for upload passed the upload deadline | Restore the network and upload as soon as possible |
| 10029811 / 10029812 | Offline not allowed, or just restored from a backup and no new license yet / invoice with fuel | Issue online only; after a restore, offline issuing resumes automatically after one online sync |
| 10029813 / 10029814 | Certificate unavailable / expired | Check the certificate; after renewal call TrocarCertificado |
| 10029816 | The device has been deactivated | Contact the integrator |
| 10029817 | Request validation failed: missing required field, invalid value or field not in the contract (each one naming the field path) | Fix according to Detalhes; you can validate first with Previsualizar |
| 10029780 | An item line references a tax class, but the platform cannot be reached to expand it; no invoice number was used | Resend with the same id once the connection is back; when offline, send impostos on the item lines |
| 10029818 | The same id was already used for an invoice with different content | Use a new id for a new sale |
| 10029819 | No document with this id on this machine | Check id and empresaId |
| 10029822 | The current status does not allow cancellation | Do not retry when already cancelled or a cancellation is in progress; for cancellation by substitution, the original must be a regular invoice issued online |
| 10029827 | The data directory comes from another computer or another Windows user | Run as the original user; to replace the computer, deactivate the old device and pair again |
| 10029828 | The data directory is in use by another process | Run only one instance; restoring a backup must happen before Iniciar, so call Encerrar first on an instance already started |
| 10029832 / 10029833 | Runtime exited unexpectedly / wait timeout | Retry with the same id |
| 10029841 | Authorized XML not available yet | If not authorized yet, wait for NOTA_AUTORIZADA; if authorized and still reported, the platform has not archived it or cannot be reached, so retry later |
| 10029842 | The local store is newer than the program | The data directory was used by a newer SDK version and startup is refused: upgrade the SDK and the runtime to at least the version used last time; never delete the data directory |
| 10029843 | Cancellation XML not available yet | If not successfully cancelled yet, wait for CANCELAMENTO_CONCLUIDO; if cancelled and still reported, the platform has not archived it or cannot be reached, so retry later |
| 10029844 | Failed to write the file | The export or backup directory cannot be written, or the backup file already exists: change the directory or file name, and check disk space and permissions |
| 10029845 | Invalid substitute invoice key | Pass the 44-digit key of an offline substitute invoice issued on this machine, with the same CNPJ, not refused by the platform |
| 10029846 | The backup cannot be restored | Wrong passphrase, or the backup file was altered or corrupted: check the passphrase and use an intact backup; the original store was not changed |
| 10029874 | Invalid parameter, for example the POS software name or version missing at initialization, a wrongly formatted proxy, or print options or export dates out of range | Complete or fix the parameters according to Detalhes |
| 10029877 | Runtime not found | Check the runtime directory in the installer |
| 10029880 / 10029881 | The secondary cannot reach the primary / the request was sent but no response came back from the primary | Retry later or move to the backup machine; for an unknown result, call Consultar with the same id after the primary recovers |
| 10029882 | The terminal token of the secondary is invalid or revoked | Issue a new terminal token on the primary and update TokenTerminal |
| 10029884 | A secondary called a primary-only method | Run pairing, certificate change, backup and export on the primary |
| 10029307 | The device environment differs from the company's current environment | Generate a new pairing code in the company's current environment and pair a new device |
All error codes and handling advice are in the SDK reference and Error codes.
Why does issuing take a moment while offline?
The core tries online first and only switches to offline issuing after the wait times out; the result has TentativaOnline set to true; this offline invoice uses the next number, and the platform settles the number of the online attempt with nothing for you to do. If the last connection attempt just failed, it issues offline right away without waiting.
How do I test offline issuing?
Pair a test computer in the testing environment, disconnect that computer from the network and issue; invoices in the testing environment have no fiscal value.
What if I replace the POS computer?
First let the old computer go online and upload all offline invoices, then deactivate the old device, generate a new pairing code for the new computer and pair it. Do not copy the data directory.
The old computer failed and the offline invoices have not been uploaded yet. What now?
If the computer still boots, export the invoices waiting for upload with ExportarPendentes, zip the whole pendentes-… subdirectory of this export into one zip file and give it to platform operations, who upload it directly under "Import pending package" (the export is already split into folders by device with at most 500 invoices per package, so no unzipping or further splitting is needed), then deactivate the old device and pair the new computer again; see path 1 in Backup and recovery from a failed computer. An encrypted backup can only be restored on the original computer and does not help when changing computers. If the computer no longer boots, contact the platform.
What is the difference between an online invoice being denied (NOTA_NEGADA) and the upload of an offline invoice being rejected (NOTA_REJEITADA)?
An online invoice that was denied cannot be corrected: correct the sale data and reissue with a new id. An offline invoice has already been printed and handed to the consumer, so when its upload is rejected, make a same-number correction with Substituir; the number and access key stay the same.
