Exemple #1
0
        public TRetConsReciNFe ConsultaRecLote2(TConsReciNFe consReciNFe, TRetEnviNFe retEnvNFe, X509Certificate2 cert)
        {
            XmlNode strRetorno = null;

            C_WebService.ListaUrl listaURL = default(C_WebService.ListaUrl);
            listaURL = WsUrls.BuscaURL(retEnvNFe.cUF, retEnvNFe.tpAmb);

            string nomeArquivoPedido  = _PastaLog + retEnvNFe.infRec.nRec + "-ped-rec.xml";
            string nomeArquivoRetProc = _PastaLog + retEnvNFe.infRec.nRec + "-pro-rec.xml";

            try
            {
                RetRecepcao2.NfeRetRecepcao2 wsMsg = default(RetRecepcao2.NfeRetRecepcao2);
                RetRecepcao2.nfeCabecMsg     cab   = new RetRecepcao2.nfeCabecMsg();

                //UF E VERSÃO DO CABEÇALHO
                cab.cUF         = PegarCodigoUF(retEnvNFe.cUF);
                cab.versaoDados = retEnvNFe.versao;

                //CRIA UMA INSTANCIA DA CONEXÃO COM O WEBSERVICE
                wsMsg = new RetRecepcao2.NfeRetRecepcao2(listaURL.UrlNfeRetRecepcao);

                //ASSOCIA CABEÇALHO NFE
                wsMsg.nfeCabecMsgValue = cab;

                //DEFINE TEMPO MAXIMO DE ESPERA POR RETORNO
                wsMsg.Timeout = 100000;

                //ASSOCIA CERTIFICADO A CONEXAO WEBSERVICE
                wsMsg.ClientCertificates.Add(cert);

                //DEFINE PROTOCOLO USADO NA CONEXÃO
                //wsMsg.SoapVersion = SoapProtocolVersion.Soap12

                //CRIA UM NOVO DOCUMENTO XML
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(Funcoes.RemoveNameSpaceFromXml(consReciNFe.Serialize()));
                xmldoc.Save(nomeArquivoPedido);

                //ENVIA CONSULTA PARA SEFAZ E OBTEM RETORNO EM FORMATO STRING
                strRetorno = wsMsg.nfeRetRecepcao2(xmldoc);

                TRetConsReciNFe retornoReciNFe = new TRetConsReciNFe();
                XmlDocument     retornoXML     = new XmlDocument();
                retornoXML.LoadXml(strRetorno.OuterXml);
                retornoXML.Save(nomeArquivoRetProc);
                retornoReciNFe            = TRetConsReciNFe.LoadFromFile(nomeArquivoRetProc);
                retornoReciNFe.XmlRetorno = retornoXML;

                return(retornoReciNFe);
            }
            catch (Exception)
            {
                throw new ACBr.Net.NFe.Exceptions.ConsultaRecLote2Exception("Falha ao consultar o recebimento de lote de NFe.", consReciNFe, retEnvNFe, cert);
            }
        }
Exemple #2
0
        public TRetConsReciNFe ConsultarLote(TConsReciNFe consRecibo, TRetEnviNFe retEnvio)
        {
            throw new NotImplementedException("Trocar para consulta de RetAutorizacao");

            /*var ws = new C_WebService(Configuracao.PastaLog);
             * var reciboNFe = ws.ConsultaRecLote2(consRecibo, retEnvio, Certificado);
             * if (reciboNFe.protNFe == null) return reciboNFe;
             * foreach (var item in reciboNFe.protNFe)
             * {
             *  var nota = NotasFiscais.FirstOrDefault(n => n.NFe.infNFe.Id == "NFe" + item.infProt.chNFe);
             *  if (nota == null) continue;
             *  nota.protNFe = item;
             *
             *  if (item.infProt.cStat == "100")
             *  {
             *      SalvarNFe(ref nota);
             *  }
             * }
             * return reciboNFe;*/
        }
 public ConsultaRecLote2Exception(string message, TConsReciNFe consReciNFe, TRetEnviNFe retEnvNFe, X509Certificate2 cert) : base(message)
 {
     this.consReciNFe = consReciNFe;
     this.retEnvNFe   = retEnvNFe;
     this.cert        = cert;
 }
