### Configure Java-NFe Library Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt Initializes the Java-NFe library by creating a ConfiguracoesNfe object. This object requires the digital certificate, state, environment, and schemas path. Optional configurations include setting timeouts, proxy details, enabling contingency mode, and specifying retry attempts. This configuration is essential for all subsequent NFe operations. ```java import br.com.swconsultoria.certificado.Certificado; import br.com.swconsultoria.certificado.CertificadoService; import br.com.swconsultoria.nfe.dom.ConfiguracoesNfe; import br.com.swconsultoria.nfe.dom.enuns.AmbienteEnum; import br.com.swconsultoria.nfe.dom.enuns.EstadosEnum; // Load digital certificate from PFX file Certificado certificado = CertificadoService.certificadoPfx( "/path/to/certificate.pfx", "certificatePassword" ); // Create configuration with default timezone (America/Sao_Paulo) ConfiguracoesNfe config = ConfiguracoesNfe.criarConfiguracoes( EstadosEnum.SP, // Issuer state/UF AmbienteEnum.HOMOLOGACAO, // HOMOLOGACAO or PRODUCAO certificado, // Digital certificate "/path/to/schemas" // Schemas folder path ); // Optional: Configure timeout (milliseconds) config.setTimeout(30000); // Optional: Configure proxy for corporate networks Proxy proxy = new Proxy(); proxy.setHost("proxy.company.com"); proxy.setPorta(8080); proxy.setUsuario("username"); proxy.setSenha("password"); config.setProxy(proxy); // Optional: Enable contingency mode (SVC) config.setContigenciaSVC(true); // Optional: Set retry attempts (default is 3) config.setRetry(5); // Configuration is now ready for use ``` -------------------------------- ### Download NFe Documents as Recipient (Java) Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt Demonstrates how to download NFe XML documents for a recipient using their CNPJ/CPF. It supports querying by NSU for multiple documents or by access key for a single NFe. Requires NFe library configuration and handles compressed XML. ```java import br.com.swconsultoria.nfe.Nfe; import br.com.swconsultoria.nfe.dom.enuns.ConsultaDFeEnum; import br.com.swconsultoria.nfe.dom.enuns.PessoaEnum; import br.com.swconsultoria.nfe.schema.retdistdfeint.RetDistDFeInt; import br.com.swconsultoria.nfe.util.XmlNfeUtil; try { // Download by NSU (Sequential Unique Number) RetDistDFeInt retorno = Nfe.distribuicaoDfe( config, PessoaEnum.JURIDICA, // JURIDICA (CNPJ) or FISICA (CPF) "10732644000128", // Recipient CNPJ/CPF ConsultaDFeEnum.NSU, // Query type: NSU or CHAVE "000000000000001" // NSU number ); // Alternative: Download by specific NFe access key // RetDistDFeInt retorno = Nfe.distribuicaoDfe( // config, // PessoaEnum.JURIDICA, // "10732644000128", // ConsultaDFeEnum.CHAVE, // "52200237874385000126550020000447071000447081" // NFe access key // ); // Display status System.out.println("Status: " + retorno.getCStat() + " - " + retorno.getXMotivo()); System.out.println("Environment: " + retorno.getTpAmb()); System.out.println("Last NSU: " + retorno.getUltNSU()); System.out.println("Max NSU: " + retorno.getMaxNSU()); // Process downloaded documents if (retorno.getLoteDistDFeInt() != null) { retorno.getLoteDistDFeInt().getDocZip().forEach(docZip -> { try { // Documents are compressed - decompress them byte[] xmlBytes = docZip.getValue(); String xml = XmlNfeUtil.gZipToXml(xmlBytes); System.out.println("NSU: " + docZip.getNSU()); System.out.println("Schema: " + docZip.getSchema()); System.out.println("Document Length: " + xml.length()); // Process XML based on schema type if ("procNFe_v4.00.xsd".equals(docZip.getSchema())) { // This is a complete NFe with authorization protocol System.out.println("Type: Complete NFe"); // Save or process NFe XML } else if ("resNFe_v1.01.xsd".equals(docZip.getSchema())) { // This is a summary of NFe System.out.println("Type: NFe Summary"); } else if ("procEventoNFe_v1.00.xsd".equals(docZip.getSchema())) { // This is an event (cancellation, CCe, etc.) System.out.println("Type: NFe Event"); } System.out.println("---"); } catch (Exception e) { System.err.println("Error processing document: " + e.getMessage()); } }); } } catch (NfeException e) { System.err.println("Distribution error: " + e.getMessage()); } // Expected successful output: // Status: 138 - Documento localizado // Environment: 2 // Last NSU: 000000000000015 // Max NSU: 000000000000020 // NSU: 000000000000015 // Schema: procNFe_v4.00.xsd // Document Length: 8543 // Type: Complete NFe // --- ``` -------------------------------- ### XML Conversion and Manipulation with Java NFe Utilities Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt Demonstrates how to convert XML strings to Java objects and vice versa using XmlNfeUtil. It also shows how to create NFe process documents, format dates, read XML from files, extract specific tags, and decompress GZip content. Requires the br.com.swconsultoria.nfe library. ```java import br.com.swconsultoria.nfe.util.XmlNfeUtil; import br.com.swconsultoria.nfe.schema_4.enviNFe.TEnviNFe; import br.com.swconsultoria.nfe.schema_4.enviNFe.TRetEnviNFe; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; try { // Convert XML string to Java object String xmlString = "..."; TRetEnviNFe retorno = XmlNfeUtil.xmlToObject(xmlString, TRetEnviNFe.class); System.out.println("Status: " + retorno.getCStat()); // Convert Java object to XML string TEnviNFe enviNFe = new TEnviNFe(); // ... populate enviNFe String xml = XmlNfeUtil.objectToXml(enviNFe); System.out.println("XML Length: " + xml.length()); // Convert with custom encoding String xmlIso = XmlNfeUtil.objectToXml(enviNFe, StandardCharsets.ISO_8859_1); // Create NFe process document (NFe + authorization protocol) // This creates the final XML for storage with both NFe and protocol String nfeProc = XmlNfeUtil.criaNfeProc(enviNFe, retorno.getProtNFe()); System.out.println("Process NFe created"); // Format date for NFe (default timezone America/Sao_Paulo) LocalDateTime dataEmissao = LocalDateTime.now(); String dataFormatada = XmlNfeUtil.dataNfe(dataEmissao); System.out.println("Formatted Date: " + dataFormatada); // Output format: 2025-01-15T10:30:00-03:00 // Read XML from file String xmlArquivo = XmlNfeUtil.leXml("/path/to/nfe.xml"); System.out.println("XML read from file: " + xmlArquivo.length() + " bytes"); // Extract specific tag from XML String xmlCompleto = "12345"; String chave = XmlNfeUtil.getTag(xmlCompleto, "chNFe"); System.out.println("Extracted Key: " + chave); // Output: 12345 // Decompress GZip content to XML (for DFe distribution) byte[] gzipContent = /* byte array from DFe distribution */; String xmlDescompactado = XmlNfeUtil.gZipToXml(gzipContent); System.out.println("Decompressed XML length: " + xmlDescompactado.length()); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } catch (Exception e) { System.err.println("XML processing error: " + e.getMessage()); } // Expected output: // Status: 100 // XML Length: 3245 // Process NFe created // Formatted Date: 2025-01-15T10:30:00-03:00 // XML read from file: 8543 bytes // Extracted Key: 12345 // Decompressed XML length: 12456 ``` -------------------------------- ### Query Taxpayer Registration Info (Java) Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt This Java code snippet demonstrates how to query taxpayer registration details (company name, CNPJ/CPF, state registration, address) from the SEFAZ database. It utilizes the br.com.swconsultoria.nfe library and requires configuration details, a tax ID (CNPJ or CPF), and the relevant state for the query. The output includes validation status and detailed registration information. ```java import br.com.swconsultoria.nfe.Nfe; import br.com.swconsultoria.nfe.dom.enuns.EstadosEnum; import br.com.swconsultoria.nfe.dom.enuns.PessoaEnum; import br.com.swconsultoria.nfe.schema.consCad.TRetConsCad; import br.com.swconsultoria.nfe.util.RetornoUtil; try { // Query CNPJ registration TRetConsCad retorno = Nfe.consultaCadastro( config, PessoaEnum.JURIDICA, // JURIDICA (CNPJ) or FISICA (CPF) "30081357000617", // CNPJ or CPF number EstadosEnum.GO // State to query ); // Validate response RetornoUtil.validaConsultaCadastro(retorno); // Display status System.out.println("Status: " + retorno.getInfCons().getCStat() + " - " + retorno.getInfCons().getXMotivo()); System.out.println(); // Display registration data (may contain multiple registrations) retorno.getInfCons().getInfCad().forEach(cadastro -> { System.out.println("Company Name: " + cadastro.getXNome()); System.out.println("CNPJ: " + cadastro.getCNPJ()); System.out.println("State Registration (IE): " + cadastro.getIE()); System.out.println("Status: " + cadastro.getCSit()); // Address information if (cadastro.getEnder() != null) { System.out.println("Address: " + cadastro.getEnder().getXLgr() + ", " + cadastro.getEnder().getNro()); System.out.println("District: " + cadastro.getEnder().getXBairro()); System.out.println("City: " + cadastro.getEnder().getXMun()); System.out.println("State: " + cadastro.getEnder().getUF()); System.out.println("ZIP: " + cadastro.getEnder().getCEP()); } System.out.println("---"); }); } catch (NfeException e) { System.err.println("Query error: " + e.getMessage()); } ``` -------------------------------- ### Sign NFe XML Documents with Java-NFe Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt This Java code snippet demonstrates how to digitally sign NFe XML documents using the Assinar.assinaNfe method from the br.com.swconsultoria.nfe library. It handles different signature types (NFE, INUTILIZACAO, EVENTO) and includes error handling for common issues like invalid certificates or XML structure. The library automatically manages certificate loading, private key extraction, and XML signature generation. ```java import br.com.swconsultoria.nfe.Assinar; import br.com.swconsultoria.nfe.dom.enuns.AssinaturaEnum; import br.com.swconsultoria.nfe.exception.NfeException; try { // Read unsigned XML String xmlNaoAssinado = ""; // Sign NFe document String xmlAssinadoNFe = Assinar.assinaNfe( config, xmlNaoAssinado, AssinaturaEnum.NFE // Signature type ); System.out.println("NFe signed successfully"); System.out.println("Signature Length: " + xmlAssinadoNFe.length()); // Sign invalidation document String xmlInutilizacao = "..."; String xmlInutAssinado = Assinar.assinaNfe( config, xmlInutilizacao, AssinaturaEnum.INUTILIZACAO ); System.out.println("Invalidation signed successfully"); // Sign event document (cancellation, CCe, manifestation, etc.) String xmlEvento = "..."; String xmlEventoAssinado = Assinar.assinaNfe( config, xmlEvento, AssinaturaEnum.EVENTO ); System.out.println("Event signed successfully"); // The library automatically handles: // - Certificate loading from config // - Private key extraction // - XML Signature generation with SHA-256 and RSA // - Signature element insertion at correct location // - Namespace handling } catch (NfeException e) { System.err.println("Signature error: " + e.getMessage()); // Common errors: // - Invalid certificate // - Certificate expired // - Invalid XML structure // - Missing ID attribute in element to be signed } // Available signature types (AssinaturaEnum): // - NFE: for NFe documents (signs element) // - INUTILIZACAO: for invalidation (signs element) // - EVENTO: for events (signs element) // Expected output: // NFe signed successfully // Signature Length: 15243 // Invalidation signed successfully // Event signed successfully ``` -------------------------------- ### Generate NFCe QRCode URL in Java Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt Generates the QRCode URL required for NFCe (consumer electronic invoice) for both online (V3) and contingency (offline) versions. The online version is recommended for real-time verification, while the contingency version is used when online access is unavailable. It requires the NFCe access key, environment type, state QRCode URL, and optionally emission date/time, total value, recipient details, and a certificate for HMAC signature. ```java import br.com.swconsultoria.nfe.util.NFCeUtil; import br.com.swconsultoria.certificado.Certificado; import java.security.NoSuchAlgorithmException; try { // Online NFCe QRCode (Version 3 - recommended) String qrCodeOnline = NFCeUtil.getCodeQRCodeV3( "52250810732644000128650010000094071716409173", // NFCe access key "2", // Environment: 1=production, 2=homologation "https://nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode" // State QRCode URL ); System.out.println("Online QRCode URL:"); System.out.println(qrCodeOnline); // This URL should be encoded in QRCode image on DANFE // Contingency NFCe QRCode (offline - requires signature) String qrCodeContingency = NFCeUtil.getCodeQRCodeContingenciaV3( "52250810732644000128650010000094071716409173", // NFCe access key "2", // Environment "2025-01-15T10:30:00-03:00", // Emission date (ISO format) "150.00", // NFCe total value "1", // Recipient type: 1=CNPJ, 2=CPF, null=unidentified "12345678901234", // Recipient CNPJ/CPF "https://nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode", certificado // Certificate for HMAC signature ); System.out.println("\nContingency QRCode URL:"); System.out.println(qrCodeContingency); // Generate CSRT hash (for NFCe with technical responsible) String chave = "52250810732644000128650010000094071716409173"; String csrt = "G8063VRTNDMO886B6HNIN5S2HESE"; byte[] hash = NFCeUtil.geraHashCSRT(chave, csrt); String hashHex = bytesToHex(hash); System.out.println("\nCSRT Hash: " + hashHex); } catch (NoSuchAlgorithmException e) { System.err.println("Hash generation error: " + e.getMessage()); } catch (Exception e) { System.err.println("QRCode generation error: " + e.getMessage()); } // Helper method to convert bytes to hex private static String bytesToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02X", b)); } return sb.toString(); } // Expected output: // Online QRCode URL: // https://nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode?chNFe=52250810732644000128650010000094071716409173&tpAmb=2 // // Contingency QRCode URL: // https://nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode?chNFe=52250810732644000128650010000094071716409173&tpAmb=2&dhEmi=323031352D30312D31355431303A33303A30302D30333A3030&vNF=150.00&vICMS=&digVal=&cIdToken=&cHashQRCode=ABCD1234... // // CSRT Hash: A1B2C3D4E5F6... ``` -------------------------------- ### Java NFe Recipient Manifestation - Confirm Operation Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt This snippet shows how to use the NFe library to confirm an operation for a received NFe. It requires the NFe access key, recipient's CNPJ, event timestamp, and the manifestation type. The output includes the event status and protocol number. Dependencies include the NFe library and Java's LocalDateTime. ```java import br.com.swconsultoria.nfe.Nfe; import br.com.swconsultoria.nfe.dom.Evento; import br.com.swconsultoria.nfe.dom.enuns.ManifestacaoEnum; import br.com.swconsultoria.nfe.schema.envEventoCancNFe.TEnvEvento; import br.com.swconsultoria.nfe.schema.envEventoCancNFe.TRetEnvEvento; import br.com.swconsultoria.nfe.util.ManifestacaoUtil; import br.com.swconsultoria.nfe.util.RetornoUtil; import br.com.swconsultoria.nfe.exception.NfeException; import java.time.LocalDateTime; try { // Create manifestation event - Confirm Operation Evento manifesta = new Evento(); manifesta.setChave("52200237874385000126550020000447071000447081"); manifesta.setCnpj("10732644000128"); // Recipient CNPJ manifesta.setDataEvento(LocalDateTime.now()); manifesta.setTipoManifestacao(ManifestacaoEnum.CONFIRMACAO_DA_OPERACAO); // Build manifestation event TEnvEvento enviEvento = ManifestacaoUtil.montaManifestacao(manifesta, config); // Send manifestation to SEFAZ TRetEnvEvento retorno = Nfe.manifestacao( config, enviEvento, false // Skip validation (manifestation schemas may vary) ); // Validate manifestation response RetornoUtil.validaManifestacao(retorno); // Display results retorno.getRetEvento().forEach(resultado -> { System.out.println("Access Key: " + resultado.getInfEvento().getChNFe()); System.out.println("Status: " + resultado.getInfEvento().getCStat() + " - " + resultado.getInfEvento().getXMotivo()); System.out.println("Event Type: " + resultado.getInfEvento().getTpEvento()); System.out.println("Protocol: " + resultado.getInfEvento().getNProt()); }); // Create proc event for storage String proc = ManifestacaoUtil.criaProcEventoManifestacao( config, enviEvento, retorno.getRetEvento().get(0) ); } catch (NfeException e) { System.err.println("Manifestation error: " + e.getMessage()); } // Manifestation types available: // - CONFIRMACAO_DA_OPERACAO (210200): Confirm operation occurred // - CIENCIA_DA_OPERACAO (210210): Acknowledge receipt of NFe // - DESCONHECIMENTO_DA_OPERACAO (210220): Unknown operation // - OPERACAO_NAO_REALIZADA (210240): Operation not performed (requires justification) // Expected successful output: // Access Key: 52200237874385000126550020000447071000447081 // Status: 135 - Evento registrado e vinculado a NF-e // Event Type: 210200 // Protocol: 135250000345678 ``` -------------------------------- ### Generate NFe Access Key in Java Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt Generates the 44-digit access key for NFe/NFCe, including check digit calculation. This key uniquely identifies each electronic invoice. It requires parameters such as issuer state, CNPJ, model, series, sequence number, emission type, random code, and emission date/time. ```java import br.com.swconsultoria.nfe.dom.enuns.EstadosEnum; import br.com.swconsultoria.nfe.util.ChaveUtil; import java.time.LocalDateTime; // Generate NFe access key ChaveUtil chaveUtil = new ChaveUtil( EstadosEnum.GO, // Issuer state "10732644000128", // Issuer CNPJ "55", // Model: 55 (NFe) or 65 (NFCe) 1, // Series number 92752, // NFe sequential number "1", // Emission type: 1=normal, 9=contingency "96044696", // Random code (8 digits) LocalDateTime.of(2025, 1, 15, 10, 30) // Emission date/time ); // Get complete access key with "NFe" prefix String chaveCompleta = chaveUtil.getChaveNF(); System.out.println("Complete Key: " + chaveCompleta); // Get only the check digit String digito = chaveUtil.getDigitoVerificador(); System.out.println("Check Digit: " + digito); // Extract components from key // Format: UF(2) + AAMM(4) + CNPJ(14) + MOD(2) + SERIE(3) + NNF(9) + TPEMIS(1) + CNF(8) + DV(1) System.out.println("Key Length: " + chaveCompleta.length()); System.out.println("Key without prefix: " + chaveCompleta.substring(3)); // Utility method for padding numbers String paddedNumber = ChaveUtil.completarComZerosAEsquerda("123", 9); System.out.println("Padded: " + paddedNumber); // Output: 000000123 // Expected output: // Complete Key: NFe52250110732644000128550010000927529604469673 // Check Digit: 3 // Key Length: 47 // Key without prefix: 52250110732644000128550010000927529604469673 // Padded: 000000123 ``` -------------------------------- ### Cancel Authorized NFe Document with Java Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt This snippet demonstrates how to cancel an authorized NFe document using the NFe library. It requires the NFe access key, authorization protocol, and a justification of at least 15 characters. Cancellation must be done within 24 hours of authorization. The output includes the status of the cancellation event. ```java import br.com.swconsultoria.nfe.Nfe; import br.com.swconsultoria.nfe.dom.Evento; import br.com.swconsultoria.nfe.dom.enuns.DocumentoEnum; import br.com.swconsultoria.nfe.schema.envEventoCancNFe.TEnvEvento; import br.com.swconsultoria.nfe.schema.envEventoCancNFe.TRetEnvEvento; import br.com.swconsultoria.nfe.util.CancelamentoUtil; import br.com.swconsultoria.nfe.util.RetornoUtil; import java.time.LocalDateTime; try { // Create cancellation event data Evento cancela = new Evento(); cancela.setChave("52250810732644000128650010000094071716409173"); cancela.setProtocolo("152250026070344"); cancela.setCnpj("10732644000128"); cancela.setMotivo("Commercial error - incorrect values on invoice"); cancela.setDataEvento(LocalDateTime.now()); // Build cancellation event XML TEnvEvento enviEvento = CancelamentoUtil.montaCancelamento(cancela, config); // Send cancellation to SEFAZ TRetEnvEvento retorno = Nfe.cancelarNfe( config, enviEvento, true, // Validate XML before sending DocumentoEnum.NFCE // Document type (NFE or NFCE) ); // Validate cancellation response RetornoUtil.validaCancelamento(retorno); // Display results retorno.getRetEvento().forEach(resultado -> { System.out.println("Access Key: " + resultado.getInfEvento().getChNFe()); System.out.println("Status: " + resultado.getInfEvento().getCStat() + " - " + resultado.getInfEvento().getXMotivo()); System.out.println("Protocol: " + resultado.getInfEvento().getNProt()); System.out.println("Event Date: " + resultado.getInfEvento().getDhRegEvento()); }); // Create proc event XML for storage String procEvento = CancelamentoUtil.criaProcEventoCancelamento( config, enviEvento, retorno.getRetEvento().get(0) ); // Save procEvento to file system // Files.write(Paths.get("/storage/proc/cancellation.xml"), procEvento.getBytes()); } catch (NfeException e) { System.err.println("Cancellation error: " + e.getMessage()); } ``` -------------------------------- ### Validate NFe Responses with RetornoUtil in Java Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt Validates various NFe operation responses (submission, receipt query, cancellation, CCe, manifestation) by checking status codes. It distinguishes between asynchronous and synchronous processing. Errors are caught as NfeException, providing detailed messages. Dependencies include NFe library classes like RetornoUtil, TRetEnviNFe, TRetConsReciNFe, TRetEnvEvento, and NfeException. ```java import br.com.swconsultoria.nfe.util.RetornoUtil; import br.com.swconsultoria.nfe.schema_4.enviNFe.TRetEnviNFe; import br.com.swconsultoria.nfe.schema_4.consReciNFe.TRetConsReciNFe; import br.com.swconsultoria.nfe.schema.envEventoCancNFe.TRetEnvEvento; import br.com.swconsultoria.nfe.exception.NfeException; try { // Check if NFe submission is asynchronous or synchronous TRetEnviNFe retornoEnvio = /* from Nfe.enviarNfe() */; if (RetornoUtil.isRetornoAssincrono(retornoEnvio)) { System.out.println("Asynchronous processing - query receipt"); // For asynchronous: validate receipt query TRetConsReciNFe retornoRecibo = /* from Nfe.consultaRecibo() */; RetornoUtil.validaAssincrono(retornoRecibo); System.out.println("Receipt validation successful"); } else { // For synchronous: validate immediate response RetornoUtil.validaSincrono(retornoEnvio); System.out.println("Synchronous validation successful"); } // Validate contingency transmission // RetornoUtil.validaSincronoTrasmissaoContingencia(retornoEnvio); // Validate cancellation event TRetEnvEvento retornoCancelamento = /* from Nfe.cancelarNfe() */; RetornoUtil.validaCancelamento(retornoCancelamento); System.out.println("Cancellation validation successful"); // Validate substitution cancellation (NFCe) // RetornoUtil.validaCancelamentoSubstituicao(retornoCancelamento); // Validate correction letter TRetEnvEvento retornoCCe = /* from Nfe.cce() */; RetornoUtil.validaCartaCorrecao(retornoCCe); System.out.println("CCe validation successful"); // Validate manifestation TRetEnvEvento retornoManifestacao = /* from Nfe.manifestacao() */; RetornoUtil.validaManifestacao(retornoManifestacao); System.out.println("Manifestation validation successful"); // Validate EPEC (emergency prior event) // RetornoUtil.validaEpec(retornoEpec); // Validate invalidation // RetornoUtil.validaInutilizacao(retornoInutilizacao); // Validate registration query // RetornoUtil.validaConsultaCadastro(retornoCadastro); } catch (NfeException e) { // Exception contains detailed error information System.err.println("Validation failed: " + e.getMessage()); // Error messages typically in format: "code - description" // Example: "217 - NF-e nao consta na base de dados da SEFAZ" } // Successful validations produce no output (void methods) // Failures throw NfeException with descriptive error messages // Common error codes: // - 100: Authorized // - 135: Event registered and linked // - 217: NFe not found in database // - 539: Event already registered // - 573: Duplicate event rejection ``` -------------------------------- ### Check SEFAZ Web Service Status Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt Verifies the availability and operational status of the SEFAZ web service for NFe operations. This health check is recommended before initiating invoice processing to prevent transmission failures. It retrieves status code, message, state, and environment information, confirming if the service is operational (status code 107). ```java import br.com.swconsultoria.nfe.Nfe; import br.com.swconsultoria.nfe.dom.enuns.DocumentoEnum; import br.com.swconsultoria.nfe.schema_4.consStatServ.TRetConsStatServ; try { // Check NFe web service status TRetConsStatServ retorno = Nfe.statusServico(config, DocumentoEnum.NFE); // Display status information System.out.println("Status Code: " + retorno.getCStat()); System.out.println("Message: " + retorno.getXMotivo()); System.out.println("State: " + retorno.getCUF()); System.out.println("Environment: " + retorno.getTpAmb()); // Check if service is operational (code 107) if ("107".equals(retorno.getCStat())) { System.out.println("Service is operational"); } } catch (NfeException e) { System.err.println("Error checking service: " + e.getMessage()); } ``` -------------------------------- ### Issue Correction Letter (CCe) for NFe in Java Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt Creates and submits a correction letter event to fix non-fiscal errors on an authorized NFe. The correction letter can only modify descriptive information such as addresses, product descriptions, and transport details. Multiple corrections can be issued with sequential numbering (1, 2, 3, etc.). The response includes the access key, status code, protocol number, and sequence number. ```java import br.com.swconsultoria.nfe.Nfe; import br.com.swconsultoria.nfe.dom.Evento; import br.com.swconsultoria.nfe.schema.envcce.TEnvEvento; import br.com.swconsultoria.nfe.schema.envcce.TRetEnvEvento; import br.com.swconsultoria.nfe.util.CartaCorrecaoUtil; import br.com.swconsultoria.nfe.util.RetornoUtil; import java.time.LocalDateTime; try { // Create correction letter event Evento cce = new Evento(); cce.setChave("52250810732644000128550010000927501960446967"); cce.setCnpj("10732644000128"); cce.setMotivo("CORRECTION: Delivery address should be: Rua das Flores, 123, " + "Centro, Goiania-GO. Product description on item 1 should include " + "color specification: Blue. Transport volume weight corrected to 15kg."); cce.setDataEvento(LocalDateTime.now()); cce.setSequencia(1); // Sequential number (1 for first CCe, 2 for second, etc.) // Build CCe event XML TEnvEvento envEvento = CartaCorrecaoUtil.montaCCe(cce, config); // Send CCe to SEFAZ TRetEnvEvento retorno = Nfe.cce( config, envEvento, true // Validate XML before sending ); // Validate CCe response RetornoUtil.validaCartaCorrecao(retorno); // Display results retorno.getRetEvento().forEach(resultado -> { System.out.println("Access Key: " + resultado.getInfEvento().getChNFe()); System.out.println("Status: " + resultado.getInfEvento().getCStat() + " - " + resultado.getInfEvento().getXMotivo()); System.out.println("Protocol: " + resultado.getInfEvento().getNProt()); System.out.println("Sequence: " + cce.getSequencia()); }); // Create proc event CCe for storage String procCCe = CartaCorrecaoUtil.criaProcEventoCCe(config, envEvento, retorno); // Save to file system // Files.write(Paths.get("/storage/proc/cce-seq-001.xml"), procCCe.getBytes()); } catch (NfeException e) { System.err.println("CCe error: " + e.getMessage()); } ``` -------------------------------- ### Invalidate NFe Number Range in Java Source: https://context7.com/samuel-oliveira/java_nfe/llms.txt This Java code snippet demonstrates how to invalidate a range of NFe numbers that will not be used. It requires a minimum 15-character justification and uses the swconsultoria/java_nfe library to interact with SEFAZ. The process involves creating an invalidation request, sending it, validating the response, and optionally creating a processed XML for storage. ```java import br.com.swconsultoria.nfe.Nfe; import br.com.swconsultoria.nfe.dom.enuns.DocumentoEnum; import br.com.swconsultoria.nfe.schema_4.inutNFe.TInutNFe; import br.com.swconsultoria.nfe.schema_4.inutNFe.TRetInutNFe; import br.com.swconsultoria.nfe.util.InutilizacaoUtil; import br.com.swconsultoria.nfe.util.RetornoUtil; import java.time.LocalDateTime; try { // Create invalidation request TInutNFe inutNFe = InutilizacaoUtil.montaInutilizacao( DocumentoEnum.NFCE, // Document type (NFE or NFCE) "10732644000128", // Issuer CNPJ 1, // Series number 243, // Initial number to invalidate 244, // Final number to invalidate "System error during numbering sequence - numbers reserved but not used", LocalDateTime.now(), config ); // Send invalidation to SEFAZ TRetInutNFe retorno = Nfe.inutilizacao( config, inutNFe, DocumentoEnum.NFCE, true // Validate XML before sending ); // Validate invalidation response RetornoUtil.validaInutilizacao(retorno); // Display results System.out.println("Status: " + retorno.getInfInut().getCStat() + " - " + retorno.getInfInut().getXMotivo()); System.out.println("State: " + retorno.getInfInut().getCUF()); System.out.println("Year: " + retorno.getInfInut().getAno()); System.out.println("CNPJ: " + retorno.getInfInut().getCNPJ()); System.out.println("Model: " + retorno.getInfInut().getMod()); System.out.println("Series: " + retorno.getInfInut().getSerie()); System.out.println("Initial Number: " + retorno.getInfInut().getNNFIni()); System.out.println("Final Number: " + retorno.getInfInut().getNNFFin()); System.out.println("Protocol: " + retorno.getInfInut().getNProt()); // Create proc invalidation XML for storage String proc = InutilizacaoUtil.criaProcInutilizacao(config, inutNFe, retorno); // Save to file system // Files.write(Paths.get("/storage/proc/inutilization.xml"), proc.getBytes()); } catch (NfeException e) { System.err.println("Invalidation error: " + e.getMessage()); } // Expected successful output: // Status: 102 - Inutilizacao de numero homologado // State: 52 // Year: 25 // CNPJ: 10732644000128 // Model: 65 // Series: 1 // Initial Number: 243 // Final Number: 244 // Protocol: 152250000456789 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.