nfe

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2025 License: MPL-2.0 Imports: 26 Imported by: 0

README

nfe

Bibliotecas para geração, validação, assinatura e transmissão de XMLs da NFe. Pretendo desenvolver essa biblioteca conforme a necessidade surgir. Por enquanto apenas as consultas de Status, NFe e Cadastro estão disponíveis.

Extraindo chaves de um certificado A1 (.pfx) para uso com o biblioteca

openssl pkcs12 -in certificado.pfx -out ~/client.pem -clcerts -nokeys -nodes
openssl pkcs12 -in certificado.pfx -out ~/key.pem -nocerts -nodes

Consulta NFe

Exemplo
package main

import (
	"encoding/json"
	"net/http"
	"fmt"

	"github.com/frones/nfe"
)

func main() {
	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))
}

Problemas de comunicação com a Sefaz-RS e ambientes virtuais SV-RS

Usando a crypto/tls padrão do Go, foi observado um problema intermitente de comunicação com os ambientes da Sefaz-RS, com resposta 403 sendo retornada. O problema acontece porque a crypto/tls não envia o certificado durante o handshake quando a CertificateRequest do servidor especifica autoridades certificadoras que não batem com a CA do certificado [source]. Outras Sefazes não enviam uma lista de CAs permitidas, não apresentando esse problema. Mesmo a Sefaz-RS, em algumas requests não envia lista de CAs permitidas, fazendo com que o problema seja intermitente.

Durante depuração, identifiquei que de fato, a CA do meu certificado não estava na lista de CAs permitidas pelo servidor, de maneira que faz sentido que a crypto/tls não envie, mas não fica claro porque outras bibliotecas, como a OpenSSL sempre funcionam.

Um workaround possível é compilar com uma versão alterada da crypto/tls sempre ignorando a instrução de CAs permitidas, mas isso pode ter outras consequencias indesejadas.

Documentation

Overview

O package nfe fornece funções para fazer toda a comunicação com as Sefazes no âmbito da NFe.

recepcao_evento.go

Index

Examples

Constants

View Source
const VerConsCad = "2.00"
View Source
const VerConsSitNFe = "4.00"
View Source
const VerConsStatServ = "4.00"

Variables

This section is empty.

Functions

func GetChaveInfo

func GetChaveInfo(DFeChave string) (int, int, int, string, string, int, int, string, int, error)

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 GetUF

func GetUF(cUF int) string

GetUF retorna a sigla da UF a partir do código IBGE

func GetcUF

func GetcUF(uf string) int

GetcUF retorna o código IBGE da UF a partir da sigla

func NewHTTPClient

func NewHTTPClient(certFile string, certKeyFile string) (*http.Client, error)

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

func ValidaChaveDeAcesso(DFeChave string) bool

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 COFINSAliq

type COFINSAliq struct {
	CST     string  `xml:"CST"`
	VBC     float64 `xml:"vBC"`
	PCOFINS float64 `xml:"pCOFINS"`
	VCOFINS float64 `xml:"vCOFINS"`
}

type COFINSItem

type COFINSItem struct {
	CST         string
	BaseCalculo float64
	Aliquota    float64
	Valor       float64
}

type Cobr

type Cobr struct {
	Fat *Fat `xml:"fat"`
}

type CobrancaNotaFiscal

type CobrancaNotaFiscal struct {
	NumeroFatura  string
	ValorOriginal float64
	Desconto      float64
	ValorLiquido  float64
}

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 ConsChNFe

type ConsChNFe struct {
	ChNFe string `xml:"chNFe"`
}

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 Dest

type Dest struct {
	CNPJ      string `xml:"CNPJ"`
	XNome     string `xml:"xNome"`
	EnderDest Ender  `xml:"enderDest"`
	IndIEDest int    `xml:"indIEDest"`
	IE        string `xml:"IE"`
}

type Det

type Det struct {
	NItem     int     `xml:"nItem,attr"`
	Prod      Prod    `xml:"prod"`
	Imposto   Imposto `xml:"imposto"`
	InfAdProd string  `xml:"infAdProd"`
}

type DetPag

