FinOpenPOS
API Reference

API Reference

Classes

ClassDescription
AccessKeyImmutable 44-digit NF-e/NFC-e access key with component extraction methods.
ContingencyManages NF-e/NFC-e contingency mode activation and deactivation.
ConvertConverts SPED TXT representation of NF-e documents into XML.
ParserErrorError thrown when TXT parsing fails.
TaxIdImmutable wrapper for CPF or CNPJ with formatting and XML helpers.

Interfaces

InterfaceDescription
AccessKeyParamsAccess key components for NF-e/NFC-e
ArmaDataWeapon details (arma) -- inside prod, up to 500 per item
CepResultAddress result from a CEP (zip code) lookup.
CertificateDataCertificate loaded from PFX file
CertificateInfoCertificate info for display purposes
CofinsDataCOFINS tax input data. Monetary amounts in cents, rates as integer * 10000.
CofinsStDataCOFINS-ST (substituicao tributaria) input data.
CombustivelItemItem for fuel credit appropriation event
ConsumoItemItem for personal consumption destination event
ContingencyConfigContingency configuration data.
CreditoBensItemItem for goods and services credit appropriation event
CredPresumidoItemItem for deemed credit appropriation event
DFeReferenciadoDataReferenced DFe per item (DFeReferenciado) -- inside det, PL_010 schema
EpecNfceConfigConfiguration for EPEC NFC-e event building.
FiscalConfigFiscal configuration object structure.
FiscalSettingsFiscal settings from database (without raw PFX)
IcmsDataUnified input data for all ICMS variations. All monetary fields in cents; rate fields in hundredths or * 10000.
IcmsTotalsAccumulated ICMS totals across all items.
IiDataII (Imposto de Importacao) input data.
ImobilizacaoItemItem for asset immobilization event
ImportacaoZFMItemItem for ALC/ZFM import not converted to exemption event
InvoiceBuildDataData needed to build an invoice XML
InvoiceItemDataItem data for XML building
IpiDataIPI (Imposto sobre Produtos Industrializados) input data.
IsDataIS (Imposto Seletivo / IBS+CBS) input data -- PL_010 tax reform. Goes inside as an alternative/addition to ICMS.
IssqnDataISSQN (ISS - Imposto Sobre Servicos) input data. All monetary amounts in cents, rates as hundredths.
IssqnTotalsISSQN totals accumulator (mirrors PHP stdISSQNTot).
ItemNaoFornecidoItem for unfulfilled supply with prepayment event
MedDataMedicine details (med) -- inside prod
NfceQrCodeParamsParameters for building an NFC-e QR Code URL.
ObsItemDataPer-item observations (obsItem) -- inside det
PaymentDataPayment data for invoice
PerecimentoAdquirenteItemItem for perishment/loss/theft by acquirer event (FOB)
PerecimentoFornecedorItemItem for perishment/loss/theft by supplier event (CIF)
PisDataPIS tax input data. Monetary amounts in cents, rates as integer * 10000.
PisStDataPIS-ST (substituicao tributaria) input data.
PutQRTagParamsParameters for inserting QR Code into NFC-e XML.
RastroDataBatch tracking (rastro) -- up to 500 per item, inside prod
RetTribDataRetained taxes (retTrib) -- inside total
SefazReformConfigConfiguration for SEFAZ reform event builders
SefazResponseSEFAZ response after processing
TaxElementStructured representation of a tax XML element.
TaxFieldA single XML field: value
VeicProdDataVehicle details (veicProd) -- inside prod

Type Aliases

Type AliasDescription
ContingencyTypeContingency type for NF-e emission fallback
ContingencyTypeNameContingency type name: SVCAN, SVCRS, or empty (normal mode).
DestIdTypeDestination ID type (tp_idDest): 1=CNPJ, 2=CPF, 3=foreign, ""=none.
EmissionTypeEmission type (tpEmis): 1=normal, 6=SVC-AN, 7=SVC-RS, 9=offline contingency
InvoiceModelNF-e model: 55 = NF-e (B2B), 65 = NFC-e (consumer)
InvoiceStatusInvoice status lifecycle
QrCodeVersionQR Code version: 200 (v2) or 300 (v3, NT 2025.001).
SefazEnvironmentSEFAZ environment: 1 = production, 2 = homologation
SefazServiceSEFAZ web service names used for SOAP requests
TaxRegimeTax regime (CRT): 1=Simples Nacional, 2=Simples excess, 3=Normal

Variables

