Documentation
¶
Overview ¶
O package nfe fornece funções para fazer toda a comunicação com as Sefazes no âmbito da NFe.
Index ¶
- Constants
- func GetChaveInfo(DFeChave string) (int, int, int, string, string, int, int, string, int, error)
- func GetUF(cUF int) string
- func GetcUF(uf string) int
- func NewHTTPClient(certFile string, certKeyFile string) (*http.Client, error)
- func ValidaChaveDeAcesso(DFeChave string) bool
- type ConsCad
- type ConsSitNFe
- type ConsStatServ
- type Envelope
- type EnvelopeConsCadMT
- type EnvelopeResult
- type EnvelopeResultConsCadMG
- type EnvelopeResultConsCadMT
- type EventoNFe
- type InfCad
- type ProcEventoNFe
- type ProtNFe
- type RetCancNFe
- type RetConsCad
- type RetConsSitNFe
- type RetConsStatServ
- type RetEventoNFe
- type TAmb
- type TWebService
Examples ¶
Constants ¶
const VerConsCad = "2.00"
const VerConsSitNFe = "4.00"
const VerConsStatServ = "4.00"
Variables ¶
This section is empty.
Functions ¶
func GetChaveInfo ¶
GetChaveInfo extrai todas as informações que estão embutidas em uma chave de acesso da NFe:
cUF, Ano, Mes, CNPJ, Modelo (55/65), Número da NFe, tpEmis e cNF.
func NewHTTPClient ¶
NewHTTPClient cria um http.Client com todas as configurações necessárias para comunicação com as Sefazes.
O certificado digital para usar com essa biblioteca pode ser gerado a partir de um certificado A1 da seguinte maneira:
openssl pkcs12 -in certificado.pfx -out ~/client.pem -clcerts -nokeys -nodes openssl pkcs12 -in certificado.pfx -out ~/key.pem -nocerts -nodes
func ValidaChaveDeAcesso ¶
ValidaChaveDeAcesso verifica se a chave de acesso fornecida é válida, através dos seguintes critérios:
- Tamanho = 44 e conteúdo numérico
- Dígito verificador consistente
- cUF corresponde a um item da tabela do IBGE
- Mes/Ano válidos, posteriores a 01/2006 e não posteriores ao ano atual
- CNPJ válido e diferente de 00000000000000
- Modelo igual a 55 ou 65 ou 67
- Número da NF diferente de zero
Types ¶
type ConsCad ¶
type ConsCad struct {
XMLName xml.Name `json:"-" xml:"http://www.portalfiscal.inf.br/nfe ConsCad"`
Versao string `json:"versao" xml:"versao,attr"`
InfCons struct {
XServ string `json:"xServ" xml:"xServ"`
UF string `json:"UF" xml:"UF"`
IE string `json:"IE,omitempty" xml:"IE,omitempty"`
CNPJ string `json:"CNPJ,omitempty" xml:"CNPJ,omitempty"`
CPF string `json:"CPF,omitempty" xml:"CPF,omitempty"`
} `json:"infCons" xml:"infCons"`
}
ConsCad representa o XML de consulta do cadastro do contribuinte
func (ConsCad) Consulta ¶
func (cons ConsCad) Consulta(tpAmb TAmb, client *http.Client, optReq ...func(req *http.Request)) (RetConsCad, []byte, error)
Realiza a consulta na Sefaz correspondente (determinada automaticamente pelo UF), utilizando o http.Client (ver NewHTTPClient) e as funções de personalização da http.Request fornecidos.
Ver ConsultaCad() para uma maneira mais simples de consultar o status do serviço
type ConsSitNFe ¶
type ConsSitNFe struct {
XMLName xml.Name `json:"-" xml:"http://www.portalfiscal.inf.br/nfe consSitNFe"`
Versao string `json:"versao" xml:"versao,attr"`
TpAmb TAmb `json:"tpAmb" xml:"tpAmb"`
XServ string `json:"xServ" xml:"xServ"`
ChNFe string `json:"chNFe" xml:"chNFe"`
}
ConsSitNFe representa o XML de consulta de uma NFe
func (ConsSitNFe) Consulta ¶
func (cons ConsSitNFe) Consulta(client *http.Client, optReq ...func(req *http.Request)) (RetConsSitNFe, []byte, error)
Realiza a consulta na Sefaz correspondente (determinada automaticamente pelo cUF presente na chave), utilizando o http.Client (ver NewHTTPClient) e as funções de personalização da http.Request fornecidos.
Ver ConsultaNFe() para uma maneira mais simples de consultar a NFe
Example ¶
client, err := nfe.NewHTTPClient("~/client.pem", "~/key.pem")
if err != nil {
fmt.Printf("Erro na criação do HTTP Client e leitura do certificado. Detalhes: %v\n", err)
return
}
cons := nfe.ConsSitNFe{
Versao: nfe.VerConsSitNFe,
TpAmb: nfe.Homologacao,
XServ: "CONSULTAR",
ChNFe: "12345678901234567890123456789012345678901234",
}
ret, xmlfile, err := cons.Consulta(client)
if err != nil {
fmt.Printf("Erro na consulta da chave de acesso. Detalhes: %v\n", err)
return
}
fmt.Printf("%v\n\n", ret)
fmt.Printf("%s\n", xmlfile)
type ConsStatServ ¶
type ConsStatServ struct {
XMLName xml.Name `json:"-" xml:"http://www.portalfiscal.inf.br/nfe consStatServ"`
Versao string `json:"versao" xml:"versao,attr"`
TpAmb TAmb `json:"tpAmb" xml:"tpAmb"`
CUF int `json:"cUF" xml:"cUF"`
XServ string `json:"xServ" xml:"xServ"`
}
ConsStatServ representa o XML de consulta do status do serviço
func (ConsStatServ) Consulta ¶
func (cons ConsStatServ) Consulta(client *http.Client, optReq ...func(req *http.Request)) (RetConsStatServ, []byte, error)
Realiza a consulta na Sefaz correspondente (determinada automaticamente pelo cUF), utilizando o http.Client (ver NewHTTPClient) e as funções de personalização da http.Request fornecidos.
Ver ConsultaStatServ() para uma maneira mais simples de consultar o status do serviço
Example ¶
client, err := nfe.NewHTTPClient("~/client.pem", "~/key.pem")
if err != nil {
fmt.Printf("Erro na criação do HTTP Client e leitura do certificado. Detalhes: %v\n", err)
return
}
cons := nfe.ConsStatServ{
Versao: nfe.VerConsStatServ,
TpAmb: nfe.Homologacao,
XServ: "STATUS",
CUF: 35,
}
ret, xmlfile, err := cons.Consulta(client)
if err != nil {
fmt.Printf("Erro na consulta da chave de acesso. Detalhes: %v\n", err)
return
}
fmt.Printf("%v\n\n", ret)
fmt.Printf("%s\n", xmlfile)
type Envelope ¶
type Envelope struct {
XMLName xml.Name `xml:"soap12:Envelope"`
Xsi string `xml:"xmlns:xsi,attr"`
Xsd string `xml:"xmlns:xsd,attr"`
Soap12 string `xml:"xmlns:soap12,attr"`
Body struct {
NfeDadosMsg struct {
Xmlns string `xml:"xmlns,attr"`
Value []byte `xml:",innerxml"`
} `xml:"nfeDadosMsg"`
} `xml:"soap12:Body"`
}
Envelope representa o XML do envelope SOAP que será usado na comunicação.
type EnvelopeConsCadMT ¶
type EnvelopeConsCadMT struct {
XMLName xml.Name `xml:"soap12:Envelope"`
Xsi string `xml:"xmlns:xsi,attr"`
Xsd string `xml:"xmlns:xsd,attr"`
Soap12 string `xml:"xmlns:soap12,attr"`
Body struct {
ConsultaCadastro struct {
Xmlns string `xml:"xmlns,attr"`
NfeDadosMsg struct {
Value []byte `xml:",innerxml"`
} `xml:"nfeDadosMsg"`
} `xml:"consultaCadastro"`
} `xml:"soap12:Body"`
}
EnvelopeConsCadMT representa o XML do envelope SOAP que será usado na comunicação com a consulta de cadastro do MT.
type EnvelopeResult ¶
type EnvelopeResult struct {
XMLName xml.Name `xml:"Envelope"`
Body struct {
NfeResultMsg struct {
Value []byte `xml:",innerxml"`
} `xml:"nfeResultMsg"`
} `xml:"Body"`
}
EnvelopeResult representa o XML do envelope SOAP de retorno da requisição.
type EnvelopeResultConsCadMG ¶
type EnvelopeResultConsCadMG struct {
XMLName xml.Name `xml:"Envelope"`
Body struct {
ConsultaCadastro4Result struct {
Value []byte `xml:",innerxml"`
} `xml:"consultaCadastro4Result"`
} `xml:"Body"`
}
EnvelopeResultConsCadMG representa o XML do envelope SOAP de retorno da requisição ConsCad em MG, que é diferente de todas as outras respostas do sistema NFe.
type EnvelopeResultConsCadMT ¶
type EnvelopeResultConsCadMT struct {
XMLName xml.Name `xml:"Envelope"`
Body struct {
NfeResultMsg struct {
ConsultaCadastroResult struct {
Value []byte `xml:",innerxml"`
} `xml:"consultaCadastroResult"`
} `xml:"nfeResultMsg"`
} `xml:"Body"`
}
EnvelopeResultConsCadMT representa o XML do envelope SOAP de retorno da requisição ConsCad em MT, que é diferente de todas as outras respostas do sistema NFe.
type EventoNFe ¶
type EventoNFe struct {
Versao string `json:"-" xml:"versao,attr"`
InfEvento struct {
Versao string `json:"versao,omitempty" xml:"versao,attr,omitempty"`
ID string `json:"Id" xml:"Id,attr"`
COrgao int `json:"cOrgao" xml:"cOrgao"`
TpAmb TAmb `json:"tpAmb" xml:"tpAmb"`
CNPJ string `json:"CNPJ,omitempty" xml:"CNPJ,omitempty"`
CPF string `json:"CPF,omitempty" xml:"CPF,omitempty"`
ChNFe string `json:"chNFe" xml:"chNFe"`
DhEvento time.Time `json:"dhEvento" xml:"dhEvento"`
TpEvento string `json:"tpEvento" xml:"tpEvento"`
NSeqEvento int `json:"nSeqEvento" xml:"nSeqEvento"`
VerEvento string `json:"verEvento" xml:"verEvento"`
DetEvento struct {
Versao string `xml:"versao,attr"`
Value []byte `xml:",innerxml"`
} `json:"-" xml:"detEvento"`
} `json:"infEvento" xml:"infEvento"`
Signature *xmlsig.Signature `json:"-" xml:"Signature"`
}
EventoNFe representa o XML de registro de um evento junto à Sefaz.
type InfCad ¶
type InfCad struct {
IE string `json:"IE" xml:"IE"`
CNPJ string `json:"CNPJ,omitempty" xml:"CNPJ,omitempty"`
CPF string `json:"CPF,omitempty" xml:"CPF,omitempty"`
UF string `json:"UF" xml:"UF"`
CSit int `json:"cSit" xml:"cSit"`
IndCredNFe int `json:"indCredNFe" xml:"indCredNFe"`
IndCredCTe int `json:"indCredCTe" xml:"indCredCTe"`
XNome string `json:"xNome" xml:"xNome"`
XFant string `json:"xFant,omitempty" xml:"xFant,omitempty"`
XRegApur string `json:"xRegApur,omitempty" xml:"xRegApur,omitempty"`
CNAE string `json:"CNAE,omitempty" xml:"CNAE,omitempty"`
DIniAtiv civil.Date `json:"dIniAtiv,omitempty" xml:"dIniAtiv,omitempty"`
DUltSit civil.Date `json:"dUltSit,omitempty" xml:"dUltSit,omitempty"`
DBaixa civil.Date `json:"dBaixa,omitempty" xml:"dBaixa,omitempty"`
IEUnica string `json:"IEUnica,omitempty" xml:"IEUnica,omitempty"`
IEAtual string `json:"IEAtual,omitempty" xml:"IEAtual,omitempty"`
Ender *struct {
XLgr string `json:"xLgr,omitempty" xml:"xLgr,omitempty"`
Nro string `json:"nro,omitempty" xml:"nro,omitempty"`
XCpl string `json:"xCpl,omitempty" xml:"xCpl,omitempty"`
XBairro string `json:"xBairro,omitempty" xml:"xBairro,omitempty"`
CMun string `json:"cMun,omitempty" xml:"cMun,omitempty"`
XMun string `json:"xMun,omitempty" xml:"xMun,omitempty"`
CEP string `json:"CEP,omitempty" xml:"CEP,omitempty"`
} `json:"ender,omitempty" xml:"ender,omitempty"`
}
type ProcEventoNFe ¶
type ProcEventoNFe struct {
XMLName xml.Name `json:"-" xml:"procEventoNFe"`
Versao string `json:"versao" xml:"versao,attr"`
Evento *EventoNFe `json:"evento" xml:"http://www.portalfiscal.inf.br/nfe evento"`
RetEvento *RetEventoNFe `json:"retEvento" xml:"retEvento"`
}
ProcEventoNFe representa o XML que contem tanto a requisição (EventoNFe) quanto o retorno da Sefaz (RetEventoNFe), e poderá vir dentro de consultas de status (ConsSitNFe).
type ProtNFe ¶
type ProtNFe struct {
Versao string `json:"-" xml:"versao,attr"`
InfProt struct {
TpAmb TAmb `json:"tpAmb" xml:"tpAmb"`
VerAplic string `json:"verAplic" xml:"verAplic"`
ChNFe string `json:"chNFe" xml:"chNFe"`
DhRecbto time.Time `json:"dhRecbto" xml:"dhRecbto"`
NProt string `json:"nProt" xml:"nProt"`
DigVal string `json:"digVal" xml:"digVal"`
CStat int `json:"cStat" xml:"cStat"`
XMotivo string `json:"xMotivo" xml:"xMotivo"`
} `json:"infProt" xml:"infProt"`
}
ProtNFe representa o XML do protocolo de autorização da NFe, encontrado em RetConsSitNFe.
type RetCancNFe ¶
type RetCancNFe struct {
Versao string `json:"-" xml:"versao,attr"`
InfCanc struct {
TpAmb TAmb `json:"tpAmb" xml:"tpAmb"`
VerAplic string `json:"verAplic" xml:"verAplic"`
CStat int `json:"cStat" xml:"cStat"`
XMotivo string `json:"xMotivo" xml:"xMotivo"`
CUF int `json:"cUF" xml:"cUF"`
ChNFe string `json:"chNFe" xml:"chNFe"`
DhRecbto time.Time `json:"dhRecbto" xml:"dhRecbto"`
NProt string `json:"nProt" xml:"nProt"`
} `json:"infCanc" xml:"infCanc"`
}
RetCancNFe representa o XML de retorno da Sefaz do cancelamento da NFe. Não é mais usado, tendo sido substituído pelos eventos (EventoNFe), mas ainda pode ser retornado em uma consulta de protocolo (ConsSitNFe) de notas antigas.
type RetConsCad ¶
type RetConsCad struct {
XMLName xml.Name `json:"-" xml:"http://www.portalfiscal.inf.br/nfe retConsCad"`
Versao string `json:"versao" xml:"versao,attr"`
InfCons struct {
VerAplic string `json:"verAplic" xml:"verAplic"`
CStat int `json:"cStat" xml:"cStat"`
XMotivo string `json:"xMotivo" xml:"xMotivo"`
UF string `json:"UF" xml:"UF"`
IE string `json:"IE,omitempty" xml:"IE,omitempty"`
CNPJ string `json:"CNPJ,omitempty" xml:"CNPJ,omitempty"`
CPF string `json:"CPF,omitempty" xml:"CPF,omitempty"`
DhCons time.Time `json:"dhCons" xml:"dhCons"`
CUF int `json:"cUF" xml:"cUF"`
InfCad *[]InfCad `json:"infCad,omitempty" xml:"infCad,omitempty"`
} `json:"infCons" xml:"infCons"`
}
RetConsCad representa o XML de retorno da Sefaz à consulta do cadastro do contribuinte
type RetConsSitNFe ¶
type RetConsSitNFe struct {
XMLName xml.Name `json:"-" xml:"http://www.portalfiscal.inf.br/nfe retConsSitNFe"`
Versao string `json:"versao" xml:"versao,attr"`
TpAmb TAmb `json:"tpAmb" xml:"tpAmb"`
VerAplic string `json:"verAplic" xml:"verAplic"`
CStat int `json:"cStat" xml:"cStat"`
XMotivo string `json:"xMotivo" xml:"xMotivo"`
CUF int `json:"cUF" xml:"cUF"`
DhRecbto time.Time `json:"dhRecbto" xml:"dhRecbto"`
ChNFe string `json:"chNFe" xml:"chNFe"`
ProtNFe *ProtNFe `json:"protNFe" xml:"protNFe"`
RetCancNFe *RetCancNFe `json:"retCancNFe,omitempty" xml:"retCancNFe,omitempty"`
ProcEventoNFe *[]ProcEventoNFe `json:"procEventoNFe,omitempty" xml:"procEventoNFe,omitempty"`
}
RetConsSitNFe representa o XML de retorno da Sefaz à consulta da NFe
func ConsultaNFe ¶
func ConsultaNFe(dfechave string, tpAmb TAmb, client *http.Client, optReq ...func(req *http.Request)) (RetConsSitNFe, []byte, error)
Função auxiliar para executar a ConsSitNFe.Consulta()
Example ¶
Esse exemplo mostra todos os passos para se fazer uma consulta de protocolo na Sefaz. Desde a criação de um novo http.Client (através da NewHTTPClient) até a personalização do User-Agent por meio do parâmetro optReq.
client, err := nfe.NewHTTPClient("~/client.pem", "~/key.pem")
if err != nil {
fmt.Printf("Erro na criação do HTTP Client e leitura do certificado. Detalhes: %v\n", err)
return
}
ret, xmlfile, err := nfe.ConsultaNFe("12345678901234567890123456789012345678901234", nfe.Homologacao, client, func(req *http.Request) { req.Header.Set("User-Agent", "MyUA/1.0") })
if err != nil {
fmt.Printf("Erro na consulta da chave de acesso. Detalhes: %v\n", err)
return
}
fmt.Printf("Objeto RetConsSitNFe: %v\n", ret)
fmt.Printf("Arquivo XML: %v\n", string(xmlfile))
jsonfile, err := json.Marshal(ret)
if err != nil {
fmt.Printf("Erro na serialização do json. Detalhes: %v\n", err)
return
}
fmt.Printf("Arquivo JSON: %v\n", string(jsonfile))
type RetConsStatServ ¶
type RetConsStatServ struct {
XMLName xml.Name `json:"-" xml:"http://www.portalfiscal.inf.br/nfe retConsStatServ"`
Versao string `json:"versao" xml:"versao,attr"`
TpAmb TAmb `json:"tpAmb" xml:"tpAmb"`
VerAplic string `json:"verAplic" xml:"verAplic"`
CStat int `json:"cStat" xml:"cStat"`
XMotivo string `json:"xMotivo" xml:"xMotivo"`
CUF int `json:"cUF" xml:"cUF"`
DhRecbto time.Time `json:"dhRecbto" xml:"dhRecbto"`
TMed int `json:"tMed" xml:"tMed"`
DhRetorno time.Time `json:"dhRetorno,omitempty" xml:"dhRetorno,omitempty"`
XObs string `json:"xObs,omitempty" xml:"xObs,omitempty"`
}
RetConsStatServ representa o XML de retorno da Sefaz à consulta do status do serviço
func ConsultaStatServ ¶
func ConsultaStatServ(cUF int, tpAmb TAmb, client *http.Client, optReq ...func(req *http.Request)) (RetConsStatServ, []byte, error)
Função auxiliar para executar a ConsStatServ.Consulta()
Example ¶
Esse exemplo mostra todos os passos para se fazer uma consulta de status do serviço na Sefaz. Desde a criação de um novo http.Client (através da NewHTTPClient) até a personalização do User-Agent por meio do parâmetro optReq.
client, err := nfe.NewHTTPClient("~/client.pem", "~/key.pem")
if err != nil {
fmt.Printf("Erro na criação do HTTP Client e leitura do certificado. Detalhes: %v\n", err)
return
}
ret, xmlfile, err := nfe.ConsultaStatServ(35, nfe.Homologacao, client, func(req *http.Request) { req.Header.Set("User-Agent", "MyUA/1.0") })
if err != nil {
fmt.Printf("Erro na consulta da chave de acesso. Detalhes: %v\n", err)
return
}
fmt.Printf("Objeto RetConsStatServ: %v\n", ret)
fmt.Printf("Arquivo XML: %v\n", string(xmlfile))
jsonfile, err := json.Marshal(ret)
if err != nil {
fmt.Printf("Erro na serialização do json. Detalhes: %v\n", err)
return
}
fmt.Printf("Arquivo JSON: %v\n", string(jsonfile))
type RetEventoNFe ¶
type RetEventoNFe struct {
Versao string `json:"versao" xml:"versao,attr"`
InfEvento struct {
ID string `json:"Id" xml:"Id,attr,omitempty"`
TpAmb TAmb `json:"tpAmb" xml:"tpAmb"`
VerAplic string `json:"verAplic" xml:"verAplic"`
COrgao int `json:"cOrgao" xml:"cOrgao"`
CStat int `json:"cStat" xml:"cStat"`
XMotivo string `json:"xMotivo" xml:"xMotivo"`
ChNFe string `json:"chNFe" xml:"chNFe"`
TpEvento string `json:"tpEvento" xml:"tpEvento"`
XEvento string `json:"xEvento" xml:"xEvento"`
NSeqEvento int `json:"nSeqEvento" xml:"nSeqEvento"`
CNPJDest string `json:"CNPJDest,omitempty" xml:"CNPJDest,omitempty"`
CPFDest string `json:"CPFDest,omitempty" xml:"CPFDest,omitempty"`
EmailDest string `json:"emailDest,omitempty" xml:"emailDest,omitempty"`
DhRegEvento time.Time `json:"dhRegEvento" xml:"dhRegEvento"`
NProt string `json:"nProt" xml:"nProt"`
} `json:"infEvento" xml:"infEvento"`
}
RetEventoNFe representa o XML de retorno da Sefaz à solicitação de registro de evento. Normalmente será utilizado encapsulado em um ProcEventoNFe.
type TWebService ¶
type TWebService int
TWebService representa o serviço que será consultado. Usado pela função getURLWS para obter a URL da requisição.
const ( ConsultaStatus TWebService = iota ConsultaProtocolo ConsultaCadastro Autorizacao RetAutorizacao Evento Inutilizacao )