type DetPag struct {
	IndPag int     `xml:"indPag"`
	TPag   string  `xml:"tPag"`
	VPag   float64 `xml:"vPag"`
}

type DistDFeInt

type DistDFeInt struct {
	XMLName   xml.Name  `xml:"http://www.portalfiscal.inf.br/nfe distDFeInt"`
	Versao    string    `xml:"versao,attr"`
	TpAmb     int       `xml:"tpAmb"`
	CUFAutor  int       `xml:"cUFAutor"`
	CNPJ      string    `xml:"CNPJ"`
	ConsChNFe ConsChNFe `xml:"consChNFe"`
}

type DistDFeWrapper

type DistDFeWrapper struct {
	XMLName xml.Name `xml:"nfeDistDFeInteresse"`
	Xmlns   string   `xml:"xmlns,attr"`

	Dados struct {
		XMLName xml.Name   `xml:"nfeDadosMsg"`
		Xmlns   string     `xml:"xmlns,attr"`
		Msg     DistDFeInt `xml:"distDFeInt"`
	}
}

type DocZip

type DocZip struct {
	NSU    string `xml:"NSU,attr"`
	Schema string `xml:"schema,attr"`
	Value  string `xml:",chardata"`
}

type Emit

type Emit struct {
	CNPJ      string `xml:"CNPJ"`
	XNome     string `xml:"xNome"`
	XFant     string `xml:"xFant"`
	EnderEmit Ender  `xml:"enderEmit"`
	IE        string `xml:"IE"`
	IM        string `xml:"IM"`
	CNAE      string `xml:"CNAE"`
	CRT       int    `xml:"CRT"`
}

type Ender

type Ender struct {
	XLgr    string `xml:"xLgr"`
	Nro     string `xml:"nro"`
	XCpl    string `xml:"xCpl"`
	XBairro string `xml:"xBairro"`
	CMun    string `xml:"cMun"`
	XMun    string `xml:"xMun"`
	UF      string `xml:"UF"`
	CEP     string `xml:"CEP"`
	CPais   string `xml:"cPais"`
	XPais   string `xml:"xPais"`
	Fone    string `xml:"fone"`
}

type EnderecoNFe

type EnderecoNFe struct {
	Logradouro      string
	Numero          string
	Complemento     string
	Bairro          string
	Municipio       string
	CodigoMunicipio string
	UF              string
	CEP             string
	Pais            string
	CodigoPais      string
	Telefone        string
}

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 Fat

type Fat struct {
	NFat  string  `xml:"nFat"`
	VOrig float64 `xml:"vOrig"`
	VDesc float64 `xml:"vDesc"`
	VLiq  float64 `xml:"vLiq"`
}

type ICMS00

type ICMS00 struct {
	Orig  int     `xml:"orig"`
	CST   string  `xml:"CST"`
	ModBC int     `xml:"modBC"`
	VBC   float64 `xml:"vBC"`
	PICMS float64 `xml:"pICMS"`
	VICMS float64 `xml:"vICMS"`
}

type ICMSItem

type ICMSItem struct {
	Origem      int
	CST         string
	BaseCalculo float64
	Aliquota    float64
	Valor       float64
}

type ICMSTot

type ICMSTot struct {
	VBC        float64 `xml:"vBC"`
	VICMS      float64 `xml:"vICMS"`
	VICMSDeson float64 `xml:"vICMSDeson"`
	VFCP       float64 `xml:"vFCP"`
	VBCST      float64 `xml:"vBCST"`
	VST        float64 `xml:"vST"`
	VFCPST     float64 `xml:"vFCPST"`
	VFCPSTRet  float64 `xml:"vFCPSTRet"`
	VProd      float64 `xml:"vProd"`
	VFrete     float64 `xml:"vFrete"`
	VSeg       float64 `xml:"vSeg"`
	VDesc      float64 `xml:"vDesc"`
	VII        float64 `xml:"vII"`
	VIPI       float64 `xml:"vIPI"`
	VIPIDevol  float64 `xml:"vIPIDevol"`
	VPIS       float64 `xml:"vPIS"`
	VCOFINS    float64 `xml:"vCOFINS"`
	VOutro     float64 `xml:"vOutro"`
	VNF        float64 `xml:"vNF"`
	VTotTrib   float64 `xml:"vTotTrib"`
}