VariableDescription
C14N_ALGORITHMC14N canonicalization algorithm URI
ENVELOPED_SIGNATURE_TRANSFORMEnveloped signature transform URI
EVENT_TYPESEvent type constants matching PHP sped-nfe
IBGE_TO_UFIBGE numeric code -> UF abbreviation (reverse lookup).
LOCALStandard LOCAL TXT layout.
LOCAL_V12LOCAL v1.2 TXT layout.
LOCAL_V13LOCAL v1.3 TXT layout.
NFCE_QRCODE_URLSNFC-e QR Code base URLs per environment and state
NFE_NAMESPACENF-e XML namespace
NFE_PROC_NAMESPACENF-e process namespace (for procNFe wrapper)
NFE_VERSIONNF-e version (currently 4.00)
NFE_WSDL_NSSEFAZ NF-e WSDL base namespace
PAYMENT_TYPESDefault payment type codes (tPag) mapped by friendly name
SEBRAESEBRAE TXT layout.
SEFAZ_STATUSSEFAZ status codes (cStat) used across the fiscal module. These replace magic numbers scattered in invoice-service.ts, complement.ts, etc. Reference: Manual de Orientacao do Contribuinte (MOC) v7.0+
SOAP_ENVELOPE_NSSOAP envelope namespace for SEFAZ web service requests
STATE_IBGE_CODESUF abbreviation -> IBGE numeric code (cUF).
STRUCTURE_310TXT structure for NFe version 3.10.
STRUCTURE_400TXT structure for NFe version 4.00 (standard LOCAL layout).
STRUCTURE_400_SEBRAETXT structure for NFe version 4.00 (SEBRAE layout).
STRUCTURE_400_V12TXT structure for NFe version 4.00 (LOCAL v1.2 layout).
STRUCTURE_400_V13TXT structure for NFe version 4.00 (LOCAL v1.3 layout).
VALID_EVENT_STATUSESValid cStat values for cancellation and event responses. 135 = event registered, 136 = registered but unlinked, 155 = already cancelled.
VALID_PROTOCOL_STATUSESValid cStat values when attaching a protocol to a signed NFe (nfeProc). These statuses indicate the NFe was processed (authorized or denied) and the protocol can be attached.
XMLDSIG_NAMESPACEXML Digital Signature namespace

Functions

