TF Fiscal
Documentation

Offline NFC-e

SDK reference

Offline NFC-e embedded SDK reference: configuration, signatures and errors of each method, data types, events and error codes.

Reference for the embedded SDK, organized by configuration, methods, data types, events, issuance request and error codes; each section can be looked up on its own. Method names are in Portuguese; headings and text on this page write them with an uppercase first letter (for example Emitir), while Java code uses a lowercase first letter (for example emitir). If this is your first integration, start with the Embedded SDK tutorial.

Configuration

The configuration is passed once when calling Iniciar and cannot be changed after initialization; to change it, call Encerrar and then Iniciar again. The configuration is set with chained Configuracao.builder() ... .build() calls.

The last five settings in the table (primary/secondary role, primary port, allowed networks, primary address, terminal token) are used only in a primary/secondary deployment, where several tills in one store share one device series. For the roles, the deployment steps and the methods available on a secondary, see Multiple tills (primary and secondary mode).

SettingJavaRequiredDescription
Data directorydiretorioDados(Path)YesLocal store directory. One per till and open by only one process at a time; until upload, the signed files of offline invoices exist only here, so do not delete it, see Embedded SDK
Runtime directorydiretorioRuntime(Path)Required in subprocess modeRuntime installation directory. It must contain tffiscal-nfce.exe; when not found, 10029877 is returned
POS software namenomeAplicativo(String)YesPOS software name. The platform identifies the POS software by it, so the same software uses the same name on every till; returns 10029874 when missing
POS versionversaoAplicativo(String)YesPOS version number. The platform uses it for minimum and blocked version control, for example 3.2.1
Error message languageidioma(String)NoLanguage of exception messages. pt-BR (default), en, zh-CN, es; only the language part counts, so en-US is English, and other languages fall back to Portuguese. Errors returned by the platform and passed on by the SDK (such as a tax class not found or not matching the tax regime) use this language too
Call timeouttempoLimitePadraoMs(long)NoMaximum wait for a single call. Default 30 seconds; on timeout 10029833 is returned and the late result is discarded. Pairing and fetching the authorization or cancellation XML wait at least 120 seconds; ExportarXmls, ExportarPendentes, Backup and RestaurarBackup wait at least 30 minutes; a longer value configured here takes precedence
Startup timeouttempoLimiteInicioMs(long)NoMaximum wait for the runtime to be ready. Default 5 seconds; on timeout 10029831 is returned
Automatic restartreiniciarAutomaticamente(boolean)NoRestart after an unexpected runtime exit. On by default, retrying at intervals of 1, 2, 4 seconds up to 60 seconds
Log forwardingencaminharLog(boolean)NoForward core logs to the POS. Off by default; when on, they are written to java.util.logging
Outbound proxyproxy(String)NoManual proxy address. In the form host:porta; not set by default, connecting directly without a proxy; a wrong format returns 10029874. See Outbound proxy
Proxy authenticationproxyAutenticacao(String, String)NoProxy user name and password. Usable with both the manual and the system proxy; the password is only handed to the runtime in memory and is not written to disk or to the logs; setting only the authentication, with neither a proxy address nor the system proxy, returns 10029874
Use system proxyusarProxyDoSistema(boolean)NoSystem proxy switch. Off by default; when on, the Windows system proxy settings are used and take precedence over Proxy; PAC auto-config scripts are not supported
XML retention daysretencaoXmlDias(int)NoLocal XML retention days. How many days authorized XMLs and cancellation XMLs are kept on this machine, from 1 to 3650; 90 days when not set or set to 0; out of range returns 10029874. XMLs cleaned up after the retention period are fetched from the platform automatically when read; for the monthly XML export, keep the export range within the retention period
Run modemodo(Modo)NoJava run mode. SUBPROCESSO (default) or EM_PROCESSO, see below
Event listeneraoReceberEvento(Consumer<EventoNfce>)NoEvent handler attached at startup. Events queued before startup are not missed, see Events
Runtime commandcomandoRuntime(String)NoAdvanced setting. Full path of the runtime executable, only for development and testing
Runtime argumentsargumentosRuntime(List<String>)NoAdvanced setting. Runtime startup arguments, default --stdio; only for development and testing
Stand-in enginemotorSimulado(boolean)NoStand-in engine for tests. Only for samples and automated tests, it does not produce valid invoices; never turn it on in production
Primary/secondary rolemodoOperacao(ModoOperacao)NoRole of this till when several tills share one series. Standalone (default), primary or secondary, with the values INDEPENDENTE / PRINCIPAL / SECUNDARIO; see Multiple tills (primary and secondary mode)
Primary portportaPrincipal(int)NoLocal network port of the primary. Primary only; unset or 0 means 8786; if the port is taken, Iniciar returns 10029887
Allowed networksredesPermitidas(List<String>)NoSecondary networks accepted by the primary. Primary only; CIDR notation, for example 192.168.0.0/24; unset means the /24 network of the primary; only private local network addresses are accepted; a bad format returns 10029874
Primary addressenderecoPrincipal(String)Required on a secondaryAddress of the primary the secondary connects to. host:porta form, for example 192.168.0.10:8786; must be a private local network address, otherwise 10029883
Terminal tokentokenTerminal(String)Required on a secondaryTerminal token of the secondary. Issued by CriarTerminal on the primary, starts with tfl_; only handed to the runtime in memory, never written to disk or logs; if invalid or revoked, Iniciar returns 10029882

Java run modes

ModoMeaningRequirements
SUBPROCESSODefault. The SDK starts the runtime as a child processHost on Java 8 or later; ship the runtime and set diretorioRuntime
EM_PROCESSOThe core runs directly in the POS JVM, with no child processHost on Java 21 or later, with the runtime and core jars on the classpath; below Java 21 startup returns 10029835. With proxy authentication, the JVM startup parameters must include -Djdk.http.auth.tunneling.disabledSchemes=, see Outbound proxy

Outbound proxy

The core decides whether to use a proxy to reach the platform according to the table below:

SettingProxy used
UsarProxyDoSistema onSystem proxy. First reads the Windows WinHTTP machine proxy setting, and if there is none, the Internet Options proxy setting of the current Windows user; when Proxy is also set, the system proxy wins
Only Proxy setManual proxy. Uses the address given in Proxy
Neither setDirect connection
  • PAC auto-config scripts are not supported: when Windows only has an auto-config script and no fixed proxy address, the core writes a warning to the log and connects directly. On such networks set Proxy manually instead.
  • Proxy authentication: proxyAutenticacao applies to both the manual and the system proxy.
  • Startup parameter in Java in-process mode: Basic authentication on the proxy over HTTPS tunnels depends on the JVM system property jdk.http.auth.tunneling.disabledSchemes, which the JVM reads only once, the first time its built-in HTTP client is used; changing it later has no effect. In Java in-process mode (EM_PROCESSO) with proxy authentication, the host must add -Djdk.http.auth.tunneling.disabledSchemes= to the JVM startup parameters (nothing after the equals sign). When the core loads, it also clears the property as early as possible if the host has not set it, and checks whether that took effect: if the host explicitly disabled Basic, the host already used the JVM's built-in HTTP client, or this cannot be determined, Avisos in Situacao reports that proxy authentication may not work, and a warning is written to the log. In Java subprocess mode the runtime child process sets it at startup, and the host does not need to do anything.

Below is a manual proxy with authentication.

java
Configuracao configuracao = Configuracao.builder()
// Other settings as above
.proxy("10.0.0.5:3128")
.proxyAutenticacao("caixa01", senhaProxy)
.build();

Configuration example

A common base configuration; settings not listed keep their defaults.

java
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")
.tempoLimitePadraoMs(30_000)
.build();

Methods

Each method follows the same order: purpose and whether it needs the network, signature, parameters, return, possible errors, examples. Besides the errors listed for each method, any method can return the common errors, see the beginning of Error codes.

Iniciar

Starts the SDK: launches the runtime (subprocess mode) or loads the core (Java in-process mode), opens the data directory, resumes anything left unfinished last time, and begins the background heartbeat, uploads and result fetching. Every other method must be called after Iniciar succeeds; one data directory can have only one instance at a time.

Network: Not needed. It starts even without a network and begins syncing as soon as there is one.

Signature

java
public static TfFiscalNfce iniciar(Configuracao config);

Parameters

ParameterJavaRequiredDescription
ConfigurationconfigYesInitialization settings. Fields in Configuration

Return

A ready SDK instance TfFiscalNfce. Call Encerrar when done; you can also close it automatically with try-with-resources.

Possible errors

CodeCaseAction
10029877Runtime not foundCheck that the runtime directory and tffiscal-nfce.exe ship with the installer
10029831Runtime failed to start or was not ready within the startup timeoutCheck the logs; on very slow computers raise the startup timeout
10029830SDK and runtime versions are incompatibleShip the runtime and the SDK in the same version
10029835Java in-process mode on a host below Java 21Use subprocess mode, or upgrade Java
10029828The data directory is already open by another processOpen only one instance per directory; check for leftover processes
10029827The local key cannot be unlocked: the data directory comes from another computer or another Windows userRun with the original Windows user; to change computers, deactivate the old device and pair again
10029829Local store inconsistentDo not delete the data directory, contact the platform
10029842The local store is newer than the current core: the data directory was used by a newer SDK version, so startup is refusedUpgrade the SDK and the runtime to at least the version used last time; never delete the data directory, it holds the originals of offline invoices not yet uploaded
10029840Invalid configurationFix the setting named in Message
10029874Wrong setting value: POS software name or version missing, wrongly formatted proxy address, only proxy authentication set, or XML retention days out of rangeFix the setting according to Detalhes.campo
10029882The terminal token of the secondary is invalid or revokedIssue a new terminal token on the primary and update TokenTerminal
10029883The primary address of the secondary is badly formatted or not a private local network addressFix EnderecoPrincipal
10029887The local network port of the primary cannot be openedChange PortaPrincipal or free the port

Can also return the common errors.

Examples

java
try (TfFiscalNfce nfce = TfFiscalNfce.iniciar(configuracao)) {
System.out.println("ativado=" + nfce.isAtivado());
}

Ativado / Empresas

  • Ativado: whether this data directory has at least one paired company. The POS uses it at startup to decide whether to enter the pairing flow.
  • Empresas: list of paired companies. When one data directory pairs several companies (several CNPJs), use it to find the empresaId of each one.

Both query the core every time, with no caching: after the platform deactivates the device, the status shows it in the Situacao field.

Network: Not needed.

Signature

java
public boolean isAtivado();
public List<Resultados.EmpresaAtivada> getEmpresas();

Parameters

None.

Return

Ativado returns a boolean. Empresas returns the list of paired companies; element fields are in Data types: paired company.

Possible errors

Only the common errors.

Examples

java
if (!nfce.isAtivado()) {
nfce.ativar(codigoAtivacao, Certificado.doRepositorio(thumbprint, false));
}
for (Resultados.EmpresaAtivada empresa : nfce.getEmpresas()) {
System.out.println(empresa.getEmpresaId() + " " + empresa.getCnpj() + " " + empresa.getSituacao());
}

InspecionarCodigoAtivacao

Checks locally the format, platform signature, validity and target platform address of a pairing code, and reads the company, environment and allowed form. It does not go online and does not consume the code. Useful before pairing, to show the cashier "this is a testing code, valid for 72 hours", or to stop malformed, expired or wrong-form codes early.

Network: Not needed. A valid code does not guarantee a successful pairing: used or revoked codes and similar cases can only be decided by the platform during Ativar.

