Offline NFC-e
Operations and advanced tasks
Embedded SDK operations and advanced topics: cancellation, cancellation by substitution, query and receipt reprint, getting the XML, monthly XML export for the accountant, backup and recovery from a failed computer, closing and restarting, with Java examples.
This page covers the SDK operations the POS software uses day to day after go-live: cancellation, cancellation by substitution, query and receipt reprint, getting and exporting XMLs monthly, backup and recovery from a failed computer, closing and restarting. By the end you can handle cancellations and reconciliation, and keep the offline invoices safe when something goes wrong with the computer. Prerequisites: pairing and issuing already work as in the embedded SDK tutorial; with primary/secondary mode, backup, export and similar methods only work on the primary, see What a secondary can do.
1 Cancellation
Cancelar(id, reason) cancels an invoice, with a reason of 15 to 255 characters. The return value tells how far the cancellation request got:
| Return | Meaning |
|---|---|
Solicitado | Submitted to the platform |
Agendado | The offline invoice has been uploaded but is not authorized yet; the request is sent the moment it is authorized |
EnfileiradoLocal | Queued locally: offline, or the offline / substitute invoice has not been uploaded yet; submitted in the same round right after the upload |
- Final result: arrives in the
CANCELAMENTO_CONCLUIDO/CANCELAMENTO_REJEITADOevents; if rejected, the invoice is still valid, see Receiving results. - Deadline: the cancellation deadline is the same as in the cloud; see Cancel NFC-e. How a cancellation is held before an offline invoice is authorized is in Offline invoices and upload.
- Cannot be cancelled: when the invoice is already cancelled or already has a cancellation in progress,
10029822is returned; do not retry. - Replaced by an offline invoice: when an invoice issued online is to be replaced by an offline invoice issued afterwards on this machine, use cancellation by substitution instead.
The sample code for cancellation is together with query and reprint, see Executar in section 3.
2 Cancellation by substitution
When to use it: a sale already has an invoice issued online (the original invoice), and later, while this machine was offline, an offline contingency invoice was issued for the same sale (the substitute invoice), for example because the consumer asked to reissue with a CPF just when the network was down. The original invoice must be cancelled by substitution, naming the offline invoice that replaces it. For a regular cancellation see section 1.
Call CancelarPorSubstituicao(original id, substitute key, reason), with a reason of 15 to 255 characters. Preconditions:
- Original invoice: a regular invoice issued online on this machine and forwarded by the platform. If the original invoice is an offline invoice, is already cancelled, or already has a cancellation in progress,
10029822is returned. - Substitute invoice: an offline contingency invoice issued afterwards on this machine for the same company; pass its 44-digit access key (the
Chaveof the issuing result). If the key format is wrong, it is not an NFC-e, its CNPJ differs from the original invoice, it equals the original key, or it is not an offline invoice of this machine that the platform has not refused,10029845is returned.
Reading the result: while the substitute invoice has not been uploaded (or the machine is offline), EnfileiradoLocal is returned and the request is queued locally, then submitted automatically after the substitute invoice is uploaded successfully; when the substitute invoice is already uploaded and the machine is online, it is submitted to the platform directly. The final result always arrives as an event: CANCELAMENTO_CONCLUIDO means the original invoice is cancelled, and CANCELAMENTO_REJEITADO means it was rejected and the original invoice is still valid; handle it according to the motivo in the event. After a successful cancellation you can get the cancellation XML as shown in section 3.
The code below matches scenario 05 of the sample projects: it takes the key from the issuing result of the substitute invoice and requests cancellation by substitution of the original invoice.
import com.tffiscal.nfce.sdk.ResultadoEmissao;import com.tffiscal.nfce.sdk.Resultados;import com.tffiscal.nfce.sdk.TfFiscalException;import com.tffiscal.nfce.sdk.TfFiscalNfce;public final class NfceSubstituicao {private NfceSubstituicao() {}/** Replaces the original invoice issued online with the offline substitute invoice issued afterwards on this machine; the final result arrives as CANCELAMENTO_* events. */public static Resultados.Cancelamento cancelarOriginal(TfFiscalNfce nfce, String idOriginal, ResultadoEmissao substituta) {try {Resultados.Cancelamento c = nfce.cancelarPorSubstituicao(idOriginal, substituta.getChave(),"Cliente pediu nova nota com CPF", null);// EnfileiradoLocal: the substitute invoice is not uploaded yet; submitted automatically after a successful uploadSystem.out.println("Cancelamento por substituicao: " + c.getSituacao());return c;} catch (TfFiscalException e) {// 10029822: the original is not a regular invoice issued online; 10029845: invalid substitute key, or not an offline invoice of this machineSystem.out.println("Erro " + e.getCodigo() + " " + e.getTipo() + ": " + e.getMessage());return null;}}}
3 Query, reprint the receipt and get the XML
- Query:
Consultar(id)returns the local record, available even before an offline invoice is uploaded; it includes the original requestPedido,Transmitida,XmlAutorizadoDisponiveland more. - Reprint the receipt: call
Cupomagain with the sameid. - Authorized XML and cancellation XML:
XmlAutorizado(id)gets the authorized XML, andXmlCancelamento(id)gets the cancellation XML after a successful cancellation. After authorization or cancellation the SDK downloads them to this machine automatically and keeps them forRetencaoXmlDiasdays (default 90 days, see Proxy and XML retention days). When they are not on this machine (not downloaded yet, or cleaned up after the retention period), they are fetched online synchronously: a single fetch by the core takes at most 30 seconds, and one SDK call waits at most about 120 seconds.
Do not call XmlAutorizado / XmlCancelamento on the UI thread, or the POS screen freezes while the XML is fetched online. When it cannot be obtained, 10029841 (authorized XML) or 10029843 (cancellation XML) is thrown: if the invoice is not authorized or not successfully cancelled yet, wait for the NOTA_AUTORIZADA or CANCELAMENTO_CONCLUIDO event and try again; if it is authorized and still unavailable, the platform has not archived it yet or cannot be reached, so retry later.
The code below matches scenario 04 of the sample projects: query, reprint, cancel and listing the day's invoices all run locally and are called directly; getting the XML runs on a background thread.
import com.tffiscal.nfce.sdk.FormatoCupom;import com.tffiscal.nfce.sdk.Resultados;import com.tffiscal.nfce.sdk.SituacaoNota;import com.tffiscal.nfce.sdk.TfFiscalNfce;import java.io.IOException;import java.io.UncheckedIOException;import java.nio.file.Files;import java.nio.file.Path;import java.time.LocalDate;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public final class NfceOperacoes {/** Background thread just for getting XMLs: when not local it is fetched online, taking up to about 120 seconds, so it must not block the UI thread. */private static final ExecutorService XML = Executors.newSingleThreadExecutor(r -> {Thread t = new Thread(r, "nfce-xml");t.setDaemon(true);return t;});private NfceOperacoes() {}/** Queries, reprints the receipt, cancels, and lists today's invoices; all of it runs locally and can be called on the UI thread. */public static void executar(TfFiscalNfce nfce, String id) {SituacaoNota situacao = nfce.consultar(id);System.out.println("Consultar: " + situacao.getStatus() + ", transmitida " + situacao.isTransmitida()+ ", XML autorizado disponivel " + situacao.isXmlAutorizadoDisponivel());// Reprint the receipt: fetch it again for the same idbyte[] cupom = nfce.cupom(id, FormatoCupom.ESCPOS_80);System.out.println("Cupom: " + cupom.length + " bytes");// Cancel: the final result arrives through the CANCELAMENTO_CONCLUIDO / CANCELAMENTO_REJEITADO eventsResultados.Cancelamento c = nfce.cancelar(id, "Cliente desistiu da compra", null);System.out.println("Cancelar: " + c.getSituacao() + (c.getMotivo() == null ? "" : " - " + c.getMotivo()));// Today's local invoices (page 1, 50 per page)Resultados.PaginaNotas pagina = nfce.listarNotas(LocalDate.now(), null, 1, null);System.out.println("Notas de hoje: " + pagina.getItens().size() + (pagina.isTemMais() ? " ou mais" : ""));}/** Gets the authorized XML on a background thread and saves a copy; the authorized XML is the legal original, so the POS software can keep its own copy if needed. */public static CompletableFuture<Path> salvarXmlAutorizado(TfFiscalNfce nfce, String id, String chave, Path pasta) {return CompletableFuture.supplyAsync(() -> gravar(pasta.resolve("nfe-" + chave + ".xml"), nfce.xmlAutorizado(id, null)), XML);}/** Gets the cancellation XML on a background thread and saves a copy; call it after CANCELAMENTO_CONCLUIDO. */public static CompletableFuture<Path> salvarXmlCancelamento(TfFiscalNfce nfce, String id, String chave, Path pasta) {return CompletableFuture.supplyAsync(() -> gravar(pasta.resolve(chave + "-can.xml"), nfce.xmlCancelamento(id, null)), XML);}private static Path gravar(Path arquivo, byte[] conteudo) {try {Files.write(arquivo, conteudo);return arquivo;} catch (IOException e) {throw new UncheckedIOException(e);}}}
Call it like this from the UI to get the authorized XML, catching 10029841 and retrying later. The result callback runs on a background thread, so Swing screens switch back to the UI thread with SwingUtilities.invokeLater before updating.
NfceOperacoes.salvarXmlAutorizado(nfce, id, chave, pastaXml).whenComplete((arquivo, erro) -> {if (erro == null) {System.out.println("XML salvo em " + arquivo);} else if (erro.getCause() instanceof TfFiscalException&& ((TfFiscalException) erro.getCause()).getCodigo() == 10029841) {// Not authorized yet, or not local and the platform has not archived it / cannot be reached: retry laterSystem.out.println(erro.getCause().getMessage());}});
4 Monthly XML export for the accountant
When to use it: at the start of each month, hand the previous month's authorized and cancellation XMLs to the accountant. ExportarXmls(start date, end date, directory) exports this machine's invoices in the range by issue date (local date in the company's state); both the start and end dates are included.
- Files: one
{chave}-nfe.xmlper authorized invoice, plus one{chave}-can.xmlfor each cancelled invoice ({chave}is the 44-digit access key); files with the same name already in the directory are overwritten. - Result:
QuantidadeNotasis the number of invoices with at least one file exported,QuantidadeArquivosis the number of files written (a cancelled invoice counts as two files),Arquivoslists every file written, andFalhaslists the invoices in the range whose XML is missing (document id, access key and reason). A missing XML for one invoice does not stop the export. - Retention period: XMLs not on this machine are first fetched online automatically; those still unavailable go into
Falhas, and the reason says whether the local retention period has passed. Keep the export range withinRetencaoXmlDias(see Proxy and XML retention days), otherwise each invoice has to be fetched online and it takes longer; for older invoices use the cloud query. - Without network: if the platform cannot be reached right before the export starts, or for the first time during the export, the remaining invoices with missing XML are no longer fetched online and go straight into
Falhas, instead of waiting for a timeout one by one. To get the files already on this machine while offline, turn on the local-only option: only XMLs already on this machine are exported, with no network access at all, and the missing invoices also go intoFalhas. Use the five-parameter overloadexportarXmls(de, ate, diretorio, true, empresaId). - Duration: invoices may have to be fetched online one by one, and the SDK waits at most 30 minutes, so call it on a background thread and do not wait on the UI thread. If the wait times out (
10029833), the runtime may still be writing files: do not retry right away on the same directory; wait a moment and export again to a new directory. - Common errors: a missing or badly formatted date returns
10029874; a directory that cannot be written returns10029844.
The code below exports the previous month's authorized and cancellation XMLs on a background thread, then lists the result and the invoices with missing XML:
import com.tffiscal.nfce.sdk.Resultados;import com.tffiscal.nfce.sdk.TfFiscalNfce;import java.nio.file.Path;import java.time.LocalDate;import java.util.Map;import java.util.concurrent.CompletableFuture;import java.util.concurrent.Executor;public final class NfceContador {private NfceContador() {}/** Exports the previous month's authorized and cancellation XMLs on a background thread; executor is the POS software's own background thread pool. */public static CompletableFuture<Resultados.ExportacaoXml> exportarMesAnterior(TfFiscalNfce nfce, Path pasta, Executor executor) {LocalDate primeiroDoMes = LocalDate.now().withDayOfMonth(1);LocalDate de = primeiroDoMes.minusMonths(1);LocalDate ate = primeiroDoMes.minusDays(1);return CompletableFuture.supplyAsync(() -> nfce.exportarXmls(de, ate, pasta, null), executor);}/** Lists the result after the export; invoices with missing XML need separate handling. */public static void mostrar(Resultados.ExportacaoXml r) {System.out.println("XML exportados: " + r.getQuantidadeNotas() + " notas, " + r.getQuantidadeArquivos()+ " arquivos, falhas " + r.getFalhas().size());for (Map<String, Object> falha : r.getFalhas()) {System.out.println(" " + falha.get("id") + " " + falha.get("chave") + ": " + falha.get("motivo"));}}}
5 Backup and recovery from a failed computer
Until upload, this machine's data directory holds the only legal originals of the offline invoices. Two things are needed in normal operation: regular encrypted backups, and making sure the staff know which path to take when something goes wrong with the computer.
Regular backups
Backup(target file, passphrase) encrypts the whole local store into one backup file, and issuing can continue at the same time.
- Passphrase: at least 8 characters, otherwise
10029817is returned; if empty,10029874is returned. A key is derived from the passphrase with PBKDF2-SHA256, and the whole store is encrypted with AES-256-GCM; neither the SDK nor the platform stores the passphrase, so if the passphrase is lost, the backup cannot be restored; keep it separate from the backup file. Do not put the passphrase in the program or in command-line arguments; the sample code in this section, like scenario 05 of the sample project, reads it from the environment variableTFFISCAL_BACKUP_SENHA. - File: if the target file already exists,
10029844is returned, so put the time in the file name; a failure while writing does not leave an incomplete file behind. - Result:
Arquivo(file path),Bytes(size),VersaoBanco(local store schema version) andSha256(file digest). - Restore scope: the device keys in the backup are protected by Windows data protection, so it can only be restored on the same computer and under the same Windows user that made the backup; a backup cannot move you to another computer, which must be paired again.
Which path to take when the computer fails
| Situation | Path to take |
|---|---|
| The computer has to be replaced or cannot be repaired, and the offline invoices cannot be uploaded from it in time | Path 1: export a pending upload package and hand it to the platform |
| The local store on the same computer is lost or corrupted, and you have an encrypted backup of this computer | Path 2: restore from the backup on this computer |
Path 1: the computer failed before the upload. When the computer still boots but can no longer go online to upload (for example it has to be replaced right away), use ExportarPendentes(directory) to export every signed offline invoice not yet uploaded and hand it to the platform, which uploads it on your behalf:
-
Call
Iniciaras usual, then callExportarPendentes. It only exports and does not change the local state; these invoices stay in this machine's upload queue. Each call creates a new subdirectory in the target directory named after the export time (UTC), with folders by device and at most 500 invoices per package:text{diretorio}/pendentes-20261111-150000/{dispositivoId}/pacote-001/manifesto.json/pacote-001/{chave}.xml/pacote-002/…{diretorio}is the target directory passed in,{dispositivoId}is the device ID, and{chave}is the 44-digit access key. -
Each manifest
manifesto.jsonrecords the device it belongs to, and every invoice is written into the manifest together with its signed XML, so it can be handed to the platform for import as is; the{chave}.xmlfiles in the same directory are the same signed XML, for manual inspection.Manifestosin the result lists every manifest; when there are no pending invoices,Quantidadeis 0 andManifestosis empty, and there is nothing to hand to the platform. -
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", without unzipping it or splitting it by package or by device. When several companies are paired on this machine, the zip contains several device directories; operations filters by device and submits them in batches. -
Deactivate this old device on the platform, and generate a new pairing code for the new computer and pair it. Do not copy the data directory to the new computer (
10029827).
A directory that cannot be written returns 10029844. If the computer no longer boots, contact the platform.
Path 2: an encrypted backup is available. When the same computer had its disk replaced, or the local store is corrupted or was deleted by mistake, use RestaurarBackup(configuration, backup file, passphrase) to put the store from the backup back in place:
- First save the offline invoices issued after the backup, which are not in it: if the old store still starts, call
Iniciaras usual, export a pending upload package as in path 1 and hand it to the platform, then callEncerrar. RestaurarBackupis a static method, called beforeIniciar: it does not start the engine or go online, and it uses the same configuration asIniciar. If an engine is still running on the data directory (including an instance of this program on whichEncerrarhas not been called),10029828is returned; callEncerrar, then restore.- A wrong passphrase or an altered or corrupted backup file returns
10029846, without telling the two cases apart; a backup from a newer SDK version returns10029842. On failure the original store is left untouched. - On success the original store is saved in the data directory under a file name starting with
nfce.db.antes-restauracao-, andCopiaAnteriorin the result gives its path (empty when there was no store before);VersaoBancois the schema version of the restored local store, and if it is older than the current SDK, it is upgraded automatically at the next startup. - Then call
Iniciaras usual. The numbers and licenses in the backup stay at the moment of the backup, so each company first goes through a realignment: offline issuing is paused (it returns10029811), and online issuing syncs with the platform once before taking a number. Once a new license arrives, the device series numbering skips ahead 50 numbers, one skip shared by online and offline invoices; the skipped numbers are reported to the platform for voiding automatically (the results arrive through the NUMERO_INUTILIZADO event), and then online and offline issuing work as usual. This way, even if invoices issued after the backup were already handed to consumers, no numbers are duplicated. Until the realignment finishes, no invoice can be issued without reaching the platform; go online as soon as possible after the restore, and callSincronizarAgorato start syncing right away.
Call from a background thread
Backup, RestaurarBackup and ExportarPendentes all read and write a lot of files, and the SDK waits at most 30 minutes, so UI programs should call them on a background thread, as in section 3. If the wait times out (10029833), the runtime may still be writing files: do not retry right away on the same file or directory; wait a moment and use a new file name or a new directory.
The code below shows, in order, a regular backup, exporting a pending upload package for path 1, and for path 2 restoring from a backup, then starting and syncing right away:
import com.tffiscal.nfce.sdk.Configuracao;import com.tffiscal.nfce.sdk.Resultados;import com.tffiscal.nfce.sdk.TfFiscalException;import com.tffiscal.nfce.sdk.TfFiscalNfce;import java.nio.file.Path;public final class NfceContingencia {private NfceContingencia() {}/** Reads the backup passphrase from an environment variable, so it is not written into the program or the command line. */public static String senhaBackup() {String senha = System.getenv("TFFISCAL_BACKUP_SENHA");if (senha == null || senha.isEmpty()) {throw new IllegalStateException("Defina TFFISCAL_BACKUP_SENHA (minimo 8 caracteres)");}return senha;}/** Regular encrypted backup of the local store; an existing target file is refused (10029844), so the file name includes the time. Call it on a background thread. */public static Resultados.Backup backup(TfFiscalNfce nfce, Path pasta) {Resultados.Backup bak = nfce.backup(pasta.resolve("caixa-" + System.currentTimeMillis() + ".bak"), senhaBackup());System.out.println("Backup: " + bak.getArquivo() + " (" + bak.getBytes() + " bytes, sha256 " + bak.getSha256() + ")");return bak;}/** Path 1: exports the signed offline invoices not yet uploaded; zip the whole pendentes-… directory of this export and hand it to the platform. Call it on a background thread. */public static void exportarPendentes(TfFiscalNfce nfce, Path pasta) {Resultados.ExportacaoPendentes pend = nfce.exportarPendentes(pasta);System.out.println("Pendentes exportados: " + pend.getQuantidade());for (String manifesto : pend.getManifestos()) {System.out.println(" manifesto " + manifesto);}}/** Path 2: restores from an encrypted backup before iniciar, then starts and syncs right away. Call it on a background thread. */public static TfFiscalNfce restaurarEIniciar(Configuracao config, Path arquivoBackup) {try {Resultados.Restauracao r = TfFiscalNfce.restaurarBackup(config, arquivoBackup, senhaBackup());System.out.println("Backup restaurado: versao do banco " + r.getVersaoBanco() + ", copia anterior " + r.getCopiaAnterior());} catch (TfFiscalException e) {if (e.getCodigo() == 10029846) {// Wrong passphrase or corrupted backup file; the original store was not changedSystem.out.println("Senha incorreta ou backup corrompido");}throw e;}TfFiscalNfce nfce = TfFiscalNfce.iniciar(config);// Offline issuing is paused until a new license arrives, so sync one round right awaynfce.sincronizarAgora();return nfce;}}
6 Closing and restarting
- Closing: call
Encerrarbefore exiting (equivalent toclose). It waits for in-progress issuing to finish before closing, up to about 15 seconds; do not kill the process. Nothing is uploaded while closing. - Restarting: call
Iniciaras usual; no new pairing is needed. After startup the core syncs once immediately; if invoices are still waiting for upload or events are unacknowledged, you receivePENDENCIAS_NA_INICIALIZACAO, and the unacknowledged events are then redelivered. - After a crash: every invoice already issued is in the data directory. If you are unsure whether a sale was issued, call
Consultaror resendEmitirwith the sameid; it does not issue twice. - Runtime exits unexpectedly: the SDK restarts it automatically (
RUNTIME_FALHOU,RUNTIME_REINICIADOevents); calls in progress fail with10029832; retry with the sameid. - Upgrading and downgrading: when upgrading the POS software, upgrade the SDK and the runtime with it; the data directory is kept as is. If an older version is installed back, the local store is newer than the program and startup is refused (
10029842); upgrade back to at least the version used last time, and do not delete the data directory.