FunctionDescription
adjustNfeForContingencyAdjust NF-e XML for contingency mode.
attachB2BAttach a B2B financial tag to an authorized nfeProc XML. Wraps the nfeProc and B2B content in a <nfeProcB2B> element.
attachB2bTagBuild b2b tag for nfeProc.
attachCancellationAttach a cancellation event response to an authorized nfeProc XML. Appends the <retEvento> node inside the <nfeProc> wrapper.
attachEventProtocolAttach an event protocol response to the event request, producing the procEventoNFe wrapper.
attachInutilizacaoAttach the SEFAZ inutilizacao response to the request, producing the ProcInutNFe wrapper.
attachProtocolAttach the SEFAZ authorization protocol to a signed NFe XML, producing the nfeProc wrapper required for storage and DANFE.
buildAccessKeyBuild the access key (chave de acesso) -- 44 digits. Delegates to AccessKey.build(); kept for backward compatibility.
buildAccessKeyQueryXmlBuild access key query request XML (consSitNFe).
buildAceiteDebitotpEvento=211128 -- Debit acceptance in tax assessment
buildApropriacaoCreditoBenstpEvento=211150 -- Goods and services credit appropriation request
buildApropriacaoCreditoCombtpEvento=211140 -- Fuel credit appropriation request
buildAtualizacaoDataEntregatpEvento=112150 -- Update estimated delivery date
buildAuthorizationRequestXmlBuild the authorization request XML (envelope for sending an NF-e).
buildBatchEventXmlBuild batch event XML (generic, multiple events in one envelope).
buildBatchManifestationXmlBuild batch manifestation XML (multiple events in one envelope).
buildBatchSubmissionXmlBuild batch submission request XML (enviNFe).
buildCadastroQueryXmlBuild cadastro query request XML (ConsCad).
buildCancelaEventotpEvento=110001 -- Event cancellation (cancel a previously registered event)
buildCancellationEventXmlBuild cancellation event XML (using the generic event builder).
buildCancellationXmlBuild cancellation event XML.
buildCCeXmlBuild Carta de Correcao (CCe) event XML.
buildCofinsStXmlBuild COFINS-ST XML string (backward-compatible wrapper).
buildCofinsXmlBuild COFINS XML string (backward-compatible wrapper).
buildConciliacaoXmlBuild conciliation event XML.
buildCscXmlBuild CSC admin request XML (admCscNFCe).
buildDeliveryFailureCancellationXmlBuild delivery failure cancellation event XML.
buildDeliveryFailureXmlBuild delivery failure event XML (Insucesso na Entrega da NF-e).
buildDeliveryProofCancellationXmlBuild delivery proof cancellation event XML.
buildDeliveryProofXmlBuild delivery proof event XML (Comprovante de Entrega da NF-e).
buildDestinoConsumoPessoaltpEvento=211120 -- Item destination for personal consumption
buildDistDFeQueryXmlBuild DFe distribution query XML (distDFeInt).
buildEpecNfceStatusXmlBuild consStatServ XML for EPEC NFC-e status check.
buildEpecNfceXmlBuild EPEC event XML for an NFC-e (model 65).
buildEpecStatusXmlBuild EPEC NFC-e status request XML (same as status but for EPEC service).
buildEventIdBuild an event ID: ID{tpEvento}{chNFe}{seqPadded}
buildEventXmlBuild a generic SEFAZ event XML (evento inside envEvento). This produces the unsigned inner evento XML. Signing is done separately.
buildExtensionCancellationXmlBuild ECPP (cancel extension request) event XML.
buildExtensionRequestXmlBuild EPP (extension request) event XML.
buildFornecimentoNaoRealizadotpEvento=112140 -- Unfulfilled supply with prepayment
buildIcmsPartXmlBuild the ICMSPart XML group (partition between states). Used inside <ICMS> for CST 10 or 90 with interstate partition.
buildIcmsStXmlBuild the ICMSST XML group (ST repasse). Used inside <ICMS> for CST 41 or 60 with interstate ST repasse.
buildIcmsUfDestXmlBuild the ICMSUFDest XML group (interstate to final consumer). This is a sibling of <ICMS>, placed directly inside <imposto>.
buildIcmsXmlBuild ICMS XML string (backward-compatible wrapper around calculateIcms).
buildIiXmlBuild II (import tax) XML string (backward-compatible wrapper).
buildImobilizacaoItemtpEvento=211130 -- Item immobilization (fixed asset registration)
buildImportacaoZFMtpEvento=112120 -- ALC/ZFM import not converted to exemption
buildImpostoDevolBuild impostoDevol XML string (backward-compatible wrapper).
buildInfoPagtoIntegraltpEvento=112110 -- Full payment confirmation event Ported from PHP TraitEventsRTC::sefazInfoPagtoIntegral()
buildInfoPagtoIntegralXmlBuild info pagamento integral event XML (tpEvento 112110).
buildInterestedActorXmlBuild Ator Interessado event XML.
buildInvoiceXmlBuild a complete NF-e or NFC-e XML (unsigned). The XML follows layout 4.00 as defined by MOC.
buildIpiXmlBuild IPI XML string (backward-compatible wrapper).
buildIssqnXmlBuild ISSQN XML string and accumulate totals (backward-compatible wrapper).
buildIsXmlBuild IS XML string (backward-compatible wrapper).
buildManifestacaoTransfCredCBStpEvento=212120 -- Manifestation on CBS credit transfer request
buildManifestacaoTransfCredIBStpEvento=212110 -- Manifestation on IBS credit transfer request
buildManifestationXmlBuild recipient manifestation event XML.
buildNfceConsultUrlBuild the NFC-e urlChave tag content for consulting the NFe by access key.
buildNfceQrCodeUrlBuild the NFC-e QR Code URL.
buildPisStXmlBuild PIS-ST XML string (backward-compatible wrapper).
buildPisXmlBuild PIS XML string (backward-compatible wrapper).
buildReceiptQueryXmlBuild receipt query request XML (consReciNFe).
buildRouboPerdaTransporteAdquirentetpEvento=211124 -- Perishment, loss, theft by acquirer (FOB)
buildRouboPerdaTransporteFornecedortpEvento=112130 -- Perishment, loss, theft by supplier (CIF)
buildSolApropCredPresumidotpEvento=211110 -- Deemed credit appropriation request
buildStatusRequestXmlBuild the status service request XML.
buildSubstitutionCancellationXmlBuild substitution cancellation event XML (for NFC-e model 65 only).
buildTestNfceXmlBuild a minimal NFC-e XML for testing EPEC.
buildVoidingXmlBuild number voiding (inutilizacao) request XML.
calculateCofinsCalculate COFINS tax element (domain logic, no XML).
calculateCofinsStCalculate COFINS-ST tax element (domain logic, no XML).
calculateIcmsCalculate ICMS for a single item (domain logic, no XML dependency). Returns structured TaxElement + accumulated totals.
calculateIiCalculate II (import tax) element (domain logic, no XML).
calculateImpostoDevolCalculate impostoDevol element (domain logic, no XML).
calculateIpiCalculate IPI tax element (domain logic, no XML).
calculateIsCalculate IS tax element (domain logic, no XML dependency). Three mutually exclusive modes based on which fields are present.
calculateIssqnCalculate ISSQN tax element and accumulate totals (domain logic, no XML).
calculatePisCalculate PIS tax element (domain logic, no XML).
calculatePisStCalculate PIS-ST tax element (domain logic, no XML).
checkRtcModelValidate that the model is 55 (NFe) and the access key also indicates model 55. RTC events only apply to model 55. Ported from PHP TraitEventsRTC::checkModel().
createIcmsTotalsCreate a zeroed-out ICMS totals object.
createIssqnTotalsCreate a zeroed-out ISSQN totals object.
defaultLotIdGenerate lot ID from explicit value or Date.now() fallback
escapeXmlEscape special XML characters in text content and attribute values
extractCertFromPfxExtract certificate PEM from PFX using openssl CLI (with -legacy flag).
extractKeyFromPfxExtract private key PEM from PFX using openssl CLI (with -legacy flag).
extractXmlTagValueExtract text content of a simple XML tag from a raw XML string
filterFieldsFilter null entries from a TaxField array
formatCentsFormat cents integer to decimal string. E.g. 1050 -> "10.50"
formatCentsOrNullFormat cents to decimal string, returning null for null/undefined input
formatCentsOrZeroFormat cents to decimal string, defaulting to "0.00" for null/undefined
formatDateTimeBRFormat a Date as ISO 8601 with Brazil timezone offset. SEFAZ rejects UTC "Z" suffix -- requires explicit offset like -03:00.
formatDecimalFormat a number with N decimal places
formatRateFormat rate stored as hundredths to decimal string. E.g. 1800 -> "18.0000"
formatRate4Format rate stored as value * 10000 to 4-decimal string. E.g. 16500 -> "1.6500"
formatRate4OrZeroFormat rate4 (value * 10000) to 4-decimal string, defaulting to "0.0000" for null/undefined
getCertificateInfoExtract certificate info for display (without exposing private key).
getContingencyTypeGet the contingency type for a given state.
getEventDescriptionMap event type to its description
getNfceConsultationUriGet the NFC-e consultation URI (urlChave) for a given state and environment. Used for QR Code and DANFCE consultation links.
getSefazUrlGet the SEFAZ web service URL for a given state, service, environment and model.
getStateByCodeGet the UF abbreviation for an IBGE numeric code.
getStateCodeGet the IBGE numeric code for a state abbreviation.
getStructureGet the appropriate structure for the given version and layout.
getStructureByVersionStringGet the appropriate structure for parsing, using a version string like "4.00" or "3.10".
isValidGtinValidate a GTIN-8/12/13/14 barcode number.
isValidTxtValidate a TXT representation of an NFe. Returns an empty array if valid, or an array of error strings if invalid.
loadCertificateLoad private key and certificate from a PFX/PKCS12 buffer.
loadStructureLoad the TXT structure definition for the given version and layout.
lookupCepLookup address by CEP using ViaCEP with BrasilAPI as fallback.
mergeIcmsTotalsMerge item-level ICMS totals into an accumulator.
optionalFieldHelper: create an optional field (returns null if value is nullish)
parseAuthorizationResponseParse authorization response (NfeAutorizacao / NfeRetAutorizacao).
parseCancellationResponseParse cancellation event response.
parseStatusResponseParse the SEFAZ service status response (NfeStatusServico).
putQRTagInsert QR Code and urlChave tags into a signed NFC-e XML.
requiredFieldHelper: create a required field (throws if value is nullish)
resolveVerAplicResolve verAplic: explicit > config > default "4.00"
sefazRequestSend a SOAP 1.2 request to a SEFAZ web service with mutual TLS (client certificate). Uses curl with PEM cert/key extracted from PFX, because Bun's node:https does not fully support mTLS with PFX (ECONNREFUSED on Agent with pfx option).
serializeTaxElementSerialize a TaxElement to an XML string.
signEventXmlSign a SEFAZ event XML (cancelamento, CCe, etc.) with XMLDSig. Same as signXml() but references inside .
signXmlSign an NF-e XML string with XMLDSig enveloped signature using xml-crypto. Covers with C14N canonicalization, SHA-1 digest, RSA-SHA1 signature.
tagBuild an XML tag with optional attributes and children.
toArrayConvert an NFe XML string to a plain object (like PHP's toArray).
toJsonConvert an NFe XML string to a JSON string.
toStdConvert an NFe XML string to a normalized object (like PHP's toStd). In TypeScript this is equivalent to toArray since we don't have stdClass.
validateValidate a fiscal configuration JSON string. Returns the parsed config object on success, throws on failure.
validateAccessKeyValidate access key format and throw if invalid.
whichIsIdentify which NFe document type an XML string represents.

References

STATE_CODES

Renames and re-exports STATE_IBGE_CODES

On this page