Signature

java
public Resultados.CodigoAtivacao inspecionarCodigoAtivacao(String codigo);

Parameters

ParameterJavaRequiredDescription
Pairing codecodigoYesFull pairing code. Starts with TFA1.; the content of a .tfa file is the full code, and leading and trailing whitespace is removed

Return

Pairing code info; fields in Data types: pairing code info.

Possible errors

CodeCaseAction
10029825Wrong pairing code format, signature or validityConfirm it was copied completely; if expired, ask the integrator for a new one
10029826The pairing code points to an untrusted platform addressThe code was not issued by this platform, or the runtime version does not match the environment; contact the integrator

Can also return the common errors.

Examples

java
Resultados.CodigoAtivacao info = nfce.inspecionarCodigoAtivacao(codigoAtivacao);
System.out.println("ambiente " + info.getAmbiente() + " expira " + info.getExpiraEm());

Ativar

Pairs this machine as a device using the device pairing code generated by the integrator and the A1 certificate of the company. During pairing the core generates the device keys, binds the certificate and registers with the platform; on success it gets the device series and the first license, and the platform sends nfce.device.activated (see How you get the results). Each company is paired only once per data directory; the same data directory can also pair other companies.

Network: Required. If the platform cannot be reached, 10029824 is returned and the pairing code is not consumed.

Signature

java
public Resultados.Ativacao ativar(String codigoAtivacao, Certificado certificado);

Parameters

ParameterJavaRequiredDescription
Pairing codecodigoAtivacaoYesFull pairing code. Starts with TFA1., single use, valid for 72 hours
CertificatecertificadoYesA1 certificate of the company. How to pass it is in Data types: certificate source; the certificate CNPJ must match the store company

Return

Pairing result; fields in Data types: pairing result.

Possible errors

CodeCaseAction
10029825 / 10029826Local pairing code check failed / untrusted target platformSee InspecionarCodigoAtivacao
10029824Platform unreachableRetry once online
10029837The company is already paired in this data directoryNo need to pair again
10029813 / 10029814Certificate not found, without private key, CNPJ mismatch / expiredUse a valid A1 certificate of the company
10029839Paired on the platform but local saving failedCall Ativar again with the same pairing code
10029806The license does not belong to this devicePair again; if it still fails, contact the platform
10029874Invalid certificate parameter: thumbprint not 40 hexadecimal characters, or empty PFXFix the certificate parameter
10029205 to 10029208Returned by the platform: pairing code invalid / expired / used / revokedGenerate a new pairing code
10029209Returned by the platform: the code does not allow the SDK formGenerate a new one with Sdk or Qualquer
10029210 / 10029211Returned by the platform: POS software name missing / POS version blocked or too oldSet the POS software name; upgrade the POS
10029213 / 10029214Returned by the platform: certificate CNPJ differs from the company / certificate expiredUse a valid certificate of the company
10029219Returned by the platform: pairing code environment differs from the company current environmentGenerate a new code in the company current environment
10029221 to 10029225Returned by the platform: the device series set in the code is no longer availableThe integrator generates a new code with another series or start number

Can also return the common errors.

Examples

java
Resultados.Ativacao a = nfce.ativar(codigoAtivacao, Certificado.doRepositorio(thumbprint, false));
System.out.println("empresa " + a.getEmpresaId() + " dispositivo " + a.getDispositivoId() + " serie " + a.getSerieOffline());

Emitir

Issues an NFC-e. The core takes the next number of the device series, signs the invoice and first hands it to the platform for online authorization; when the platform cannot be reached, times out or the result is unclear, it signs offline on this machine and returns a printable offline invoice on the spot. The request body is exactly the same as the cloud issuance endpoint, see Issuance request.

Processing order:

  1. Local lookup by id: if the same id was already issued, the original invoice is returned with no new number; different content returns 10029818.
  2. When an item line references a tax class (classeImposto), the request is first sent to the platform, which expands it into complete impostos: this needs a connection, and when the platform cannot be reached it returns 10029780 without using an invoice number; a rejected tax class (not found, regime mismatch and so on) returns the platform's error code and message unchanged.
  3. Normalization and validation, with the same rules as the cloud; failure returns 10029817, with Detalhes listing the reason per field.
  4. Takes a number from the device series, signs and submits online, with the same result as cloud synchronous issuing; a business error from the platform is returned as is, does not fall back to offline, and the number goes to the next invoice. The only exception is the platform reporting the number as taken (10029424): the core drops that number, syncs once with the platform to refresh the confirmed number and retries only once; a second conflict is returned as is, so it never keeps hitting number after number and blocks the till.
  5. When online fails or times out, the license, upload deadline, offline switch and other conditions are checked and the invoice is signed offline, returning ContingenciaPendente. When the result was unclear, the original number is not reused: the offline invoice gets the next number and the platform settles the original one, cancelling it by substitution if it was authorized or voiding it otherwise (see Numbers the platform handles for you); if offline signing is not possible at that moment, it returns AguardandoAutorizacao and later resubmits the original number unchanged. If the last network attempt has just failed, step 4 is skipped and the invoice is signed offline directly.

Issuances of the same company run in order inside the core, keeping the device series numbers sequential across online and offline invoices; different companies can run in parallel.

Network: Optional. Issues online when connected, signs offline when not.

Signature

java
public ResultadoEmissao emitir(String pedidoJson);
public ResultadoEmissao emitir(String pedidoJson, String empresaId);

Parameters

ParameterJavaRequiredDescription
Issuance requestpedidoJsonYesIssuance request. JSON text; same structure as the cloud issuance endpoint, no need to send modoResposta. Item lines can send impostos or reference a tax class with classeImposto (needs a connection)
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired; with several and none given, 10029802 is returned

Return

Issuing result; fields and statuses in Data types: issuing result.

StatusWhat the POS does
AutorizadaPrint the receipt
ContingenciaPendenteSigned offline: print the receipt with Cupom and hand it to the consumer; upload happens automatically
AguardandoAutorizacaoAccepted online but SEFAZ has not answered, and offline signing was not possible at that moment: do not print yet, wait for the NOTA_AUTORIZADA event or query later; if SEFAZ denies it afterwards you receive NOTA_NEGADA
NegadaOnline issuing denied by SEFAZ: no same-number correction; correct the sale data according to the SEFAZ result code and result message and reissue with a new id

Possible errors

CodeCaseAction
10029817Request validation failedFix as listed in Detalhes
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; retry with the original request
10029801 / 10029802Company not paired / empresaId missing with several companiesPair first; send empresaId
10029816Device deactivatedContact the integrator
10029805 / 10029806Invalid license signature / license does not belong to this deviceContact the platform; pair again if needed
10029874The request is not a JSON objectSend JSON object text
10029803 / 10029804 / 10029807Offline with no license / license expired / offline deadline passedRestore the network; it recovers after renewal
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
10029809The system clock was moved backFix the system time
10029810The oldest pending invoice is past the upload deadlineRestore the network and upload
10029811 / 10029812The company or state does not allow offline / invoice with fuelIssue online only
10029813 / 10029814Certificate unavailable / expiredCheck the certificate; use TrocarCertificado if needed
10029815Local configuration or tax data missingSync once while online
10029823Device series numbers used upDeactivate 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
10029307Returned by the platform: device environment differs from the company current environmentPair a new device in the company current environment
10029424Returned by the platform: number already taken. The core already dropped the number and retried once; a repeated conflict means the local database and the platform records disagreeDo not retry with another number; export the logs and contact the platform
10029426Returned by the platform: the same id already has a non-rejected invoice on the platform, for example issued by the cloud API or another deviceCheck the original invoice with Query NFC-e; use a new id for a new sale
Other platform codesBusiness errors returned by the platform during online issuing, such as 10022004Handle as described in Issue NFC-e

Can also return the common errors.

Examples

java
ResultadoEmissao r = nfce.emitir(pedidoJson);
if ("Autorizada".equals(r.getStatus()) || "ContingenciaPendente".equals(r.getStatus())) {
impressora.enviar(nfce.cupom(r.getId(), FormatoCupom.ESCPOS_80));
}

Previsualizar

Checks an issuance request with the same normalization, validation and tax rules as Emitir, and returns whether it passes, the per-field error messages, the invoice total and the tax total. It takes no number, does not sign, does not store anything and does not go online. Useful for validating while the cashier types: a failed validation does not throw, it returns Valido = false.

Network: Not needed.

Signature

java
public Resultados.PreVisualizacao previsualizar(String pedidoJson, String empresaId);

Parameters

ParameterJavaRequiredDescription
Issuance requestpedidoJsonYesRequest to validate. Same structure as Emitir; id can be left empty for now
Company identifierempresaIdRequired with several companiesIssuing company. In Java pass null when only one company is paired

Return

Preview result; fields in Data types: preview result. Erros is already translated into the configured error message language and can be shown to the cashier as is.

Possible errors

A failed validation does not throw. Besides the common errors, only company-related errors: 10029801 (company not paired), 10029802 (empresaId missing with several companies), 10029815 (local tax data missing, sync once while online).

Can also return the common errors.

Examples

java
Resultados.PreVisualizacao p = nfce.previsualizar(pedidoJson, null);
if (!p.isValido()) {
p.getErros().forEach(System.out::println);
}

Call it after about 300 milliseconds of typing pause rather than on every keystroke.

Consultar

Queries the current status of a local invoice by the id used at issuance: whether it is authorized, uploaded, has a pending cancellation, how many corrections it had, whether the authorized XML is downloaded, and the original issuance request. Both online and offline invoices are stored on this machine, so offline invoices can be queried before upload too. After the POS crashes and restarts, use it to get back the invoices issued before the crash.

Network: Not needed. It returns the local record; upload and authorization results are updated by the background sync. To get the latest result quickly, call SincronizarAgora first.

Signature

java
public SituacaoNota consultar(String id);
public SituacaoNota consultar(String id, String empresaId);

Parameters

ParameterJavaRequiredDescription
Invoice identifieridYesThe id in the issuance request
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired

Return

Query status; fields in Data types: query status.

Possible errors

CodeCaseAction
10029819No such invoice on this machineCheck id and empresaId; if the invoice was not issued on this machine, use the cloud query
10029801 / 10029802Company not paired / empresaId missing with several companiesPair first; send empresaId

Can also return the common errors.

Examples

java
SituacaoNota s = nfce.consultar("PDV01-000131");
System.out.println(s.getStatus() + " transmitida=" + s.isTransmitida() + " protocolo=" + s.getProtocolo());

ListarNotas

Lists local invoices page by page (online and offline ones), newest issue time first, 50 per page. Useful for a "today's invoices" screen or for checking pending uploads at shift change. To avoid counting the whole table, the result gives no total, only whether there is a next page.

Network: Not needed.

Signature

java
public Resultados.PaginaNotas listarNotas(LocalDate data, String status, int pagina, String empresaId);

Parameters

ParameterJavaRequiredDescription
Issue datedataNoFilter by issue day. The day follows the time zone of the company's state; when omitted there is no date limit, so always send it for a "today" list
StatusstatusNoFilter by status. Values in Data types: invoice status; when omitted there is no limit
PagepaginaNoPage number. Starts at 1, default 1
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired; in Java pass null

Return

Invoice page; fields in Data types: invoice page. Paginate the screen with "previous / next" only, and disable next when TemMais is false.

Possible errors

CodeCaseAction
10029874Date not in yyyy-mm-dd, wrong status value, or page below 1Pass values from the table
10029801 / 10029802Company not paired / empresaId missing with several companiesPair first; send empresaId

