TF Fiscal
Documentation

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:

text
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 events
Daily: 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:

http
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:

json
{ "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 .tfa file (UTF-8, a single line whose content is the full pairing code).
  • If ambiente is 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):

xml
<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:

text
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, empresaId can 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 with ExportarPendentes and 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 .tfa file. First check it locally with InspecionarCodigoAtivacao and 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.

java
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 code
System.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 directly
System.out.println("Erro " + c + " " + e.getTipo() + ": " + e.getMessage());
}
return false;
}
}
}

When pairing or startup fails, handle it by error code:

CategoryError codeHandling
Retryable10029824 (cannot reach the platform), 10029833 (timeout)Ask to check the network and retry
Retryable10029839 (paired on the platform but saving locally failed)Pair again with the same pairing code
Needs a new pairing code10029825, 10029205 to 10029209, 10029219, 10029221 to 10029225Ask the integrator to generate a new pairing code
Needs a new certificate10029813, 10029814, 10029213, 10029214Use a valid certificate of the company
Fails at startup10029842 (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:

OptionHow to set itNotes
DirectSet none of the proxy settingsDefault
Manual proxySet Proxy to host:porta, for example 10.0.0.1:3128An invalid format returns 10029874
System proxySet UsarProxyDoSistema to trueReads 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, returns 10029874.
  • 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 case Avisos in 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:

java
// Add to the Configuracao.builder() chain from 2.1: go online through a manual proxy that requires authentication
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")
.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.

json
{
"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.

json
{
"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" }
}
}
]
}
FieldFillDescription
idRequiredPOS 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
ambienteEmissaoRequiredIssuing environment. Same as the environment the device was paired in
modoRespostaDo not sendThe SDK always waits for the result
pedido.presencaConsumidorRequiredPresence type. OperacaoPresencial for in-store sales
pedido.pagamento.formasRequiredPayment details. tipo and valor of each item; the total must cover the invoice total
pedido.pagamento.trocoOptionalChange. Fill when cash overpays; the payment total minus change must equal the invoice total
clienteOptionalConsumer. 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 / valorUnitarioRequiredBasic item line information
itens[].ean / cest / valorDescontoOptionalBarcode, CEST, line discount
itens[].impostos.icms.situacaoTributariaRequiredICMS tax code. For example 102 in Simples Nacional, 00 in the regular regime
itens[].impostos.icms.aliquotaOptionalICMS rate. Percentage
itens[].impostos.pis / cofinsRequiredPIS / COFINS tax codes, for example 49 in Simples Nacional, 07 in the regular regime
itens[].classeImpostoOptionalTax 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.

java
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 automatically
return true;
case "AguardandoAutorizacao":
// Accepted online but SEFAZ has not answered: do not print yet, wait for the NOTA_AUTORIZADA (authorized) or NOTA_NEGADA (denied) event
return false;
default:
// Negada: correct according to the SEFAZ result and reissue with a new id
System.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 directly
System.out.println("Erro " + e.getCodigo() + " " + e.getTipo() + ": " + e.getMessage() + " " + e.getDetalhesJson());
return false;
}
}
}

3.3 Returned statuses

StatusWhat happenedPOS screen
AutorizadaAuthorized onlinePrint the receipt and complete the sale
ContingenciaPendenteCould not reach the platform, issued offline on the local machinePrint 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
AguardandoAutorizacaoAccepted by the platform, SEFAZ has not answered yet, and offline signing was not possible at that momentDo 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
NegadaRejected by SEFAZShow the SEFAZ result code and message, correct and reissue with a new id
Exception thrownInvalid request, offline conditions not met, and so onShow 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:

FormatMeaning
ESCPOS_80ESC/POS commands for 80mm thermal printers
ESCPOS_58ESC/POS commands for 58mm thermal printers
TEXTOPlain text, UTF-8
HTMLHTML page, UTF-8, for screen preview or browser printing
PDF_8080mm-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.
java
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.

OptionValuesDefault
ColunasCharacters per line. 48, 42 or 32By format: 48 for 80mm, 32 for 58mm
PaginaCodigoPrinter code page. CP1252, CP860 (common on Portuguese printers), CP850 or CP437; characters missing from the code page are printed without accentsCP1252
ModoQrCodeHow the QR code is printed. NATIVO: the printer's own QR code command; IMAGEM: printed as a bitmap, for printers without native QR code supportNATIVO
TamanhoModuloQrQR code module size. 1 to 16 dots4
CortarCut the paper after printing. true cuts, false does not (for printers without a cutter)true
ViasNumber of copies. 1 to 9Set 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).

java
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.

EventWhat the POS software does
NOTA_AUTORIZADAMark the document as authorized; invoices waiting for authorization online (AguardandoAutorizacao) are printed now
NOTA_NEGADAAn 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_REJEITADASEFAZ 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_PLATAFORMAThe platform refused the offline invoice; log it and contact the platform
CANCELAMENTO_CONCLUIDO / CANCELAMENTO_REJEITADOUpdate the cancellation result; if rejected, the invoice is still valid
NUMERO_INUTILIZACAO_RECUSADAThe 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_DESATIVADOShow a prominent "This till can no longer issue"
LICENCA_EXPIRANDO / PRAZO_TRANSMISSAO_PROXIMOAsk to restore the network soon
CERTIFICADO_EXPIRANDOAsk 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:

java
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 id
System.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 substituir
System.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 itself
System.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 ignored
break;
}
}
/** 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 change
String 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:

  1. Emitir tries online first; on wait timeout or when the platform cannot be reached, it issues an offline contingency invoice on the local machine and returns ContingenciaPendente. If the last connection attempt just failed, it issues offline right away without waiting.
  2. The receipt is printed as usual, with the offline contingency mark and a "pending authorization" notice added automatically, and no protocol number.
  3. 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.
  4. After the upload is authorized you receive the NOTA_AUTORIZADA event; when SEFAZ rejects the upload of an offline invoice you receive NOTA_REJEITADA, and you make a same-number correction with Substituir; see section 5.

When an invoice cannot be issued offline, Emitir throws an exception:

Error codeSituationHow it clears
10029804 / 10029807 / 10029810License expired / offline deadline passed / the oldest invoice waiting for upload passed the upload deadlineClears automatically once the network is back
10029808The device series reached number 999999999Deactivate 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
10029811The state or company does not allow offline issuingOnline issuing only
10029812Invoice with fuelCannot 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 SituacaoScreen 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
OfflineAteAsk to go online soon when the offline duration is about to run out
Avisos is not emptyThe runtime environment needs a technician; log the original text or show it to technical support

7 Pre-launch checklist

  1. The full flow works in the testing environment: pairing, online issuing (Autorizada), offline issuing (ContingenciaPendente), and NOTA_AUTORIZADA received after the network is back.
  2. Resending the same id does not issue extra invoices; after a crash and restart, Consultar gets the result back.
  3. Events are deduplicated by EventoId, and the deduplication records are persisted; NOTA_NEGADA (reissue with a new id) and NOTA_REJEITADA (same-number correction) are handled separately.
  4. 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.
  5. 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.
  6. The POS screen can show the offline status, the number of invoices waiting for upload and the upload deadline.
  7. Certificate expiry and device deactivation are shown prominently.
  8. XmlAutorizado, XmlCancelamento, ExportarXmls, Backup, RestaurarBackup and ExportarPendentes are all called on a background thread, and the UI does not freeze; SincronizarAgora returns immediately and can be called directly.
  9. When the store goes online through a proxy, pairing and issuing have been tested on the real network.
  10. 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 Iniciar has 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.
  11. After the company switches to the production environment, generate new pairing codes in production, pair new devices, and deactivate the test devices.
  12. With primary/secondary mode, you have rehearsed the primary going down (the secondary returns 10029880 and the till moves to the backup machine) and revoking a secondary (it then returns 10029882).

Next steps

Common errors and handling

Error codeSituationHandling
10029801 / 10029802The company is not paired on this machine / several companies are paired but empresaId was not passedPair first; pass empresaId
10029804 / 10029807Offline and the license expired / offline deadline passedRestore the network; renewal is automatic
10029808Device series numbers used up to 999999999Deactivate 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
10029809System clock was set backCorrect the system time
10029810The oldest invoice waiting for upload passed the upload deadlineRestore the network and upload as soon as possible
10029811 / 10029812Offline not allowed, or just restored from a backup and no new license yet / invoice with fuelIssue online only; after a restore, offline issuing resumes automatically after one online sync
10029813 / 10029814Certificate unavailable / expiredCheck the certificate; after renewal call TrocarCertificado
10029816The device has been deactivatedContact the integrator
10029817Request 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
10029780An item line references a tax class, but the platform cannot be reached to expand it; no invoice number was usedResend with the same id once the connection is back; when offline, send impostos on the item lines
10029818The same id was already used for an invoice with different contentUse a new id for a new sale
10029819No document with this id on this machineCheck id and empresaId
10029822The current status does not allow cancellationDo not retry when already cancelled or a cancellation is in progress; for cancellation by substitution, the original must be a regular invoice issued online
10029827The data directory comes from another computer or another Windows userRun as the original user; to replace the computer, deactivate the old device and pair again
10029828The data directory is in use by another processRun only one instance; restoring a backup must happen before Iniciar, so call Encerrar first on an instance already started
10029832 / 10029833Runtime exited unexpectedly / wait timeoutRetry with the same id
10029841Authorized XML not available yetIf 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
10029842The local store is newer than the programThe 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
10029843Cancellation XML not available yetIf 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
10029844Failed to write the fileThe 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
10029845Invalid substitute invoice keyPass the 44-digit key of an offline substitute invoice issued on this machine, with the same CNPJ, not refused by the platform
10029846The backup cannot be restoredWrong passphrase, or the backup file was altered or corrupted: check the passphrase and use an intact backup; the original store was not changed
10029874Invalid parameter, for example the POS software name or version missing at initialization, a wrongly formatted proxy, or print options or export dates out of rangeComplete or fix the parameters according to Detalhes
10029877Runtime not foundCheck the runtime directory in the installer
10029880 / 10029881The secondary cannot reach the primary / the request was sent but no response came back from the primaryRetry later or move to the backup machine; for an unknown result, call Consultar with the same id after the primary recovers
10029882The terminal token of the secondary is invalid or revokedIssue a new terminal token on the primary and update TokenTerminal
10029884A secondary called a primary-only methodRun pairing, certificate change, backup and export on the primary
10029307The device environment differs from the company's current environmentGenerate 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.