Exemple #4
0
        public TRetEnviNFe EnviaLote2(HiperNFe Notas, int NumLote)
        {
            XmlNode strRetorno = null;
            dynamic xmldoc     = new XmlDocument();

            ListaUrl listaURL = default(ListaUrl);

            listaURL = WsUrls.BuscaURL(Notas.Configuracao.CodUF, Notas.Configuracao.Ambiente);

            string nomeArquivoLote    = _PastaLog + NumLote.ToString() + "-env-lot.xml";
            string nomeArquivoRetLote = _PastaLog + NumLote.ToString() + "-rec.xml";

            try
            {
                TEnviNFe LoteNFe = new TEnviNFe();
                LoteNFe.idLote = NumLote.ToString();
                LoteNFe.versao = Notas.Configuracao.Versao;
                // ERROR: Not supported in C#: ReDimStatement

                int indice = 0;
                LoteNFe.NFe = new TNFe[Notas.NotasFiscais.Count];
                foreach (TNfeProc nota in Notas.NotasFiscais)
                {
                    LoteNFe.NFe[indice] = nota.NFe;
                    indice += 1;
                }
                LoteNFe.GeraLoteNFe(nomeArquivoLote);
                xmldoc.Load(nomeArquivoLote);
                //Carrega o arquivo XML

                Recepcao2.NfeRecepcao2 wsMsg = default(Recepcao2.NfeRecepcao2);
                Recepcao2.nfeCabecMsg  cab   = new Recepcao2.nfeCabecMsg();

                //UF E VERSÃO DO CABEÇALHO
                cab.cUF         = PegarCodigoUF(Notas.Configuracao.CodUF);
                cab.versaoDados = LoteNFe.versao;

                //CABEÇALHO USADA PARA ENVIO DE LOTE
                wsMsg = new Recepcao2.NfeRecepcao2(listaURL.UrlNfeRecepcao);
                wsMsg.nfeCabecMsgValue = cab;

                wsMsg.Timeout = 100000;
                wsMsg.ClientCertificates.Add(Notas.Certificado);
                wsMsg.SoapVersion = SoapProtocolVersion.Soap12;

                xmldoc.Save(nomeArquivoLote);
                //RETORNO DA SEFAZ
                strRetorno = wsMsg.nfeRecepcaoLote2(xmldoc);
                TRetEnviNFe retornoEnvio = new TRetEnviNFe();
                XmlDocument retornoXML   = new XmlDocument();
                retornoXML.LoadXml(strRetorno.OuterXml);
                retornoXML.Save(nomeArquivoRetLote);
                retornoEnvio = TRetEnviNFe.LoadFromFile(nomeArquivoRetLote);

                return(retornoEnvio);
            }
            catch (Exception)
            {
                throw new ACBr.Net.NFe.Exceptions.EnviaLote2Exception("Falha ao enviar o lote de NFe.");
            }
        }
 public ConsultaRecLote2Exception(string message, TConsReciNFe consReciNFe, TRetEnviNFe retEnvNFe, X509Certificate2 cert): base(message)
 {       
     this.consReciNFe = consReciNFe;
     this.retEnvNFe = retEnvNFe;
     this.cert = cert;
 }
Exemple #6
0
        /** <exception cref="Exception"/>
         * <summary>Responsável pelo envio da Nota Fiscal para a SEFAZ.</summary>
         */
        internal async Task <int> EnviarNotaFiscalAsync(NotaFiscal notaFiscal, string cscId, string csc)
        {
            string           qrCode               = "";
            TNFe             nfe                  = null;
            string           newNodeXml           = string.Empty;
            int              idNotaCopiaSeguranca = 0;
            NotaFiscalEntity notaFiscalEntity     = null;

            string refUri           = "#NFe" + notaFiscal.Identificacao.Chave;
            string digVal           = "";
            string nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";

            X509Certificate2 certificado;

            var certificadoEntity = new CertificadoRepository(new NFeContext()).GetCertificado();

            certificado = EscolherCertificado(certificadoEntity);

            var     xml  = Regex.Replace(XmlUtil.GerarXmlLoteNFe(notaFiscal, nFeNamespaceName), "<motDesICMS>1</motDesICMS>", string.Empty);
            XmlNode node = AssinaturaDigital.AssinarLoteComUmaNota(xml, refUri, certificado, ref digVal);

            try
            {
                var codigoUF = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), notaFiscal.Emitente.Endereco.UF);

                if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
                {
                    //NFC-e tem QrCode obrigatório
                    qrCode = QrCodeUtil.GerarQrCodeNFe(notaFiscal.Identificacao.Chave, notaFiscal.Destinatario, digVal, notaFiscal.Identificacao.Ambiente,
                                                       notaFiscal.Identificacao.DataHoraEmissao, notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe.ToString("F", CultureInfo.InvariantCulture),
                                                       notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms.ToString("F", CultureInfo.InvariantCulture), cscId, csc, notaFiscal.Identificacao.TipoEmissao);

                    newNodeXml = node.InnerXml.Replace("<qrCode />", "<qrCode>" + qrCode + "</qrCode>");
                }
                else
                {
                    newNodeXml = node.InnerXml;
                }

                var document = new XmlDocument();
                document.LoadXml(newNodeXml);
                node = document.DocumentElement;

                TEnviNFe lote = (TEnviNFe)XmlUtil.Deserialize <TEnviNFe>(node.OuterXml);
                nfe = lote.NFe[0];

                var servico = ServiceFactory.GetService(notaFiscal.Identificacao.Modelo, notaFiscal.Identificacao.Ambiente, Factory.Servico.AUTORIZACAO, codigoUF, certificado);
                var client  = (NFeAutorizacao4.NFeAutorizacao4SoapClient)servico.SoapClient;

                //salvar nota PreEnvio aqui
                notaFiscal.Identificacao.Status = NFe.Repository.Status.PENDENTE;

                var notaFiscalService = new NotaFiscalService();

                idNotaCopiaSeguranca = await notaFiscalService.SalvarNotaFiscalPendenteAsync(notaFiscal, XmlUtil.GerarNfeProcXml(nfe, qrCode), notaFiscal.Identificacao.Ambiente);

                XmlNode     result  = client.nfeAutorizacaoLote(node);
                TRetEnviNFe retorno = (TRetEnviNFe)XmlUtil.Deserialize <TRetEnviNFe>(result.OuterXml);
                XmlSchemas.NfeAutorizacao.Retorno.TProtNFe protocolo = (XmlSchemas.NfeAutorizacao.Retorno.TProtNFe)retorno.Item; //existem dois valores possíveis de retorno (esse aqui só vale para lote com 1 nota)

                if (protocolo.infProt.cStat.Equals("100"))
                {
                    notaFiscalEntity = await notaFiscalService.GetNotaFiscalByIdAsync(idNotaCopiaSeguranca, false);

                    notaFiscalEntity.Status          = (int)Status.ENVIADA;
                    notaFiscalEntity.DataAutorizacao = DateTime.ParseExact(protocolo.infProt.dhRecbto, "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture);

                    notaFiscalEntity.Protocolo = protocolo.infProt.nProt;
                    string xmlNFeProc = XmlUtil.GerarNfeProcXml(nfe, qrCode, protocolo);

                    await notaFiscalService.SalvarAsync(notaFiscalEntity, xmlNFeProc);
                }
                else
                {
                    if (protocolo.infProt.xMotivo.Contains("Duplicidade"))
                    {
                        notaFiscalEntity = await CorrigirNotaDuplicada(notaFiscal, qrCode, nFeNamespaceName, certificado, nfe, idNotaCopiaSeguranca, notaFiscalEntity);
                    }
                    else
                    {
                        //Nota continua com status pendente nesse caso
                        XmlUtil.SalvarXmlNFeComErro(notaFiscal, node);
                        string mensagem = string.Concat("O xml informado é inválido de acordo com o validar da SEFAZ. Nota Fiscal não enviada!", "\n", protocolo.infProt.xMotivo);
                        throw new ArgumentException(mensagem);
                    }
                }

                notaFiscal.QrCodeUrl            = qrCode;
                notaFiscal.Identificacao.Status = Status.ENVIADA;
                notaFiscal.DhAutorizacao        = notaFiscalEntity.DataAutorizacao.ToString("dd/MM/yyyy HH:mm:ss");
                notaFiscal.DataHoraAutorização  = notaFiscalEntity.DataAutorizacao;
                notaFiscal.ProtocoloAutorizacao = notaFiscalEntity.Protocolo;
                return(idNotaCopiaSeguranca);
            }
            catch (Exception e)
            {
                var codigoUF = notaFiscal.Identificacao.UF;
                var ambiente = notaFiscal.Identificacao.Ambiente;

                if (e.InnerException is WebException)
                {
                    throw new Exception("Serviço indisponível ou sem conexão com a internet.", e.InnerException);
                }

                try
                {
                    notaFiscalEntity = await VerificarSeNotaFoiEnviada(notaFiscal, cscId, csc, qrCode, nfe, idNotaCopiaSeguranca, notaFiscalEntity, nFeNamespaceName, certificado);
                }
                catch (Exception retornoConsultaException)
                {
                    EscreverLogErro(e);
                    EscreverLogErro(retornoConsultaException);
                    XmlUtil.SalvarXmlNFeComErro(notaFiscal, node);
                    throw retornoConsultaException;
                }

                notaFiscal.QrCodeUrl            = qrCode;
                notaFiscal.Identificacao.Status = Status.ENVIADA;
                notaFiscal.DhAutorizacao        = notaFiscalEntity.DataAutorizacao.ToString("dd/MM/yyyy HH:mm:ss");
                notaFiscal.DataHoraAutorização  = notaFiscalEntity.DataAutorizacao;
                notaFiscal.ProtocoloAutorizacao = notaFiscalEntity.Protocolo;
                return(idNotaCopiaSeguranca);
            }
        }
        private MensagemRetornoTransmissaoNotasContingencia TransmitirLoteNotasFiscaisContingencia(List <string> nfeList, Modelo modelo)
        {
            var lote = new TEnviNFe();

            lote.idLote  = "999999";              //qual a regra pra gerar o id?
            lote.indSinc = TEnviNFeIndSinc.Item0; //apenas uma nota no lote
            lote.versao  = "4.00";
            lote.NFe     = new TNFe[1];
            lote.NFe[0]  = new TNFe(); //Gera tag <NFe /> vazia para usar no replace

            string parametroXML = XmlUtil.Serialize(lote, "http://www.portalfiscal.inf.br/nfe");

            parametroXML = parametroXML.Replace("<NFe />", XmlUtil.GerarXmlListaNFe(nfeList)).Replace("<motDesICMS>1</motDesICMS>", string.Empty);

            var document = new XmlDocument();

            document.LoadXml(parametroXML);
            var node = document.DocumentElement;

            var config = ConfiguracaoService.GetConfiguracao();

            Ambiente         ambiente = config.IsProducao ? Ambiente.Producao : Ambiente.Homologacao;
            var              codigoUF = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), EmissorService.GetEmissor().Endereco.UF);
            X509Certificate2 certificado;

            var certificadoEntity = new CertificadoRepository(new NFeContext()).GetCertificado();

            if (!string.IsNullOrWhiteSpace(certificadoEntity.Caminho))
            {
                certificado = CertificateManager.GetCertificateByPath(certificadoEntity.Caminho,
                                                                      RijndaelManagedEncryption.DecryptRijndael(certificadoEntity.Senha));
            }
            else
            {
                certificado = CertificateManager.GetCertificateBySerialNumber(certificadoEntity.NumeroSerial, false);
            }

            try
            {
                var servico = ServiceFactory.GetService(modelo, ambiente, Factory.Servico.AUTORIZACAO, codigoUF, certificado);
                var client  = (NFeAutorizacao4.NFeAutorizacao4SoapClient)servico.SoapClient;

                XmlNode     result  = client.nfeAutorizacaoLote(node);
                TRetEnviNFe retorno = (TRetEnviNFe)XmlUtil.Deserialize <TRetEnviNFe>(result.OuterXml);

                return(new MensagemRetornoTransmissaoNotasContingencia()
                {
                    RetEnviNFeInfRec = (TRetEnviNFeInfRec)retorno.Item,
                    TipoMensagem = TipoMensagem.Sucesso
                });
            }
            catch (Exception)
            {
                if (!_isFirstTimeResending)
                {
                    _isFirstTimeResending = true;
                    return(TransmitirLoteNotasFiscaisContingencia(nfeList, modelo));
                }
                else
                {
                    _isFirstTimeResending = false;

                    return(new MensagemRetornoTransmissaoNotasContingencia()
                    {
                        TipoMensagem = TipoMensagem.ServicoIndisponivel
                    });
                }
            }
        }