SEFAZ NF-e and NFC-e transport (modelos 55 and 65).
Does not calculate taxes. The ERP builds the XML; this library signs and talks to the official 4.00 webservices (and DistDFe 1.00 on the AN).
Every service is live over mTLS. The library signs, sends and parses; it
never composes an NF-e (AD-001), so authorize/1 takes the XML the ERP
built and returns it to SEFAZ byte for byte.
Summary
Functions
NFeRetAutorizacao4 for a receipt (n_rec).
Sign + NFeAutorizacao4. Does not mutate tax nodes once SOAP exists.
Event 110111, cancelling an authorized NF-e via NFeRecepcaoEvento4.
Event 110110, the Carta de Correção Eletrônica, via NFeRecepcaoEvento4.
NFeConsultaProtocolo4 by 44-digit access key.
NFeConsultaCadastro (CadConsultaCadastro4): the state taxpayer registry.
NFeDistribuicaoDFe on the Ambiente Nacional. Caller persists ult_nsu.
Event 110140, the EPEC (Evento Prévio de Emissão em Contingência), for an NF-e model 55.
Manifestação do destinatário for a document received through DistDFe.
NFeStatusServico4 for one UF.
Starts a DistDFe poller for one tax ID under SefazNfe.DistDFe.Supervisor.
NFeInutilizacao4, closing a range of NF-e numbers that was never used.
Functions
@spec authorization_result(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
NFeRetAutorizacao4 for a receipt (n_rec).
What an asynchronous authorize/1 leaves to be collected. cStat 105 means
the batch is still processing and the caller should ask again; 104 means it
finished, and the document's own outcome is read from the nested protocol.
:model (55 by default, or 65) selects the endpoints.
:signed_xml is optional: the signed NFe that was sent, which is
:signed_xml of the authorize/1 result. With it, and a protNFe of the same
key in the answer, the result's :xml is the nfeProc exactly as
authorize/1 builds it (SefazNfe.Proc.nfe_proc/2), so a document that was
authorized through a receipt ends up with the same legal file. The result
carries it back as :signed_xml. Without it nothing changes: :xml is nil.
A protNFe of another key, or one whose digest is not the document's, or one
that is not an authorization, leaves :xml as nil (the protocol is still in
the result).
The SOAP answer is in :response_xml; see SefazNfe.Result.
:contingency
Optional, :svc_an or :svc_rs: collect the receipt from that SVC instead of
the origin, for a batch that authorize/1 sent to it. Absent means the UF's
own authorizer, exactly as before. It must be the SVC that serves :uf, else
{:error, {:wrong_contingency, uf, svc}} naming the one that does; NFC-e has
no SVC ({:error, {:unsupported_for_model, 65}}). It is never inferred
(AD-005).
@spec authorize(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
Sign + NFeAutorizacao4. Does not mutate tax nodes once SOAP exists.
The document is :xml (the NF-e, signed or not) or :nfe, a map for
SefazNfe.Builder.build_nfe/2 (exactly one of them). A map that does not
build is {:error, {:invalid_nfe, errors}}, before anything else; the key it
generated is in Id of :signed_xml.
The pipeline is validate, sign, wrap in enviNFe, POST, parse.
The lote is synchronous by default: it carries one document, and SEFAZ
rejects an asynchronous request for a single-document batch as cStat 452.
When SEFAZ answers a receipt anyway — it may, under load — the protocol is
collected later with authorization_result/1.
XSD validation runs only when SefazNfe.Schema is configured, and then it
fails before the network — a local error naming the offending element beats
cStat 225, which names nothing.
The result carries :signed_xml — what was sent — and, once a protocol
exists, :xml holding the nfeProc. Store :signed_xml even on a receipt:
an asynchronous lote answers cStat 103 with no protocol, and without those
bytes the protocol collected later by authorization_result/1 cannot be
attached to anything. SefazNfe.Proc.nfe_proc/2 joins the two.
tpAmb is MOC data rather than a boolean — 1 is produção, 2 is homologação —
so a mismatch against :environment is refused before anything is sent.
The model is read from <mod>: 55 goes to the NF-e endpoints and 65 to the
NFC-e ones; anything else is {:error, {:unsupported_model, mod}}. For a
model 65 document infNFeSupl (with the on-line QR code 3.00) is added after
signing unless the XML already has one; see SefazNfe.NFCe. :uf is the
emitting UF, which selects the QR code address even where SVRS authorizes.
:qr_code_version (3, the default, or 2), :csc and :csc_id select the
CSC based QR code 2.00, on-line or off-line; the CSC is a secret and is never
logged nor returned in an error.
Contingency (model 55)
Contingency is the caller's choice (AD-005): this library never falls back to
it, and it builds no XML, so the ERP rebuilds the document with the new
tpEmis and this function routes on it:
1goes to the emitting UF's own authorizer;6goes to SVC-AN and7to SVC-RS, but only when that SVC is the one that serves:uf(SefazNfe.Endpoints.contingency_for/1); otherwise{:error, {:wrong_contingency, uf, svc}}, wheresvcis the SVC that does serve it;4is an NF-e under EPEC (epec/1) coming back: it goes to the ORIGIN authorizer, keepingtpEmis4;2,3and5(FS-IA, SCAN, FS-DA) are{:error, {:unsupported, {:tp_emis, n}}}.
For 4, 6 and 7 the MOC requires dhCont and xJust in ide; their
absence is {:error, {:missing_contingency_fields, [:dh_cont, :x_just]}}
(whichever is missing), before the network. NFC-e (model 65) has no SVC.
@spec cancel(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
Event 110111, cancelling an authorized NF-e via NFeRecepcaoEvento4.
Needs the protocol the authorization returned, and a justification of at
least 15 characters as the MOC requires. The model comes from the key, so an
NFC-e is cancelled at the NFC-e authorizer. Takes the optional :contingency
described in consult_protocol/1.
Like every event (cce/1, manifest/2, epec/1), the result carries
:signed_xml (the evento sent) and, once SEFAZ registered it (cStat 135,
136 or 155), :xml holding the procEventoNFe from
SefazNfe.Proc.event_proc/2. SefazNfe.Proc.cancel_register/2 appends the
cancellation to the nfeProc.
@spec cce(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
Event 110110, the Carta de Correção Eletrônica, via NFeRecepcaoEvento4.
:sequence numbers the correction; each one replaces the previous text
rather than adding to it.
NFC-e has no Carta de Correção: a model 65 key is
{:error, {:unsupported_for_model, 65}}. Takes the optional :contingency
described in consult_protocol/1.
@spec consult_protocol(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
NFeConsultaProtocolo4 by 44-digit access key.
The idempotent way back after a crash between a receipt and a protocol: ask SEFAZ what it did with a document instead of sending the batch again.
The model comes from the key, so an NFC-e is asked of the NFC-e authorizer.
:signed_xml is optional: the signed NFe that was sent. With it, when the
answer holds a protNFe of the key (an authorized document), the result's
:xml is the nfeProc as authorize/1 builds it. Only the protNFe goes in:
a procEventoNFe the answer carries (a cancellation) is not copied, so
SefazNfe.Proc.cancel_register/2 can still append it. A :signed_xml whose
key is not :ch_nfe is {:error, :signed_xml_key_mismatch}, before SEFAZ is
called. The result carries it back as :signed_xml. Without it :xml is
nil, as before.
The SOAP answer is in :response_xml; see SefazNfe.Result.
:contingency
Optional, :svc_an or :svc_rs: ask that SVC instead of the origin. Absent
means the UF's own authorizer, exactly as before. It must be the SVC that
serves :uf, else {:error, {:wrong_contingency, uf, svc}} naming the one
that does; NFC-e has no SVC ({:error, {:unsupported_for_model, 65}}).
It is never inferred from the key's tpEmis digit (AD-005): once contingency
ends, documents issued under SVC are handled at the origin, so only the
caller knows which authorizer holds the document now. cancel/1, cce/1 and
service_status/1 take the same option with the same rules.
@spec consult_taxpayer(map()) :: {:ok, SefazNfe.TaxpayerLookup.t()} | {:error, term()}
NFeConsultaCadastro (CadConsultaCadastro4): the state taxpayer registry.
:uf is the UF whose registry is consulted, and also selects the endpoint.
Exactly one filter is required: :tax_id (CPF, or CNPJ including the
alphanumeric one; shape-checked like everywhere else) or :ie, a state
registration of 2 to 14 digits (shape only).
Neither filter, or both, is {:error, {:invalid_filter, :missing | :ambiguous}};
a malformed state registration is {:error, :invalid_ie}. A UF whose
authorizer does not offer the service (AM, and MA through SVAN) is
{:error, {:unknown_endpoint, uf, :nfe_consulta_cadastro}}.
cStat 111 and 112 carry one or several records, and a rejection such as 259
(not registered) is still {:ok, lookup} with taxpayers: []. See
SefazNfe.TaxpayerLookup.
@spec dist_dfe(map()) :: {:ok, SefazNfe.DistDFe.t()} | {:error, term()}
NFeDistribuicaoDFe on the Ambiente Nacional. Caller persists ult_nsu.
:tax_id is the CNPJ or CPF of the interested party — the distDFeInt
envelope carries it, so it is required even though the URL is always the AN.
:uf is the querying party's own state, which the envelope carries as
cUFAutor. It is required and must be a real UF: the Ambiente Nacional's own
code is rejected there as cStat 215.
A CPF is 11 digits; a CNPJ is 14 and alphanumeric since NT 2025.002 (CNPJ
alfa), meaning 12 characters of [A-Z0-9] plus a two digit DV. Only the shape
is checked here — the check digits and the registration itself are SEFAZ's to
validate.
@spec epec(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
Event 110140, the EPEC (Evento Prévio de Emissão em Contingência), for an NF-e model 55.
:xml is the NF-e issued with tpEmis 4, signed or not. It is read and never
modified; every value the event carries (chNFe, cUF, dhEmi, tpNF, the
emitter's IE, the recipient's UF, document and IE, vNF, vICMS,
vST) is copied from it. :verAplic defaults to its verProc: pass
:ver_aplic to override. :id_lote is optional.
EPEC is processed by the Ambiente Nacional (cOrgao 91, no :uf needed),
sequence 1, authored by the emitter, and signed on infEvento like every
event. SEFAZ answers cStat 136 with the protocol (:n_prot) and the
registration time (:dh_recbto).
Refused before the network: a model other than 55
({:unsupported_for_model, 65}), a document that is not tpEmis 4
({:not_epec_document, tp_emis}), no recipient ({:epec, :missing_dest}) and
an access key whose UF is not cUF
({:epec, {:ch_nfe_uf_mismatch, key_uf, c_uf}}).
What this does not do
Choosing contingency is the caller's (AD-005); nothing here switches to it. The
caller also owns the rest of the flow: the DANFE has to carry the EPEC notice,
and the NF-e itself has to be transmitted to its origin authorizer, keeping
tpEmis 4, within 168 hours (authorize/1 routes a tpEmis 4 document there).
@spec manifest(atom(), map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
Manifestação do destinatário for a document received through DistDFe.
type is one of :confirmation, :awareness, :unaware or
:not_performed; the last one needs a :justification. Confirming an
operation is also what releases the full XML of a note DistDFe only
summarised.
These events are processed by the Ambiente Nacional, so no :uf is needed.
@spec service_status(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
NFeStatusServico4 for one UF.
The cheapest official call there is, and the one that proves the A1, the mTLS
handshake and the endpoint table in a single round trip. cStat 107 is
:in_operation; 108 and 109 are :retryable (the authorizer is paused), and
all arrive as {:ok, result} because SEFAZ answered. See SefazNfe.CStat.
:model (55 by default, or 65) selects the NF-e or the NFC-e authorizer.
:contingency (:svc_an or :svc_rs) asks the SVC instead. See
consult_protocol/1 for the rules, which are the same here.
@spec start_dist_dfe_poller(keyword()) :: DynamicSupervisor.on_start_child()
Starts a DistDFe poller for one tax ID under SefazNfe.DistDFe.Supervisor.
opts must include :tax_id, :cert and :handler — the poller delivers
every page to the handler, which owns the cursor. See
SefazNfe.DistDFe.Poller for the handler contract and the remaining options
(:environment, :ult_nsu, :interval, :fetch).
@spec void_numbers(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
NFeInutilizacao4, closing a range of NF-e numbers that was never used.
A broken sequence still has to be accounted for, and this is how. :model
defaults to 55 and :year to the current one; it is the mod of the voided
range and also selects the endpoints, so 65 voids NFC-e numbers at the NFC-e
authorizer.
The result carries :signed_xml (the inutNFe sent) and, on cStat 102,
:xml holding the procInutNFe from SefazNfe.Proc.void_proc/2.
Inutilização is always done at the origin authorizer: SVC does not offer it,
so :contingency is ignored here.