Can also return the common errors.

Examples

java
Resultados.PaginaNotas pagina = nfce.listarNotas(LocalDate.now(), "ContingenciaPendente", 1, null);
pagina.getItens().forEach(n -> System.out.println(n.getId() + " " + n.getNumero()));

Cancelar

Cancels an NFC-e already issued. Depending on the invoice status and the network, it goes one of three ways:

CaseOutcome SituacaoAfterwards
Invoice authorized and onlineSolicitadoSent to the platform; the result arrives as the CANCELAMENTO_CONCLUIDO or CANCELAMENTO_REJEITADO event
Offline invoice uploaded but not yet authorizedAgendadoThe platform holds the cancellation and submits it automatically the moment the invoice is authorized, with no need for the POS to be running
Currently offline, or offline invoice not uploaded yetEnfileiradoLocalQueued locally; submitted in the same round right after the upload; motivo gives the cause

The cancellation deadline is the same as in the cloud, see Cancel NFC-e. For how to use it in the checkout flow, see Operations and advanced tasks: Cancellation.

Network: Optional. Queued locally when offline.

Signature

java
public Resultados.Cancelamento cancelar(String id, String justificativa, String empresaId);

Parameters

ParameterJavaRequiredDescription
Invoice identifieridYesThe id in the issuance request
Cancellation reasonjustificativaYesReason for cancelling. 15 to 255 characters
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired; in Java pass null

Return

Cancellation acceptance; fields in Data types: cancellation result. Acceptance does not mean it is cancelled; the final result comes from the events or the Status of Consultar.

Possible errors

CodeCaseAction
10029822The current status does not allow cancellation: already cancelled, a cancellation is already pending, or not in an authorized or awaiting-authorization status; also when the local status is not synchronized yet and the platform refuses the cancellation (for example, the invoice was already rejected), with the platform reason in detalhesDo not retry; check the status with Consultar
10029819No such invoice on this machineCheck id
10029817Reason not between 15 and 255 charactersFix the reason
Other platform codesErrors returned by the platform when submitting online, such as the cancellation deadline passed 10022007Handle as in Cancel NFC-e

Can also return the common errors.

Examples

java
Resultados.Cancelamento c = nfce.cancelar("PDV01-000131", "Cliente desistiu da compra no caixa", null);
System.out.println(c.getSituacao());

CancelarPorSubstituicao

Cancellation by substitution: when an invoice issued online is replaced by an offline contingency invoice issued afterwards on this machine (the same sale issued again), use it to cancel the original invoice, stating the access key of the substitute invoice in the cancellation.

Preconditions:

InvoiceMust beOtherwise
Original invoiceA regular invoice issued online through the platform: not an offline invoice, not cancelled, and with no pending cancellation10029822
Substitute invoiceAn offline invoice issued by this machine for this company, not refused by the platform; its access key has 44 digits, model 65, a valid check digit, the same CNPJ as the original invoice, and is not equal to the original key10029845

While the substitute invoice has not been uploaded, EnfileiradoLocal is returned: the cancellation is queued locally and only submitted after the substitute invoice is uploaded successfully. The final result arrives as the CANCELAMENTO_CONCLUIDO or CANCELAMENTO_REJEITADO event. The cancellation deadline is the same as in the cloud, see Cancel NFC-e. For the complete reissue and cancellation by substitution flow, see Operations and advanced tasks: Cancellation by substitution.

Network: Optional. When offline, or while the substitute invoice has not been uploaded, it is queued locally and submitted automatically once the conditions are met.

Signature

java
public Resultados.Cancelamento cancelarPorSubstituicao(String id, String chaveSubstituta, String justificativa,
String empresaId);

Parameters

ParameterJavaRequiredDescription
Invoice identifieridYesThe id of the original invoice being replaced
Substitute keychaveSubstitutaYesAccess key of the substitute invoice. 44 digits, taken from Chave in the issuing result of the substitute invoice
Cancellation reasonjustificativaYesReason for cancelling. 15 to 255 characters
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired; in Java pass null

Return

Cancellation acceptance; fields in Data types: cancellation result. Acceptance does not mean it is cancelled; the final result comes from the events or the Status of Consultar.

Possible errors

CodeCaseAction
10029822The original is not a regular invoice issued online: it is an offline invoice, already cancelled, or already has a pending cancellationDo not retry; for offline invoices use Cancelar
10029845Invalid substitute key, or not an offline invoice of this machine and this company that was not refusedPass the 44-digit access key of the offline invoice this machine issued for the same sale
10029819The original invoice is not on this machineCheck id
10029817Reason not between 15 and 255 charactersFix the reason
Other platform codesErrors returned by the platform when submitting, such as the cancellation deadline passed 10022007Handle as in Cancel NFC-e

Can also return the common errors.

Examples

java
ResultadoEmissao substituta = nfce.emitir(pedidoRefeitoJson);
Resultados.Cancelamento c = nfce.cancelarPorSubstituicao("PDV01-000131", substituta.getChave(),
"Venda refeita em contingencia offline", null);
System.out.println(c.getSituacao());

Substituir

When an uploaded offline invoice is rejected by SEFAZ (status Rejeitada, event NOTA_REJEITADA), it has already been handed to the consumer, so it cannot be replaced by a new invoice; it can only be corrected under the same number and sent again. Substituir rebuilds and re-signs the invoice from the corrected request, keeping number, series, access key and issue time, and puts it back in the upload queue; the core uploads it at the next sync. For the upload rules and what happens after a rejection, see Offline invoices and upload.

Only content that does not affect amounts and taxes can change, for example the item NCM, CFOP or the consumer document; any change to the invoice total or to a line tax is refused.

Network: Not needed. The correction happens on this machine and the upload runs in the background.

Signature

java
public ResultadoEmissao substituir(String id, String pedidoJsonCorrigido, String empresaId);

Parameters

ParameterJavaRequiredDescription
Invoice identifieridYesThe id of the rejected invoice
Corrected requestpedidoJsonCorrigidoYesThe complete issuance request. Edit it from the original request, available in Pedido from Consultar; id stays the same as the original
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired; in Java pass null

Return

Issuing result, same structure as Emitir, with Status back to ContingenciaPendente. When the new upload is authorized, NOTA_AUTORIZADA arrives with Dados.aposCorrecao = true.

Possible errors

CodeCaseAction
10029820The current status does not allow correction: only Rejeitada can be correctedCheck the status with Consultar
10029821The correction changed amounts or taxesChange only non-amount content
10029817Request validation failedFix as listed in Detalhes
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
10029819No such invoice on this machineCheck id
10029815Local configuration or tax data missingSync once while online

Can also return the common errors.

Examples

java
SituacaoNota original = nfce.consultar("PDV01-000131");
ResultadoEmissao r = nfce.substituir("PDV01-000131", corrigirNcm(original.getPedido()), null);
System.out.println(r.getStatus());

Cupom

Builds the receipt of a local invoice. The receipt of an offline invoice automatically carries the offline contingency mark and the "pending authorization" notice and has no protocol number; the number of copies is set by the platform. ESC/POS bytes can go straight to a thermal printer, and the PDF can be printed through the Windows printer driver. Works while offline too.

To adjust columns per line, code page, QR code printing mode, paper cut or number of copies, use the overload with print options; the options are under "Print options" below.

Network: Not needed.

Signature

java
public byte[] cupom(String id, FormatoCupom formato);
public byte[] cupom(String id, FormatoCupom formato, String empresaId);
public byte[] cupom(String id, FormatoCupom formato, OpcoesCupom opcoes, String empresaId);

Parameters

ParameterJavaRequiredDescription
Invoice identifieridYesThe id in the issuance request
FormatformatoYesReceipt format. Values in the table below
Print optionsopcoes (OpcoesCupom)NoReceipt print options. Only in the overload with print options, can be null; fields under "Print options" below
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired
Java FormatoCupomContent
ESCPOS_80ESC/POS bytes for 80mm thermal printers
ESCPOS_58ESC/POS bytes for 58mm thermal printers
TEXTOUTF-8 plain text
HTMLUTF-8 HTML, for screen preview or browser printing
PDF_8080mm-wide PDF, one page per copy. Printed through the Windows printer driver, for printers that cannot take ESC/POS directly; uses the standard PDF monospaced font without embedding fonts, and Portuguese accents display correctly; the QR code is a black-and-white image

Print options

The OpcoesCupom class, with chained setters. Options not set use their defaults; out-of-range values return 10029874, with Detalhes.campo set to opcoes.

ParameterJavaRequiredDescription
Columns per linecolunas(int)NoCharacters per line. 48, 42, 32; when not set or set to 0 it follows the format, 48 for 80mm and 32 for 58mm
Code pagepaginaCodigo(String)NoPrinter code page. CP1252 (default, Western European), CP860 (Portuguese), CP850 (Western European multilingual), CP437 (US English); characters missing from the code page are printed without accents
QR code modemodoQrCode(OpcoesCupom.ModoQrCode)NoHow the QR code is printed. NATIVO (default) uses the printer's own QR code command; IMAGEM prints the QR code as a bitmap, for printers without QR code commands
QR module sizetamanhoModuloQr(int)NoDots per QR code module. 1 to 16; 4 when not set or set to 0
Paper cutcortar(boolean)NoPaper cut switch. Default true, cutting after printing
Copiesvias(int)NoNumber of copies. 1 to 9; when not set or set to 0 it follows the platform setting

Return

Receipt bytes. For PDF_80, the content of the PDF file.

Possible errors

CodeCaseAction
10029819No such invoice on this machineCheck id
10029874Wrong format value, or print options out of rangeUse a value from the tables above

Can also return the common errors.

Examples

java
byte[] cupom = nfce.cupom("PDV01-000131", FormatoCupom.ESCPOS_80);
Files.write(Paths.get("PDV01-000131.escpos"), cupom);
// 80mm PDF, printed through the Windows printer driver
byte[] pdf = nfce.cupom("PDV01-000131", FormatoCupom.PDF_80, new OpcoesCupom().vias(1), null);
Files.write(Paths.get("PDV01-000131.pdf"), pdf);

QrCodePng

Generates the QR code of a local invoice as a PNG image (black and white, with a quiet zone). Use it when laying out your own receipt or showing the QR code on screen; the content is the same as QrCode in the issuing result. Works while offline too.

Network: Not needed.

Signature

java
public byte[] qrCodePng(String id, int tamanhoPx, String empresaId);

Parameters

ParameterJavaRequiredDescription
Invoice identifieridYesThe id in the issuance request
Image sizetamanhoPxNoImage side length in pixels. 64 to 2048, must be passed explicitly
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired; in Java pass null

Return

PNG image bytes.

Possible errors

CodeCaseAction
10029819No such invoice on this machineCheck id
10029817Image size not between 64 and 2048Fix the size

Can also return the common errors.

Examples

java
Files.write(Paths.get("PDV01-000131-qrcode.png"), nfce.qrCodePng("PDV01-000131", 240, null));

XmlAutorizado

Reads the authorized XML of an invoice as is (with the authorization protocol). After an online invoice is authorized, or an offline invoice is authorized after upload, the core automatically downloads the authorized XML to this machine; how many days it is kept is set by the RetencaoXmlDias setting (default 90 days). When it is not on this machine (not downloaded yet, or cleaned up after the retention period), the core fetches it from the platform online right away; the platform archive is the official copy.

When XmlAutorizadoDisponivel from Consultar is true, it is read locally without going online.