type IPIItem

type IPIItem struct {
	CST                 string
	BaseCalculo         float64
	Aliquota            float64
	Valor               float64
	CodigoEnquadramento string
}

type IPINT

type IPINT struct {
	CST string `xml:"CST"`
}

type IPITrib

type IPITrib struct {
	CST  string  `xml:"CST"`
	VBC  float64 `xml:"vBC"`
	PIPI float64 `xml:"pIPI"`
	VIPI float64 `xml:"vIPI"`
}

type Ide

type Ide struct {
	CUF         int    `xml:"cUF"`
	CNF         string `xml:"cNF"`
	NatOp       string `xml:"natOp"`
	Mod         string `xml:"mod"`
	Serie       int    `xml:"serie"`
	NNF         int    `xml:"nNF"`
	DhEmi       string `xml:"dhEmi"`
	TpNF        int    `xml:"tpNF"`
	IdDest      int    `xml:"idDest"`
	CMunFG      int    `xml:"cMunFG"`
	TpImp       int    `xml:"tpImp"`
	TpEmis      int    `xml:"tpEmis"`
	CDV         int    `xml:"cDV"`
	TpAmb       int    `xml:"tpAmb"`
	FinNFe      int    `xml:"finNFe"`
	IndFinal    int    `xml:"indFinal"`
	IndPres     int    `xml:"indPres"`
	IndIntermed int    `xml:"indIntermed"`
	ProcEmi     int    `xml:"procEmi"`
	VerProc     string `xml:"verProc"`
}

type Imposto

type Imposto struct {
	VTotTrib float64 `xml:"vTotTrib"`

	ICMS struct {
		ICMS00 *ICMS00 `xml:"ICMS00"`
	} `xml:"ICMS"`

	IPI struct {
		CEnq    string   `xml:"cEnq"`
		IPITrib *IPITrib `xml:"IPITrib"`
		IPINT   *IPINT   `xml:"IPINT"`
	} `xml:"IPI"`

	PIS struct {
		PISAliq *PISAliq `xml:"PISAliq"`
	} `xml:"PIS"`

	COFINS struct {
		COFINSAliq *COFINSAliq `xml:"COFINSAliq"`
	} `xml:"COFINS"`
}

type InfAdic

type InfAdic struct {
	InfCpl string `xml:"infCpl"`
}

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 InfNFe

type InfNFe struct {
	Id     string `xml:"Id,attr"`
	Versao string `xml:"versao,attr"`

	Ide     Ide      `xml:"ide"`
	Emit    Emit     `xml:"emit"`
	Dest    Dest     `xml:"dest"`
	Det     []Det    `xml:"det"`
	Total   Total    `xml:"total"`
	Transp  *Transp  `xml:"transp"`
	Cobr    *Cobr    `xml:"cobr"`
	Pag     *Pag     `xml:"pag"`
	InfAdic *InfAdic `xml:"infAdic"`
}

type InfProt

type InfProt struct {
	Id       string    `xml:"Id,attr"`
	TpAmb    int       `xml:"tpAmb"`
	VerAplic string    `xml:"verAplic"`
	ChNFe    string    `xml:"chNFe"`
	DhRecbto time.Time `xml:"dhRecbto"`
	NProt    string    `xml:"nProt"`
	DigVal   string    `xml:"digVal"`
	CStat    int       `xml:"cStat"`
	XMotivo  string    `xml:"xMotivo"`
}

type ItemNotaFiscal

type ItemNotaFiscal struct {
	Numero        int
	Codigo        string
	CodigoEAN     string
	Descricao     string
	NCM           string
	CEST          string
	CFOP          string
	Unidade       string
	Quantidade    float64
	ValorUnitario float64
	ValorTotal    float64

	ValorTotalTributos float64

	ICMS   *ICMSItem
	IPI    *IPIItem
	PIS    *PISItem
	COFINS *COFINSItem

	Observacao string
}

type ManifestacaoEvento added in v1.1.0

type ManifestacaoEvento struct {
	COrgao     int
	TpAmb      int
	CNPJ       string
	CPF        string
	ChNFe      string
	DhEvento   time.Time
	TpEvento   string
	NSeqEvento int
	VerEvento  string
	DescEvento string
}