Do not call it on the UI thread: when it is not local, it waits for the platform, up to about 120 seconds (or the call timeout, when that is configured longer); run it on a background thread.

Network: Possibly. When it is not local, it is fetched from the platform synchronously, up to about 120 seconds; do not call it on the UI thread.

Signature

java
public byte[] xmlAutorizado(String id, String empresaId);

Parameters

ParameterJavaRequiredDescription
Invoice identifieridYesThe id in the issuance request
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired; in Java pass null

Return

UTF-8 bytes of the authorized XML.

Possible errors

CodeCaseAction
10029841Authorized XML not available: not authorized yet, or not on this machine and cannot be fetched from the platformIf not authorized, fetch it after the NOTA_AUTORIZADA event; if authorized, the platform has not archived it yet or cannot be reached right now, so retry later
10029819No such invoice on this machineCheck id

Can also return the common errors.

Examples

java
// May be fetched online, so run it on a background thread
CompletableFuture.supplyAsync(() -> nfce.xmlAutorizado("PDV01-000131", null))
.thenAccept(xml -> gravar("PDV01-000131-nfce.xml", xml));

XmlCancelamento

Reads the cancellation XML of a cancelled invoice as is (the cancellation event and its receipt). It is kept locally for the same number of days as the authorized XML, set by the RetencaoXmlDias setting (default 90 days); when it is not on this machine, the core fetches it from the platform online right away.

Do not call it on the UI thread: when it is not local, it waits for the platform, up to about 120 seconds (or the call timeout, when that is configured longer).

Network: Possibly. When it is not local, it is fetched from the platform synchronously, up to about 120 seconds; do not call it on the UI thread.

Signature

java
public byte[] xmlCancelamento(String id, String empresaId);

Parameters

ParameterJavaRequiredDescription
Invoice identifieridYesThe id in the issuance request
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired; in Java pass null

Return

UTF-8 bytes of the cancellation XML.

Possible errors

CodeCaseAction
10029843Cancellation XML not available: the invoice is not cancelled, or it is not on this machine and cannot be fetched from the platformIf not cancelled, fetch it after the CANCELAMENTO_CONCLUIDO event; if cancelled, the platform has not archived it yet or cannot be reached right now, so retry later
10029819No such invoice on this machineCheck id

Can also return the common errors.

Examples

java
CompletableFuture.supplyAsync(() -> nfce.xmlCancelamento("PDV01-000131", null))
.thenAccept(xml -> gravar("PDV01-000131-can.xml", xml));

ExportarXmls

Exports the authorized XMLs and cancellation XMLs of a period, by issue date, to a directory, for handing to the accountant monthly or for archiving. Dates follow the time zone of the company's state, and both the start and end dates are included. For the steps, see Operations and advanced tasks: Monthly XML export for the accountant.

  • File names: {chave}-nfe.xml for the authorized XML and {chave}-can.xml for the cancellation XML ({chave} is the 44-digit access key); files with the same name are overwritten.
  • XMLs not on this machine are first fetched from the platform online; those still unavailable do not stop the export and are listed one by one in Falhas in the result, with the reason (including whether they were cleaned up after the retention period).
  • Keep the export range within the retention period of the RetencaoXmlDias setting; XMLs past the retention period have to be fetched from the platform one by one, and those that cannot be fetched go into Falhas.
  • Quick finish 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.
  • Local files only: with somenteLocal set to true there is no network access at all; only XMLs already on this machine are written, and the missing invoices go into Falhas.

Network: Possibly. XMLs not on this machine are fetched online, except when somenteLocal is true. The wait limit is at least 30 minutes, or the call timeout when that is configured longer; do not call it 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.

Signature

java
public Resultados.ExportacaoXml exportarXmls(LocalDate de, LocalDate ate, Path diretorio, String empresaId);
public Resultados.ExportacaoXml exportarXmls(LocalDate de, LocalDate ate, Path diretorio, boolean somenteLocal,
String empresaId);

Parameters

ParameterJavaRequiredDescription
Start datedeYesFirst issue date. That day is included
End dateateYesLast issue date. That day is included
Target directorydiretorioYesExport directory. A relative path is turned into an absolute path from the POS program's current directory
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired; in Java pass null
Local onlysomenteLocalNoLocal export flag. true exports only XMLs already on this machine, with no network access; default false, which first fetches online the XMLs not on this machine. In Java use the five-parameter overload

Return

Export result; fields in Data types: XML export result.

Possible errors

CodeCaseAction
10029874Date missing or wrongly formatted, with Detalhes.campo set to de or ateFix the date
10029844The directory cannot be writtenChange the directory; check disk space and permissions
10029801 / 10029802Company not paired / several companies and no empresaId passedPair first; pass empresaId

A missing XML for a single invoice is not an error; see Falhas in the result.

Can also return the common errors.

Examples

java
Resultados.ExportacaoXml r = nfce.exportarXmls(LocalDate.of(2026, 10, 1), LocalDate.of(2026, 10, 31),
Paths.get("C:/Exportacao/2026-10"), null);
System.out.println("exportadas " + r.getQuantidadeNotas() + " notas, " + r.getQuantidadeArquivos() + " arquivos, falhas "
+ r.getFalhas().size());

TrocarCertificado

After the company A1 certificate is renewed or replaced, replaces the certificate registered in the core with the new one. Device identity, device series and license stay the same, with no new pairing; the new certificate is reported to the platform at the next heartbeat. Before the certificate expires the core sends the CERTIFICADO_EXPIRANDO event (once each at 30, 7 and 1 days), which you can use to warn the administrator.

Network: Not needed.

Signature

java
public void trocarCertificado(Certificado certificado, String empresaId);

Parameters

ParameterJavaRequiredDescription
CertificatecertificadoYesThe new A1 certificate. How to pass it is in Data types: certificate source; the CNPJ must match the store company
Company identifierempresaIdRequired with several companiesIssuing company. Can be omitted when only one company is paired; in Java pass null

Return

None. On success, CertificadoValidoAte in Situacao changes to the expiry of the new certificate.

Possible errors

CodeCaseAction
10029813Certificate unavailable: not found, without private key, or CNPJ different from the companyCheck the certificate store and use the company certificate
10029814Certificate expiredUse a valid certificate
10029874Invalid certificate parameter: thumbprint not 40 hexadecimal characters, or empty PFXFix the certificate parameter
10029801 / 10029802Company not paired / empresaId missing with several companiesPair first; send empresaId

Can also return the common errors.

Examples

java
nfce.trocarCertificado(Certificado.deArquivoPfx(Files.readAllBytes(Paths.get("C:/deploy/novo.pfx")), senha), null);

Situacao

Reads the overall core status: core version, engine-level warnings, and for each paired company the connection, remaining license, pending uploads, upload deadline, certificate expiry and the last error. Useful for showing hints such as "offline", "N invoices waiting for upload" or "certificate expires in 7 days" on the POS screen; it can be called periodically (for example every 10 seconds) at very low cost.

Network: Not needed.

Signature

java
public Resultados.Nucleo situacao();

Parameters

None.

Return

Core status; fields in Data types: core status. the per-company status is the list of key-value maps returned by getEmpresas().

Suggested screen hints:

ConditionHint
Conectado is falseOffline; invoices will be uploaded once online
PendentesTransmissao above 0Invoices waiting for upload; show the upload deadline from PrazoTransmissaoAte
OfflineAte closeOffline time almost used up, go online soon
CertificadoValidoAte closeCertificate about to expire; after renewal call TrocarCertificado
Situacao is not AtivoThe device can no longer issue new invoices; contact the integrator
UltimoErro has a valueReason of the last failed sync; give it to support when troubleshooting
Avisos is not emptyThe runtime environment needs adjusting, for example Java in-process mode is missing the startup parameter needed for proxy authentication, see Outbound proxy; show the text as is to the technician

Possible errors

Only the common errors.

Examples

java
Resultados.Nucleo s = nfce.situacao();
for (Map<String, Object> empresa : s.getEmpresas()) {
System.out.println(empresa.get("empresaId") + " conectado=" + empresa.get("conectado"));
}
for (String aviso : s.getAvisos()) {
System.out.println("aviso: " + aviso);
}

SincronizarAgora

Triggers a sync round immediately: heartbeat, license renewal, offline invoice upload, submission of queued cancellations and fetching of platform results. The core already syncs automatically on a schedule; this method shortens the wait, for example when the POS detects that the network is back, or before shift change when you want uploads to finish quickly.

The sync runs in the background; results arrive as events, or can be checked afterwards with Consultar and Situacao. The call only triggers the next background sync round and returns immediately without waiting for the result, so it can be called directly on the UI thread; if a company's sync round is already in progress, no second round runs in parallel, and syncing continues as soon as that round ends. Calling it while offline does not raise an error.

Network: Triggers network activity and does not wait for the sync result; the call returns immediately.

Signature

java
public void sincronizarAgora();

Parameters

None.

Return

None.

Possible errors

Only the common errors.

Examples

java
// Only triggers the next background round and returns immediately; it can be called directly on the UI thread
nfce.sincronizarAgora();

Backup

Backs up the local store encrypted to a single file, for regular safekeeping or as protection before replacing the disk. The backup is a complete snapshot taken at one moment, and issuing can continue as usual meanwhile. For the backup strategy and the overall recovery flow for a failed computer, see Operations and advanced tasks: Backup and recovery from a failed computer.

  • Encryption: 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.
  • Can only be restored on the same computer under the same Windows user: the device keys in the local store are protected at Windows user level, so after changing the computer or the Windows user the backup cannot be used; deactivate the old device and pair again.
  • Restore: use RestaurarBackup. The SDK and runtime version used to restore cannot be older than the one used for the backup; VersaoBanco in the result records the local store schema version.
  • Writing: a temporary file is written first and then renamed, so a failure does not leave an incomplete backup file behind.

Network: Not needed. The wait limit is at least 30 minutes, or the call timeout when that is configured longer; with a large local store it takes a few minutes, so do not call it on the UI thread. If the wait times out (10029833), the runtime may still be writing the file: do not retry right away with the same file name; wait a moment and use a new file name.

Signature

java
public Resultados.Backup backup(Path destino, String senha);

Parameters

ParameterJavaRequiredDescription
Backup filedestinoYesBackup file path. The file must not already exist; a relative path is turned into an absolute path from the POS program's current directory
PassphrasesenhaYesBackup passphrase. At least 8 characters; the same passphrase is needed to restore, and it is not written to the logs

Return

Backup result; fields in Data types: backup result.

Possible errors

CodeCaseAction
10029874Empty passphrase; Detalhes.campo is senhaPass the passphrase
10029817Passphrase shorter than 8 charactersUse a longer passphrase
10029844The target file already exists, or the directory cannot be writtenChange the file name or directory; check disk space and permissions

Can also return the common errors.

Examples

java
Resultados.Backup b = nfce.backup(Paths.get("D:/Backup/tffiscal-20261031.bak"), senhaBackup);
System.out.println(b.getArquivo() + " " + b.getBytes() + " sha256=" + b.getSha256());

RestaurarBackup

Puts the local store back from an encrypted backup made by Backup, to recover after the local store is lost, corrupted or damaged by a mistake. This is a static method, called before Iniciar: it does not start the engine or go online; in subprocess mode the SDK temporarily starts a runtime, which exits once the restore is done. When it is called, no instance may be running on this data directory: an instance already started must first Encerrar, and Iniciar again after the restore. For when to use a backup and when to export a pending upload package instead, see Operations and advanced tasks: Backup and recovery from a failed computer.

  • Only on the original computer: the device keys in the backup are protected by Windows data protection and can only be used on the same computer and under the same Windows user that made the backup. When changing computers or Windows users, do not rely on the backup: export the pending invoices with ExportarPendentes, hand them to the platform, and pair the new computer again.
  • Original store kept: before restoring, the original store in the data directory is renamed and kept (the file name starts with nfce.db.antes-restauracao-), and CopiaAnterior in the result gives its path; if the restore fails, the original store is left untouched.
  • Version: a backup whose local store schema version is newer than the current SDK is refused; an older one is upgraded automatically at the next Iniciar.
  • Protection after the restore: the numbers and licenses in the backup stay at the moment of the backup. After the restore and Iniciar, each company first goes through a realignment: offline issuing returns 10029811, 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. Until the realignment finishes, no invoice can be issued without reaching the platform. Even if invoices issued after the backup were already handed to consumers, no numbers are duplicated.
  • Offline invoices issued after the backup: they are not in the backup. If the old store still starts, first call ExportarPendentes on the old store before restoring and hand the export to the platform; otherwise these invoices are lost.

Network: Not needed. The wait limit is at least 30 minutes, or the call timeout when that is configured longer; do not call it on the UI thread.

Signature

java
public static Resultados.Restauracao restaurarBackup(Configuracao config, Path origem, String senha);

Parameters

ParameterJavaRequiredDescription
ConfigurationconfigYesInitialization configuration. The same one used for Iniciar, from which the data directory and the runtime location are taken; see Configuration
Backup fileorigemYesBackup file path. A relative path is turned into an absolute path from the POS program's current directory
PassphrasesenhaYesBackup passphrase. The passphrase used when the backup was made

Return

Restore result; fields in Data types: Restore result.

Possible errors

CodeCaseAction
10029846Wrong passphrase, or the backup file was altered, is corrupted or is not a backup of this SDK; the two cases are not told apartCheck the passphrase; use an intact backup. The original store was not changed
10029842The backup comes from a newer SDK versionUpgrade the SDK and the runtime to at least the version used for the backup
10029828Another engine is running on the data directory, including an instance of this program on which Encerrar has not been called yet. The SDK's static RestaurarBackup opens its own runtime connection on every call, so this is the code it getsFirst Encerrar the instance using this data directory, then restore
10029875The backup restore protocol method restaurarBackup was called on a runtime connection that has already run Iniciar. The SDK's static RestaurarBackup opens a new connection on every call and never gets this code; it only appears when integrating directly with the runtime protocolCall Encerrar, then restore over a new connection before Iniciar
10029817Passphrase shorter than 8 charactersEnter the passphrase used when the backup was made
10029874Empty backup file or passphrase; Detalhes.campo is origem or senhaFill in the missing parameter
10029844Failed to read or write a fileCheck the backup file path, and the disk space and permissions of the data directory

Can also return the common errors.

Examples

java
nfce.encerrar();
Resultados.Restauracao r = TfFiscalNfce.restaurarBackup(config, Paths.get("D:/Backup/tffiscal-20261031.bak"), senhaBackup);
System.out.println("versao " + r.getVersaoBanco() + " anterior " + r.getCopiaAnterior());
nfce = TfFiscalNfce.iniciar(config);
// Offline issuing is paused until a new license arrives, so sync one round right away (run this block on a background thread)
nfce.sincronizarAgora();

ExportarPendentes

Exports the signed offline invoices of this machine not yet uploaded as a pending upload package the platform can import directly. Used when the till is broken or cannot go online for a long time and there is no time to upload from this machine. The export does not change the local state; these invoices stay in this machine's upload queue. For the overall steps when a computer fails, see Operations and advanced tasks: Backup and recovery from a failed computer.

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 the call, {dispositivoId} is the device ID, and {chave} is the 44-digit access key.
  • Each manifest manifesto.json records 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}.xml files in the same directory are the same signed XML, for manual inspection.
  • To hand it 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. With several companies the zip contains several device directories; operations filters by device and submits them in batches.
  • No pending invoices is not an error: Quantidade is 0, Manifesto is empty and Manifestos is an empty array.
  • Each manifest is written to a temporary file first and then renamed, so any manifest you read is complete.

Network: Not needed. The wait limit is at least 30 minutes, or the call timeout when that is configured longer; do not call it 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.

Signature

java
public Resultados.ExportacaoPendentes exportarPendentes(Path diretorio);

Parameters

ParameterJavaRequiredDescription
Target directorydiretorioYesExport directory. A relative path is turned into an absolute path from the POS program's current directory

Exports the invoices waiting for upload of every company paired in this data directory, with one directory and its own manifests for each company's device; the manifests record the company of each invoice.

Return

Export result; fields in Data types: pending upload export result.

Possible errors

CodeCaseAction
10029844The directory cannot be writtenChange the directory; check disk space and permissions

Can also return the common errors.

Examples

java
Resultados.ExportacaoPendentes p = nfce.exportarPendentes(Paths.get("E:/Pendentes"));
System.out.println(p.getQuantidade() + " notas, " + p.getManifestos().size() + " pacote(s)");

CriarTerminal

Issues a terminal token for one secondary on the primary. The name is the till identifier on the invoices that secondary issues, so use a till number the store recognizes, for example Caixa 2. The full token appears only once, in this return; the primary keeps only a digest. Configure it on the secondary's TokenTerminal right away; if it is lost, revoke it and issue a new one. Primary mode only; for deploying and managing secondaries, see Multiple tills (primary and secondary mode).

Network: Not needed.

Signature

java
public Resultados.TerminalCriado criarTerminal(String nome);

Parameters

ParameterJavaRequiredDescription
Terminal namenomeYesTill name. 1 to 60 characters; must be unique among active terminals, case-insensitive

Return

The new terminal; fields in Data types: secondary terminal.

Possible errors

CodeCaseAction
10029874Name empty, longer than 60 characters, or already used by an active terminal (Detalhes.motivo is duplicado)Pick another name; to reuse an old name, revoke the old terminal first
10029884Not in primary modeCall it on the primary only

Can also return the common errors.

Examples

java
Resultados.TerminalCriado t = principal.criarTerminal("Caixa 2");
// The full token is returned only once; configure it on till 2 right away
System.out.println(t.getId() + " " + t.getToken());

ListarTerminais

Lists the secondary terminals on the primary, newest first, without tokens. By default terminals revoked more than 30 days ago are hidden; pass todos as true to list all of them. Records are always kept. Primary mode only.

Network: Not needed.

Signature

java
public List<Resultados.Terminal> listarTerminais(boolean todos);

Parameters

ParameterJavaRequiredDescription
List alltodosNoInclude terminals revoked more than 30 days ago. Default false

Return

List of terminals; fields in Data types: secondary terminal.

Possible errors

CodeCaseAction
10029884Not in primary modeCall it on the primary only

Can also return the common errors.

Examples

java
for (Resultados.Terminal t : principal.listarTerminais(false)) {
System.out.println(t.getNome() + " " + t.getSituacao() + " " + t.getUltimoUsoEm());
}

RevogarTerminal

Revokes the terminal token of one secondary on the primary, effective immediately: later calls from that secondary return 10029882, and events not yet delivered to it are dropped. Call it when a secondary is lost, retired or its token leaked. Revocation cannot be undone; issue a new token when needed. Primary mode only.

Network: Not needed.

Signature

java
public void revogarTerminal(String id);

Parameters

ParameterJavaRequiredDescription
Terminal identifieridYesThe id returned by CriarTerminal, starting with trm_

Return

None.

Possible errors

CodeCaseAction
10029888Terminal not foundCheck the id with ListarTerminais
10029884Not in primary modeCall it on the primary only

Can also return the common errors.

Examples

java
principal.revogarTerminal("trm_8Kq2Xc0vLm4R");

Encerrar

Closes the SDK: stops the background sync, waits for issuances in progress to finish (up to 10 seconds), closes the local store and then ends the runtime (forcing it to stop if it has not exited after another 5 seconds). The whole process takes at most about 15 seconds. Call it before the POS exits. It can be called repeatedly; after it, any other method returns 10029834 and you need to call Iniciar again.

No uploads happen while the SDK is closed; after the next Iniciar a sync round runs at once, and if there are still invoices waiting for upload or unacknowledged events, PENDENCIAS_NA_INICIALIZACAO is sent. For what to watch out for when exiting and restarting, see Operations and advanced tasks: Closing and restarting.

Network: Not needed.

Signature

java
public void encerrar();
public void close();

close is the same as Encerrar and works with try-with-resources.

Parameters

None.

Return

None.

Possible errors

Throws no errors and can be called repeatedly.

Examples

java
Runtime.getRuntime().addShutdownHook(new Thread(nfce::encerrar));

Data types

The result objects returned by the methods, the status values in events and the certificate parameters. How to read the columns of each table:

  • JSON name: the field name in the raw text of getJson().
  • Java: getter; fields marked "via getCampos()" have no dedicated getter, read them with getCampos().get("fieldName").
  • Time fields are ISO 8601 UTC text.
  • Every result keeps its raw text (getJson()); fields added by a newer runtime can still be read from the raw text by an older SDK.
  • Fields with "Nullable" = "Yes" can be null.

Invoice status

Values of Status in issuing results, query statuses and events.

ValueMeaningWhat the POS does
AutorizadaAuthorizedPrint the receipt
ContingenciaPendenteSigned offline on this machine, waiting for uploadPrint the receipt and hand it to the consumer; upload happens automatically
AguardandoAutorizacaoAccepted online, SEFAZ has not answered yetDo not print yet, wait for the authorization event; if it is denied afterwards you receive NOTA_NEGADA
NegadaAn invoice forwarded online was denied by SEFAZ, including invoices denied after waiting for authorization (event NOTA_NEGADA)No same-number correction; correct the sale data and reissue with a new id
RejeitadaSEFAZ rejected the upload of an offline invoice (event NOTA_REJEITADA)Make a same-number correction with Substituir; never issue a new one
RecusadaThe platform refused this offline invoiceNeeds manual action, contact the platform
CanceladaCancelledNone

Issuing result

Returned by Emitir and Substituir. Java ResultadoEmissao.

JSON nameJavaTypeNullableDescription
idgetId()TextNoInvoice identifier. The id in the issuance request
statusgetStatus()TextNoInvoice status. Values above
emitidaEmContingenciaisEmitidaEmContingencia()BooleanNoOffline signing flag. Stays true after authorization
chavegetChave()TextYesAccess key. 44 digits
seriegetSerie() (Long)IntegerYesSeries
numerogetNumero() (Long)IntegerYesInvoice number
dataEmissaogetDataEmissao()TimeYesIssue time
protocologetProtocolo()TextYesAuthorization protocol number. null while waiting for upload offline
qrCodegetQrCode()TextYesQR Code content. Encode it as a QR Code when laying out the receipt yourself
urlConsultagetUrlConsulta()TextYesConsumer lookup URL
motivogetMotivo()TextYesReason text. From SEFAZ or the platform
cStatgetCStat() (Long)IntegerYesSEFAZ result code. null when there is no SEFAZ result
xMotivogetXMotivo()TextYesSEFAZ result message. Always paired with the result code
tentativaOnlineisTentativaOnline()BooleanNoOnline attempt flag. true when online was tried first and the result was unclear before falling back to offline; this invoice uses the number after the one of the online attempt, and on upload the platform settles that original number; false for invoices authorized online
respostaPlataformagetRespostaPlataforma()TextYesRaw platform response. For online issuing, the JSON returned by the platform, same structure as Query NFC-e; null offline
terminalgetTerminal()TextYesTill identifier. For invoices issued by a secondary in primary/secondary mode, its terminal name; null for invoices issued by the primary itself or in standalone mode. Reported to the platform with the invoice; same value as terminal in Query NFC-e and webhooks

Query status

Returned by Consultar and element of the invoice page. Java SituacaoNota; contains every field of the issuing result, plus:

JSON nameJavaTypeNullableDescription
transmitidaisTransmitida()BooleanNoUploaded flag. The offline invoice was uploaded to the platform
cancelamentoPendenteisCancelamentoPendente()BooleanNoPending cancellation flag. A cancellation is held or queued locally
correcoesgetCorrecoes() (Long)IntegerNoNumber of corrections
atualizadoEmgetAtualizadoEm()TimeYesLast update time
xmlAutorizadoDisponivelisXmlAutorizadoDisponivel()BooleanNoLocal XML ready flag. true when the authorized XML is on this machine, so XmlAutorizado reads it locally; when authorized but false, the call fetches it online
pedidogetPedido()TextYesIssuance request. JSON text, used as the base for a same-number correction; item lines that referenced a tax class already carry the impostos expanded by the platform, which you can keep for sending while offline

Invoice page

Returned by ListarNotas. Java Resultados.PaginaNotas.

JSON nameJavaTypeNullableDescription
itensgetItens()ArrayNoInvoices of this page. Elements are query statuses, newest issue time first
paginagetPagina()IntegerNoPage number. Starts at 1
tamanhoPaginagetTamanhoPagina()IntegerNoPage size. Always 50
temMaisisTemMais()BooleanNoNext page flag. No total is given

Preview result

Returned by Previsualizar. Java Resultados.PreVisualizacao.

JSON nameJavaTypeNullableDescription
validoisValido()BooleanNoValidation passed flag
errosgetErros()Text arrayNoValidation errors. Already translated into the error message language; empty array when valid
pedidoNormalizadogetPedidoNormalizado()TextYesNormalized request. JSON text, usually not needed
valorTotalgetValorTotal() (BigDecimal)DecimalYesInvoice total
valorTributosgetValorTributos() (BigDecimal)DecimalYesTax total

Cancellation result

Returned by Cancelar and CancelarPorSubstituicao. Java Resultados.Cancelamento.

JSON nameJavaTypeNullableDescription
situacaogetSituacao()TextNoAcceptance outcome. Values below
motivogetMotivo()TextYesNotes
situacaoMeaning
SolicitadoAuthorized invoice; the cancellation was sent to the platform and the result arrives as the CANCELAMENTO_CONCLUIDO or CANCELAMENTO_REJEITADO event
AgendadoOffline invoice uploaded but not yet authorized; the platform holds the cancellation and submits it automatically after authorization
EnfileiradoLocalQueued locally: offline, or the offline / substitute invoice has not been uploaded yet; submitted in the same round right after the upload

Pairing code info

Returned by InspecionarCodigoAtivacao. Java Resultados.CodigoAtivacao.

JSON nameJavaTypeNullableDescription
ambientegetAmbiente() (Long)IntegerNoIssuing environment. 1 production, 2 testing
formasPermitidasgetFormasPermitidas() (Long)IntegerNoAllowed forms. 0 any form, 1 Invoice Assistant only, 2 embedded SDK only
expiraEmgetExpiraEm()TimeNoPairing code expiry
plataformagetPlataforma()TextNoPlatform address. The platform the code points to
seriegetSerie() (Long)IntegerYesSet device series. The series the integrator set when generating the code; null if not set, and the platform assigns one at pairing
numeroInicialgetNumeroInicial() (Long)IntegerYesSet start number. When only the series was set, the number the platform computed when generating the code; null if not set, and numbering starts at 1

Pairing result

Returned by Ativar. Java Resultados.Ativacao.

JSON nameJavaTypeNullableDescription
empresaIdgetEmpresaId()TextNoCompany identifier. The empresaId of the other methods
dispositivoIdgetDispositivoId()TextNoDevice identifier
cnpjgetCnpj()TextNoCompany CNPJ
ufvia getCampos()TextNoState
ambientevia getCampos()IntegerNoIssuing environment. 1 production, 2 testing
serieOfflinegetSerieOffline() (Long)IntegerNoDevice series. Exclusive to this device, shared by online and offline invoices with continuous numbering; the field name was kept
licencaExpiraEmgetLicencaExpiraEm()TimeYesLicense expiry
numeroInicialgetNumeroInicial() (Long)IntegerNoStart number. Number of the first invoice of this device; 1 when the code did not set one

Paired company

Element of Empresas. Java Resultados.EmpresaAtivada.

JSON nameJavaTypeNullableDescription
empresaIdgetEmpresaId()TextNoCompany identifier
dispositivoIdgetDispositivoId()TextNoDevice identifier
cnpjgetCnpj()TextNoCompany CNPJ
ufvia getCampos()TextNoState
ambientevia getCampos()IntegerNoIssuing environment. 1 production, 2 testing
serieOfflinevia getCampos()IntegerNoDevice series
situacaogetSituacao()TextNoDevice status. Values below
situacaoMeaningAction
AtivoCan issueNone
DesativadoDevice deactivated by the integratorCannot be undone; to keep using the same computer, pair again
RevogadoDevice revoked by the platformContact the platform
EmpresaDesativadaOffline issuing for the company disabledContact the platform
AplicativoBloqueadoPOS software blocked by the platformContact the platform
VersaoBloqueadaPOS version blocked or below the minimumUpgrade the POS

Any value other than Ativo stops new invoices; offline invoices already issued are still uploaded.

Core status

Returned by Situacao. Java Resultados.Nucleo.

JSON nameJavaTypeDescription
versaoNucleogetVersaoNucleo()TextCore version
empresasgetEmpresas() (elements are key-value maps)ArrayStatus of each paired company, fields below
avisosgetAvisos()Text arrayEngine warnings. Runtime environment issues the host needs to handle, empty array when there are none. For example, proxy authentication is configured, but Java in-process mode is missing the JVM startup parameter needed for proxy authentication or the setting did not take effect, see Outbound proxy. The text is in Portuguese and can be shown as is

Elements of empresas:

JSON nameTypeNullableDescription
empresaIdTextNoCompany identifier
dispositivoIdTextNoDevice identifier
situacaoTextNoDevice status. Same values as paired company
conectadoBooleanNoOnline flag. Whether the platform can be reached right now
ultimoContatoTimeYesLast contact time
licencaExpiraEmTimeYesLicense expiry
offlineAteTimeYesOffline issuing deadline. The earlier of license expiry and certificate expiry
pendentesTransmissaoIntegerNoInvoices waiting for upload
pendenteMaisAntigaEmTimeYesOldest pending time. Issue time of the oldest invoice waiting for upload
prazoTransmissaoAteTimeYesUpload deadline. Deadline of the oldest invoice waiting for upload; after it the device cannot keep issuing offline
certificadoValidoAteTimeYesCertificate expiry
ultimoErroTextYesLast error. Reason of the last failed sync
numerosNaoUtilizadosPendentesIntegerNoNumber ranges waiting to be voided. Ranges of numbers taken but unused that still have to be reported to the platform for voiding; when a report is refused and the refusal is not final, it is retried automatically, see NUMERO_INUTILIZACAO_RECUSADA
restauradoPendenteSincronizacaoBooleanNoRestore pending sync flag. true after a backup restore until a new license arrives; meanwhile offline issuing returns 10029811 and online issuing first syncs with the platform; false once aligned. Use it to tell the cashier to go online; do not parse the error text

XML export result

Returned by ExportarXmls. Java Resultados.ExportacaoXml.

JSON nameJavaTypeNullableDescription
quantidadeNotasgetQuantidadeNotas()IntegerNoInvoices exported. Number of documents with at least one file written
quantidadeArquivosgetQuantidadeArquivos()IntegerNoFile count. Total number of authorized XML and cancellation XML files written; a cancelled invoice with both its authorized and cancellation XML written counts as two
arquivosgetArquivos()Text arrayNoExported files. Absolute paths of the files written, one file each for the authorized XML and the cancellation XML
falhasgetFalhas() (elements are key-value maps)ArrayNoMissing list. Documents in the range whose XML could not be obtained, empty array when there are none; element fields below

falhas elements:

JSON nameJava keyTypeDescription
ididTextInvoice identifier
chavechaveTextAccess key
motivomotivoTextReason it is missing. Includes whether it was cleaned up after the retention period

Backup result

Returned by Backup. Java Resultados.Backup.

JSON nameJavaTypeNullableDescription
arquivogetArquivo()TextNoBackup file. Absolute path
bytesgetBytes()IntegerNoFile size. In bytes
versaoBancogetVersaoBanco()IntegerNoLocal store schema version. The core version used to restore must not be older than this
sha256getSha256()TextNoFile digest. SHA-256 of the encrypted backup file, lowercase hexadecimal

Restore result

Returned by RestaurarBackup. Java Resultados.Restauracao.

JSON nameJavaTypeNullableDescription
versaoBancogetVersaoBanco()IntegerNoLocal store schema version. Version of the restored store; if older than the current SDK, it is upgraded automatically at the next startup
copiaAnteriorgetCopiaAnterior()TextYesCopy of the original store. Absolute path of the original store file kept before the restore; empty when there was no store before

Pending upload export result

Returned by ExportarPendentes. Java Resultados.ExportacaoPendentes.

JSON nameJavaTypeNullableDescription
quantidadegetQuantidade()IntegerNoInvoices exported
manifestogetManifesto()TextYesFirst manifest. Absolute path of the first package's manifesto.json; empty when there are no invoices waiting for upload
manifestosgetManifestos()Text arrayNoAll manifests. One per pacote-NNN in each device directory, at most 500 invoices per package; empty array when there are no invoices waiting for upload
arquivosgetArquivos()Text arrayNoSigned XML files. Absolute paths

Certificate source

Certificate parameter of Ativar and TrocarCertificado.

SourceJava
Certificate already in the Windows certificate storeCertificado.doRepositorio(thumbprint, maquinaLocal)
PFX fileCertificado.deArquivoPfx(bytes, senha)
ParameterDescription
thumbprintCertificate thumbprint. SHA-1, 40 hexadecimal characters, spaces are ignored; a wrong format returns 10029874
maquinaLocalLocal machine store flag. true uses the local machine certificate store, false (default) the store of the current Windows user
PFX bytes and senhaPFX certificate and password. The core imports the certificate into the certificate store with a non-exportable private key, then keeps only the thumbprint; the password is not stored

When you pair or replace the certificate with a PFX (Certificado.deArquivoPfx), the core imports the certificate into the "Current User > Personal" store of the Windows user running the SDK, with a non-exportable private key, and keeps it there permanently: every signature uses it. Do not delete this certificate: without it the device cannot sign and issuing returns 10029813.

When the device is retired, clean up in this order:

  1. Check in the status that pendentesTransmissao is 0 for every company, so all offline invoices have been uploaded
  2. Deactivate or revoke the device in the console; if you are only replacing the certificate, install the new one first with TrocarCertificado
  3. As the same Windows user, open certmgr.msc and delete the old certificate under "Personal > Certificates" by thumbprint, or run Remove-Item Cert:\CurrentUser\My\<thumbprint> in PowerShell

Secondary terminal

Returned by CriarTerminal. Java Resultados.TerminalCriado.

JSON nameJavaTypeNullableDescription
idgetId()TextNoTerminal identifier. Starts with trm_, used to revoke
nomegetNome()TextNoTerminal name. The till identifier on the invoices this secondary issues
tokengetToken()TextNoTerminal token. Starts with tfl_, returned only once; configure it as the secondary's TokenTerminal

Elements of ListarTerminais. Java Resultados.Terminal; no token.

JSON nameJavaTypeNullableDescription
idgetId()TextNoTerminal identifier
nomegetNome()TextNoTerminal name
situacaogetSituacao()TextNoTerminal status. Ativo or Revogado
criadoEmgetCriadoEm()TimeNoIssue time
ultimoUsoEmgetUltimoUsoEm()TimeYesLast use. null if never used
revogadoEmgetRevogadoEm()TimeYesRevocation time. null for active terminals

Exceptions

Every failure throws an exception.

FieldJava TfFiscalExceptionDescription
Error codegetCodigo()Integer. Branch on it, see Error codes
Error constantgetTipo()For example ENGINE_LICENSE_EXPIRED; platform errors carry the platform constant name
MessagegetMessage()Translated into the configured error message language, can be shown as is
DetailsgetDetalhes(), getDetalhesJson()For example erros with per-field reasons on validation failure, or campo on a parameter error

Error code constants: TfFiscalErrorCodes registers the common codes; codes not registered still appear as numbers in the error code field.

Events

Local events the core delivers to the POS program when invoice status, license, certificate, connection and so on change. Webhooks that the platform sends to the integrator's server are a separate channel, see How you get the results; for which events a secondary receives in primary/secondary mode, see Multiple tills (primary and secondary mode).

Subscribing

How to subscribeCallback thread
aoReceberEvento(Consumer<EventoNfce>) in the configuration, or the instance method aoReceberEvento, whose return value cancels the subscription when closedSubprocess mode calls back one by one on a dedicated SDK thread; in-process mode calls back synchronously on the core delivery thread. A handler that throws an exception does not acknowledge

Attach the handler at startup with aoReceberEvento in the configuration, so events queued before startup are not missed.

Delivery and acknowledgement

  • At least once, in order: an event is stored on this machine in the same transaction as the state change that triggered it, then delivered.
  • Acknowledgement: returning normally from the handler acknowledges the event. If the handler throws, the event is not acknowledged, and about 30 seconds later delivery restarts from the earliest unacknowledged event, with the same EventoId and Seq.
  • Deduplication: the same event can arrive more than once; deduplicate by EventoId.
  • Do not block in the handler for long: record the event first and do slow work asynchronously, or later events pile up.
  • SDK local events: RUNTIME_FALHOU and RUNTIME_REINICIADO are produced by the SDK itself, have Seq 0, need no acknowledgement and are not redelivered.

Common fields

JSON nameJavaTypeNullableDescription
eventoIdgetEventoId()TextNoEvent identifier. Deduplication key, unchanged on redelivery
seqgetSeq() (long)IntegerNoLocal sequence. Monotonically increasing; 0 for SDK local events
tipogetTipo()TextNoEvent type. See the sections below
ocorridoEmgetOcorridoEm()Time textNoOccurrence time. ISO 8601 UTC
empresaIdgetEmpresaId()TextYesCompany identifier. null for SDK local events
dispositivoIdvia getCampos()TextYesDevice identifier
idgetId()TextYesInvoice identifier. Only invoice events have it
chavegetChave()TextYesAccess key. Only invoice events have it
statusgetStatus()TextYesCurrent invoice status. Only invoice events have it; values in Invoice status
dadosgetDados() (Map<String, Object>)ObjectNoEvent data. Fields in the sections below

NOTA_EMITIDA_OFFLINE

Offline signing succeeded. Invoice event, status is ContingenciaPendente.

dados fieldTypeDescription
serieIntegerDevice series
numeroIntegerInvoice number
qrCodeTextQR Code content
tentativaOnlineBooleanOnline attempt flag. true when online was tried first and the result was unclear before falling back to offline; false for invoices authorized online

Handling: mark the POS sale as "offline, waiting for upload". Emitir already returned the same result at issuing time; this event mainly fills in the status after the POS crashes and restarts.

NOTA_AUTORIZADA

An offline invoice was authorized after upload or after a same-number correction, or an invoice pending online was authorized. Invoice event, status is Autorizada.

dados fieldTypeDescription
protocoloTextAuthorization protocol number
dataAutorizacaoTime text, nullableAuthorization time
foraDoPrazoBooleanLate delivery flag. true when it reached SEFAZ more than 24 hours after issuing; the invoice is still valid
aposCorrecaoBooleanAuthorized after correction flag. true when authorized after a same-number correction

Handling: mark the POS sale as authorized and record the protocol; an invoice that was pending online can now be printed.

NOTA_REJEITADA

An offline invoice was rejected by SEFAZ on upload. Invoice event, status is Rejeitada.

dados fieldTypeDescription
cStatIntegerSEFAZ result code
motivoTextSEFAZ result message

Handling: ask the manager to fix it and correct it under the same number with Substituir; never issue a new invoice. The original request is in Pedido from Consultar.

NOTA_NEGADA

An invoice forwarded online and waiting for authorization (AguardandoAutorizacao) was later denied by SEFAZ. Invoice event, status is Negada. A rejected upload of an offline invoice does not send this event; it sends NOTA_REJEITADA.

dados fieldTypeDescription
cStatIntegerSEFAZ result code
motivoTextSEFAZ result message
numeroLiberadoBooleanNumber reclaimed. When true, SEFAZ did not use this number, so the kernel keeps it for the next invoice issued online and no gap is left in the numbering

Handling: this invoice cannot get a same-number correction. Correct the sale data according to the result code and message, and issue again by calling Emitir with a new id.

NOTA_RECUSADA_PLATAFORMA

The platform refused this offline invoice. Invoice event, status is Recusada.

dados fieldTypeDescription
codigoInteger, nullablePlatform error code
mensagemTextPlatform message

Handling: needs manual action; record the code and message and contact the platform.

CANCELAMENTO_CONCLUIDO

Cancellation succeeded. Invoice event, status is Cancelada.

dados fieldTypeDescription
cStatInteger, nullableSEFAZ result code
motivoTextResult message
protocoloText, nullableCancellation protocol number

Handling: mark the POS sale as cancelled.

CANCELAMENTO_REJEITADO

The cancellation was refused, for example past the cancellation deadline, or the platform refused a held cancellation. Invoice event, status is the invoice original status.

dados fieldTypeDescription
cStatInteger, nullableSEFAZ result code
motivoTextRefusal reason
protocoloText, nullableProtocol number

Handling: the invoice is still valid. Ask the manager to handle it under the rules of Cancel NFC-e.

NUMERO_INUTILIZADO

Device series numbers that were taken but never signed are closed: voided at SEFAZ, or, in states that no longer accept voiding such as AC, BA and SP, exempt from reporting by rule. Either way the numbers count as used and are never issued. Not an invoice event.

dados fieldTypeDescription
serieIntegerDevice series
inicioIntegerFirst number
fimIntegerLast number

Handling: nothing to do; it can be logged for reconciliation.

NUMERO_INUTILIZACAO_RECUSADA

The platform refused the voiding request for unused numbers. Not an invoice event. A refusal that is not final is sent only once, on the first failure, and the core then retries automatically with backoff; a final refusal needs manual checking.

dados fieldTypeDescription
serieIntegerDevice series
inicioIntegerFirst number
fimIntegerLast number
codigoIntegerPlatform error code
mensagemTextPlatform message
definitivoBooleanFinal flag. true means it will not be retried, for example an invalid range or invoices already exist in the range; false means the core retries automatically

Handling: when definitivo is false, logging it is enough; the number of ranges waiting to be voided is in NumerosNaoUtilizadosPendentes of Situacao. When true, record the error code and message, and have the administrator check the number range and then contact the platform.

DISPOSITIVO_DESATIVADO

The device was deactivated or revoked, offline issuing for the company was disabled, or the POS software or its version was blocked. New invoices are refused from now on; offline invoices already issued are still uploaded.

dados fieldTypeDescription
situacaoTextDevice status. Values in Paired company
motivoTextReason. Can be an empty string

Handling: show "this machine can no longer issue invoices" prominently on the POS screen and, depending on situacao, contact the integrator or upgrade the POS.

LICENCA_EXPIRANDO

Less than 12 hours left on the license and it could not be renewed, usually because the network has been down for a long time. At most once every 6 hours.

dados fieldTypeDescription
expiraEmTime textLicense expiry
offlineAteTime textOffline issuing deadline

Handling: ask the cashier to restore the network soon; the license renews automatically once online.

LICENCA_EXPIRADA

The license expired; offline issuing is refused, online issuing is not affected.

dados fieldTypeDescription
expiradaEmTime textExpiry time

Handling: it renews automatically once the network is back.

PRAZO_TRANSMISSAO_PROXIMO

The oldest invoice waiting for upload is past 80% of the upload deadline.

dados fieldTypeDescription
pendenteMaisAntigaEmTime textIssue time of the oldest pending invoice
prazoAteTime textUpload deadline

Handling: ask the cashier prominently to restore the network now. After the deadline this machine cannot keep issuing offline.

CERTIFICADO_EXPIRANDO

The company certificate expires within 30, 7 or 1 days, one reminder each.

dados fieldTypeDescription
validoAteTime textCertificate expiry

Handling: remind the administrator to renew the certificate, then call TrocarCertificado.

CONEXAO_ALTERADA

Switch between online and offline.

dados fieldTypeDescription
conectadoBooleanOnline flag. true means the connection is back

Handling: update the online / offline indicator on the POS screen.

PENDENCIAS_NA_INICIALIZACAO

At startup the machine still has offline invoices waiting for upload, or unacknowledged events.

dados fieldTypeDescription
pendentesTransmissaoIntegerInvoices waiting for upload
eventosNaoEntreguesIntegerUnacknowledged events

Handling: the POS screen can show "N offline invoices waiting for upload" and check the network; unacknowledged events are redelivered afterwards, nothing else to do.

RUNTIME_FALHOU

SDK local event: the runtime process exited unexpectedly. Seq is 0. Calls in progress fail with 10029832.

dados fieldTypeDescription
codigoSaidaIntegerProcess exit code
tentativaIntegerRestart attempt number
proximaTentativaMsIntegerMilliseconds until the next restart

Handling: with automatic restart on, nothing to do; log it, and if it happens often, export the logs and contact the platform. Resend failed issuances with the same id; the core is idempotent by id.

RUNTIME_REINICIADO

SDK local event: the runtime restarted automatically and was initialized again. Seq is 0.

dados fieldTypeDescription
tentativaIntegerRestart number

Handling: nothing to do; events not acknowledged before the restart are redelivered.

Issuance request

The issuance request accepted by Emitir, Previsualizar and Substituir is the request body of the Issue NFC-e endpoint: same field names, values and validation rules, with the core and the platform using the same normalization and validation rules; referencing a tax class needs a connection, see the table below. For each field, enumerations and scenario examples, go straight to Issue NFC-e.

There are three differences:

FieldIn the SDK
modoRespostaNo need to send it. The SDK always waits for the result; if sent, it is ignored
ambienteEmissaoKeep it equal to the device environment. The device environment is set by the pairing code, see Generate pairing code
itens[].classeImpostoAvailable with a connection. Expanded by the platform before issuing, with the same result as cloud issuing; when offline or when the platform cannot be reached it returns 10029780, in which case send impostos instead. See Tax classes and connectivity

id is the idempotency key: calling Emitir again with the same id returns the original invoice; after an offline restart or a timeout, resend with the same id instead of a new one.

Passing the request

The issuance request is passed as JSON text. Hosts on Java 21 or later also have the typed entry point TfFiscalNfceTipado, with the same request type the platform uses; the same classeImposto rules apply.

Request example

On-site sale, consumer not identified, paid in cash:

json
{
"id": "PDV01-000131",
"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" }
}
}
]
}

Error codes

The Invoice Assistant and the embedded SDK share the offline issuing core. Core errors are thrown as exceptions in the SDK (Codigo is the error code, Tipo the constant) and returned as codigo by the Invoice Assistant local interface. 10029800 to 10029846 come from the core, 10029870 to 10029888 from the SDK wrapper, the runtime communication and primary/secondary mode; the other numbers in the range are unassigned. Error codes returned by the platform are passed through unchanged.

Common errors: any method can return 10029832 (runtime exited unexpectedly), 10029833 (timed out), 10029834 (shut down) or 10029836 (internal core error); in operations that go online, business errors returned by the platform are passed through unchanged. The "Possible errors" of each method list only the codes specific to that method. All error codes and suggested actions are in Error codes.

CodeConstantScenarioAction
10029800ENGINE_NOT_STARTEDNot initializedDoes not happen in normal use; if it does, the SDK wrapper has a defect, initialize again
10029801ENGINE_NOT_ACTIVATEDThe company is not paired on this machine, or no company is paired yetGuide the user to pairing; with several companies, check empresaId
10029802ENGINE_EMPRESA_REQUIREDSeveral companies are paired but empresaId was not givenSend empresaId
10029803ENGINE_LICENSE_MISSINGNo license available for offline issuingSync once while online (SincronizarAgora)
10029804ENGINE_LICENSE_EXPIREDLicense expired; offline issuing is refused, online issuing works as usualRestore the network; the license renews itself
10029805ENGINE_LICENSE_SIGNATURE_INVALIDInvalid license signatureManual action: contact the platform, the local store may have been tampered with
10029806ENGINE_LICENSE_NOT_FOR_DEVICEThe license does not belong to this deviceManual action: pair again
10029807ENGINE_OFFLINE_WINDOW_CLOSEDOffline issuing deadline has passedRestore the network and issue online
10029808ENGINE_LICENSE_QUOTA_EXHAUSTEDDevice 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
10029809ENGINE_CLOCK_ROLLBACKThe system clock was moved backManual action: fix the system time
10029810ENGINE_TRANSMISSION_DEADLINE_REACHEDThe oldest pending invoice is past the upload deadlineManual action: restore the network and upload as soon as possible
10029811ENGINE_OFFLINE_NOT_ALLOWEDThe company or the state does not allow offline issuing; or the device was just restored from a backup and has not received a new license yetIssue online only; after a restore, offline issuing resumes automatically after one online sync
10029812ENGINE_OFFLINE_FUEL_NOT_SUPPORTEDInvoices with fuel cannot be issued offlineIssue once the network is back
10029813ENGINE_CERTIFICATE_UNAVAILABLECertificate not found, without private key, or CNPJ mismatchManual action: check the certificate store; use TrocarCertificado if needed
10029814ENGINE_CERTIFICATE_EXPIREDCertificate expiredManual action: renew it, then TrocarCertificado
10029815ENGINE_SNAPSHOT_MISSINGLocal configuration or tax data missing or invalidSync while online; if it persists, contact the platform
10029816ENGINE_DEVICE_DEACTIVATEDDevice deactivatedManual action: contact the integrator; offline invoices already issued are still uploaded
10029817ENGINE_REQUEST_INVALIDRequest validation failed; Detalhes lists the reason per fieldFix the request; Previsualizar can pre-validate it
10029780ENGINE_TAX_CLASS_REQUIRES_ONLINEAn 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
10029818ENGINE_DUPLICATE_ID_DIFFERENT_CONTENTThe same id was already used for an invoice with different contentUse a new id for a new sale; retry with the original request to get the original invoice back
10029819ENGINE_NOTE_NOT_FOUNDThis machine has no such invoiceCheck id and empresaId
10029820ENGINE_NOTE_NOT_CORRECTABLEThe current status does not allow correctionOnly Rejeitada can go through Substituir
10029821ENGINE_CORRECTION_CHANGES_TOTALSThe correction changed amounts or taxesChange only non-amount content
10029822ENGINE_CANCEL_NOT_ALLOWEDThe current status does not allow cancellationDo not retry
10029823ENGINE_SERIE_EXHAUSTEDDevice series numbers used upDeactivate 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
10029824ENGINE_PLATFORM_UNREACHABLEAn operation that needs the network (pairing) cannot reach the platformCheck the network and retry
10029825ENGINE_ACTIVATION_CODE_INVALIDPairing code format, signature or validity is wrongManual action: generate a new pairing code
10029826ENGINE_ACTIVATION_HOST_UNTRUSTEDThe pairing code points to an untrusted platform addressManual action: confirm where the code came from and the installer environment (testing / production)
10029827ENGINE_KEY_PROTECTION_FAILEDThe data directory comes from another computer or another Windows userManual action: run on the original computer and user, or pair again
10029828ENGINE_DATA_DIR_LOCKEDThe data directory is in use by another process, including, when restoring a backup, an instance of this program on which Encerrar has not been calledClose the other instance; call Encerrar before restoring a backup
10029829ENGINE_LOCAL_STORE_CORRUPTEDLocal store inconsistentManual action: do not delete the data directory, contact the platform
10029830ENGINE_PROTOCOL_VERSION_UNSUPPORTEDSDK and runtime versions are incompatibleUpgrade the SDK and the runtime together
10029831ENGINE_RUNTIME_START_FAILEDThe runtime failed to startCheck that the runtime directory is complete and not blocked by antivirus software
10029832ENGINE_RUNTIME_CRASHEDThe runtime exited unexpectedlyRetry; with automatic restart on, the SDK recovers by itself; resend issuances with the same id
10029833ENGINE_TIMEOUTTimed out waitingResend the issuance with the same id, or call Consultar first
10029834ENGINE_SHUTTING_DOWNShutting down or already shut downCall Iniciar again
10029835ENGINE_IN_PROCESS_UNSUPPORTEDJava in-process mode requires Java 21 or laterUse subprocess mode
10029836ENGINE_INTERNAL_ERRORInternal core error; the message carries a reference numberContact the platform with the reference number and the logs
10029837ENGINE_ALREADY_ACTIVATEDThe company is already paired in this data directoryNo need to pair again; to change devices, deactivate the old one first
10029838ENGINE_PLATFORM_RESPONSE_UNTRUSTEDPlatform response failed verification; the previous data was keptRetried automatically later; if it persists, check whether a network proxy is rewriting responses
10029839ENGINE_ACTIVATION_PERSIST_FAILEDPaired on the platform but local saving failedPair again with the same pairing code
10029840ENGINE_CONFIG_INVALIDInvalid initialization configurationFix the configuration
10029841ENGINE_AUTHORIZED_XML_UNAVAILABLEAuthorized XML not available: not authorized yet, or not on this machine and cannot be fetched from the platformIf not authorized, fetch it after the authorization event; if authorized, the platform has not archived it yet or cannot be reached right now, so retry later
10029842ENGINE_LOCAL_STORE_NEWER_VERSIONThe local store is newer than the current core: the data directory was used by a newer SDK version, so startup is refusedUpgrade the SDK and the runtime to at least the version used last time; never delete the data directory
10029843ENGINE_CANCEL_XML_UNAVAILABLECancellation XML not available: the invoice is not cancelled, or it is not on this machine and cannot be fetched from the platformIf not cancelled, fetch it after CANCELAMENTO_CONCLUIDO; if cancelled, retry later
10029844ENGINE_EXPORT_FAILEDFailed to write the file: the export or backup target cannot be written, or the backup file already existsChange the directory or file name; check disk space and permissions
10029845ENGINE_SUBSTITUTE_KEY_INVALIDInvalid substitute key for cancellation by substitution, or not an offline invoice of this machine and this company that was not refusedPass the 44-digit access key of the offline invoice this machine issued for the same sale
10029846ENGINE_BACKUP_INVALIDThe backup cannot be restored: wrong passphrase, or the backup file was altered, is corrupted or is not a backup of this SDKCheck the passphrase; use an intact backup. The original store was not changed
10029870ENGINE_PROTOCOL_INVALID_JSONThe runtime received a message that is not valid JSONSDK wrapper defect; upgrade the SDK
10029871ENGINE_PROTOCOL_LINE_TOO_LONGA single message exceeds 8 MBRequest too large; split the item lines
10029872ENGINE_PROTOCOL_MESSAGE_INVALIDInvalid message structureSDK wrapper defect; upgrade the SDK
10029873ENGINE_METHOD_UNKNOWNThe runtime does not know the methodThe SDK is newer than the runtime; upgrade the runtime
10029874ENGINE_PARAMS_INVALIDParameter missing or of the wrong type; Detalhes.campo names the parameterFix the parameter, for example a request that is not a JSON object, the certificate thumbprint format or the date format
10029875ENGINE_ALREADY_STARTEDInitialized twice, or the backup restore protocol method called on a runtime connection that has already run IniciarDoes not happen in normal use of the wrappers; if it does, it is an SDK wrapper defect, upgrade the SDK. When integrating directly with the runtime protocol, call Encerrar and restore over a new connection
10029876ENGINE_REQUEST_ID_DUPLICATEDThe same call is still in progressSDK wrapper defect; upgrade the SDK
10029877ENGINE_RUNTIME_NOT_FOUNDRuntime not foundCheck the installer and the runtime directory
10029878ENGINE_TOO_MANY_PENDINGMore than 64 calls waiting at the same timeReduce concurrency
10029879ENGINE_RESPONSE_TOO_LARGEA single response exceeds the limitContact the platform
10029880ENGINE_PRINCIPAL_UNREACHABLEThe secondary cannot reach the primary; the request did not get thereRetry later, or move the till to the backup machine
10029881ENGINE_PRINCIPAL_RESULT_UNKNOWNThe request reached the primary but no response came back; the result is unknownAfter the primary recovers, call Consultar with the same id; resending Emitir with the same id and content does not issue twice
10029882ENGINE_TERMINAL_TOKEN_INVALIDThe terminal token of the secondary is invalid or revokedCall CriarTerminal again on the primary and update the secondary's TokenTerminal
10029883ENGINE_PRINCIPAL_ADDRESS_INVALIDThe primary address is badly formatted or not a private local network addressFix EnderecoPrincipal
10029884ENGINE_MODE_METHOD_UNAVAILABLEThe current mode does not offer this methodPairing, certificate change, backup and export run on the primary; terminal management is primary only
10029885ENGINE_PRINCIPAL_REJECTEDThe primary rejected the request source, for example a secondary outside the allowed networksCheck the primary's RedesPermitidas and the network
10029886ENGINE_PRINCIPAL_RATE_LIMITEDToo many failed authentications; rate-limited by the primaryCheck the token and retry after 1 minute
10029887ENGINE_PRINCIPAL_LISTEN_FAILEDThe local network port of the primary cannot be openedChange PortaPrincipal or free the port
10029888ENGINE_TERMINAL_NOT_FOUNDThe terminal to revoke does not existCheck the terminal id with ListarTerminais

All codes, including the Invoice Assistant ones, are in Error codes.