type ManifestacaoEventoItem added in v1.2.0

type ManifestacaoEventoItem struct {
	Ambiente         int       // tpAmb
	CodigoOrgao      int       // cOrgao
	CodigoStatus     int       // cStat
	Motivo           string    // xMotivo
	ChNFe            string    // chNFe
	TipoEvento       string    // tpEvento
	DescricaoEvento  string    // xEvento
	NumeroSequencial int       // nSeqEvento
	DataRegistro     time.Time // dhRegEvento
	VersaoAplicativo string    // verAplic
}

type ManifestacaoEventoResponse added in v1.2.0

type ManifestacaoEventoResponse struct {
	LoteID           string                   // idLote
	Ambiente         int                      // tpAmb
	CodigoOrgao      int                      // cOrgao
	CodigoStatus     int                      // cStat
	Motivo           string                   // xMotivo
	VersaoAplicativo string                   // verAplic
	Eventos          []ManifestacaoEventoItem // retEvento[..].infEvento
}

func SendManifestacaoEvento added in v1.1.0

func SendManifestacaoEvento(
	ctx context.Context,
	client *http.Client,
	certPEMPath, keyPEMPath string,
	idLote string,
	eventos []ManifestacaoEvento,
	optReq ...func(*http.Request),
) (*ManifestacaoEventoResponse, []byte, error)

type NFe

type NFe struct {
	InfNFe InfNFe `xml:"infNFe"`
}

type NFeProc

type NFeProc struct {
	XMLName xml.Name `xml:"http://www.portalfiscal.inf.br/nfe nfeProc"`
	Versao  string   `xml:"versao,attr"`

	NFe     NFe     `xml:"NFe"`
	ProtNFe ProtNFe `xml:"protNFe"`
}

type NotaFiscalDistribuida

type NotaFiscalDistribuida struct {
	NSU    string
	Schema string

	Chave            string
	Numero           int
	Serie            int
	Modelo           string
	NaturezaOperacao string
	DataEmissao      time.Time

	Emitente     ParteNFe
	Destinatario ParteNFe

	Itens  []ItemNotaFiscal
	Totais TotaisNotaFiscal

	Transporte *TransporteNotaFiscal
	Cobranca   *CobrancaNotaFiscal
	Pagamentos []PagamentoNotaFiscal
	Protocolo  ProtocoloNotaFiscal

	InformacoesComplementares string
}

type PISAliq

type PISAliq struct {
	CST  string  `xml:"CST"`
	VBC  float64 `xml:"vBC"`
	PPIS float64 `xml:"pPIS"`
	VPIS float64 `xml:"vPIS"`
}

type PISItem

type PISItem struct {
	CST         string
	BaseCalculo float64
	Aliquota    float64
	Valor       float64
}

type Pag

type Pag struct {
	DetPag []DetPag `xml:"detPag"`
}

type PagamentoNotaFiscal

type PagamentoNotaFiscal struct {
	Indicador int
	Forma     string
	Valor     float64
}

type ParteNFe

type ParteNFe struct {
	CNPJ         string
	Nome         string
	NomeFantasia string
	IE           string
	Endereco     EnderecoNFe
}

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 Prod

type Prod struct {
	CProd    string  `xml:"cProd"`
	CEAN     string  `xml:"cEAN"`
	XProd    string  `xml:"xProd"`
	NCM      string  `xml:"NCM"`
	CEST     string  `xml:"CEST"`
	CFOP     string  `xml:"CFOP"`
	UCom     string  `xml:"uCom"`
	QCom     float64 `xml:"qCom"`
	VUnCom   float64 `xml:"vUnCom"`
	VProd    float64 `xml:"vProd"`
	CEANTrib string  `xml:"cEANTrib"`
	UTrib    string  `xml:"uTrib"`
	QTrib    float64 `xml:"qTrib"`
	VUnTrib  float64 `xml:"vUnTrib"`
	IndTot   int     `xml:"indTot"`
	XPed     string  `xml:"xPed"`
	NFCI     string  `xml:"nFCI"`
}

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 ProtocoloNotaFiscal

type ProtocoloNotaFiscal struct {
	Numero          string
	DataRecebimento time.Time
	Status          int
	Motivo          string
}

type ResultadoDistribuicaoNFe

type ResultadoDistribuicaoNFe struct {
	Ambiente     int
	Aplicativo   string
	Status       int
	Motivo       string
	DataResposta time.Time
	UltimoNSU    string
	MaximoNSU    string

	Documentos []NotaFiscalDistribuida
}

func ConsultaDistChNFe

func ConsultaDistChNFe(
	cnpj string,
	chave string,
	tpAmb TAmb,
	client *http.Client,
	optReq ...func(*http.Request),
) (ResultadoDistribuicaoNFe, error)

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

func ConsultaCad

func ConsultaCad(ie string, cnpj string, cpf string, cUF int, tpAmb TAmb, client *http.Client, optReq ...func(req *http.Request)) (RetConsCad, []byte, error)

Função auxiliar para executar a ConsCad.Consulta()

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 RetDistDFeInt

type RetDistDFeInt struct {
	XMLName  xml.Name `xml:"retDistDFeInt"`
	Versao   string   `xml:"versao,attr"`
	TpAmb    int      `xml:"tpAmb"`
	VerAplic string   `xml:"verAplic"`
	CStat    int      `xml:"cStat"`
	XMotivo  string   `xml:"xMotivo"`
	DhResp   string   `xml:"dhResp"`
	UltNSU   string   `xml:"ultNSU"`
	MaxNSU   string   `xml:"maxNSU"`

	Lote struct {
		Docs []DocZip `xml:"docZip"`
	} `xml:"loteDistDFeInt"`
}

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 SoapBodyDist

type SoapBodyDist struct {
	Wrapper DistDFeWrapper `xml:"nfeDistDFeInteresse"`
}

type SoapEnvelopeDist

type SoapEnvelopeDist struct {
	XMLName xml.Name     `xml:"soap:Envelope"`
	Soap    string       `xml:"xmlns:soap,attr"`
	Xsi     string       `xml:"xmlns:xsi,attr"`
	Xsd     string       `xml:"xmlns:xsd,attr"`
	Body    SoapBodyDist `xml:"soap:Body"`
}

type TAmb

type TAmb int

TAmb representa o ambiente (tpAmb) que será usado na comunicação.

const (
	Producao    TAmb = 1
	Homologacao TAmb = 2
)

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
)

type TotaisNotaFiscal

type TotaisNotaFiscal struct {
	ValorBaseICMS           float64
	ValorICMS               float64
	ValorProdutos           float64
	ValorNota               float64
	ValorTributosAproximado float64
}

type Total

type Total struct {
	ICMSTot ICMSTot `xml:"ICMSTot"`
}

type Transp

type Transp struct {
	ModFrete   int         `xml:"modFrete"`
	Transporta *Transporta `xml:"transporta"`
	Vol        []Vol       `xml:"vol"`
}

type Transporta

type Transporta struct {
	CNPJ   string `xml:"CNPJ"`
	XNome  string `xml:"xNome"`
	IE     string `xml:"IE"`
	XEnder string `xml:"xEnder"`
	XMun   string `xml:"xMun"`
	UF     string `xml:"UF"`
}

type TransportadoraNotaFiscal

type TransportadoraNotaFiscal struct {
	CNPJ      string
	Nome      string
	IE        string
	Endereco  string
	Municipio string
	UF        string
}

type TransporteNotaFiscal

type TransporteNotaFiscal struct {
	ModalidadeFrete   int
	Transportadora    *TransportadoraNotaFiscal
	QuantidadeVolumes float64
	Especie           string
	Marca             string
	PesoLiquido       float64
	PesoBruto         float64
}

type Vol

type Vol struct {
	QVol  float64 `xml:"qVol"`
	Esp   string  `xml:"esp"`
	Marca string  `xml:"marca"`
	PesoL float64 `xml:"pesoL"`
	PesoB float64 `xml:"pesoB"`
}

type WSError

type WSError struct {
	Url           string
	StatusCode    int
	StatusMessage string
	Body          string
}

func (*WSError) Error

func (e *WSError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL