示例#1
0
        internal static string GerarNfeProcXml(TNFe nfe, string urlQrCode, TProtNFe protocolo = null)
        {
            var nfeProc          = new TNfeProc();
            var nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";
            var nfeSerializada   = Serialize(nfe, nFeNamespaceName);

            nfeProc.NFe =
                (XmlSchemas.NfeAutorizacao.Retorno.NfeProc.TNFe)
                Deserialize <XmlSchemas.NfeAutorizacao.Retorno.NfeProc.TNFe>(nfeSerializada);

            if (nfeProc.NFe.infNFeSupl != null)
            {
                nfeProc.NFe.infNFeSupl.qrCode = "";
            }

            if (protocolo != null)
            {
                var protocoloSerializado = Serialize(protocolo, nFeNamespaceName);
                nfeProc.protNFe =
                    (XmlSchemas.NfeAutorizacao.Retorno.NfeProc.TProtNFe)
                    Deserialize <XmlSchemas.NfeAutorizacao.Retorno.NfeProc.TProtNFe>(protocoloSerializado);
            }
            else
            {
                nfeProc.protNFe = new XmlSchemas.NfeAutorizacao.Retorno.NfeProc.TProtNFe();
            }

            nfeProc.versao = "4.00";
            var result = Serialize(nfeProc, nFeNamespaceName).Replace("<motDesICMS>1</motDesICMS>", string.Empty);

            if (nfeProc.NFe.infNFeSupl != null)
            {
                result = result.Replace("<qrCode />", "<qrCode>" + urlQrCode + "</qrCode>")
                         .Replace("<NFe>", "<NFe xmlns=\"http://www.portalfiscal.inf.br/nfe\">");
            }
            else
            {
                result = result.Replace("<NFe>", "<NFe xmlns=\"http://www.portalfiscal.inf.br/nfe\">");
            }

            return(result);
        }
示例#2
0
        internal static string GerarXmlLoteNFe(NotaFiscal notaFiscal, string nFeNamespaceName)
        {
            var ide     = GetIdentificacao(notaFiscal);
            var emit    = GetEmitente(notaFiscal);
            var det     = GetDetalhamentoProdutos(notaFiscal);
            var pag     = GetPagamento(notaFiscal);
            var transp  = GetTransporte(notaFiscal);
            var infAdic = GetInformacaoAdicional(notaFiscal);
            var total   = GetTotal(notaFiscal);

            var infNFe = new TNFeInfNFe();

            if (notaFiscal.Destinatario != null)
            {
                var dest = GetDestinatario(notaFiscal);
                infNFe.dest = dest;
            }

            infNFe.ide     = ide;
            infNFe.emit    = emit;
            infNFe.det     = det;
            infNFe.pag     = pag;
            infNFe.transp  = transp;
            infNFe.infAdic = infAdic;
            infNFe.total   = total;
            infNFe.versao  = notaFiscal.VersaoLayout;
            infNFe.Id      = "NFe" + notaFiscal.Identificacao.Chave;

            var nfe = new TNFe();

            nfe.infNFe = infNFe;

            if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
            {
                nfe.infNFeSupl = new TNFeInfNFeSupl
                {
                    qrCode = "", urlChave = "http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx"
                }
            }
            ;
            else
            {
                nfe.infNFeSupl = null;
            }

            var nfeArray = new TNFe[1];

            nfeArray[0] = nfe;

            var lote = new TEnviNFe();

            lote.idLote  = "999999";              //qual a regra pra gerar o id?
            lote.indSinc = TEnviNFeIndSinc.Item1; //apenas uma nota no lote
            lote.versao  = "4.00";
            lote.NFe     = nfeArray;

            var parametroXml = Serialize(lote, nFeNamespaceName);

            parametroXml = parametroXml.Replace("<NFe>", "<NFe xmlns=\"http://www.portalfiscal.inf.br/nfe\">");

            return(parametroXml);
        }
示例#3
0
        public bool IsNotaFiscalValida(NotaFiscal notaFiscal, string cscId, string csc)
        {
            string qrCode = "";

            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();

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

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

            TNFe   nfe        = null;
            string newNodeXml = string.Empty;

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

                if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
                {
                    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];

                ValidadorXml.ValidarXml(node.OuterXml, "enviNFe_v4.00.xsd");

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
示例#4
0
        private RetornoNotaFiscal PreencheMensagemRetorno(XmlSchemas.NfeAutorizacao.Retorno.TProtNFe protocolo, string urlQrCode, TNFe nfe)
        {
            RetornoNotaFiscal mensagem = new RetornoNotaFiscal()
            {
                CodigoStatus    = protocolo.infProt.cStat,
                Motivo          = protocolo.infProt.xMotivo,
                Protocolo       = protocolo.infProt.nProt,
                UrlQrCode       = urlQrCode,
                DataAutorizacao = protocolo.infProt.dhRecbto,
                Xml             = XmlUtil.GerarNfeProcXml(nfe, urlQrCode, protocolo)
            };

            return(mensagem);
        }
示例#5
0
        private static async Task <NotaFiscalEntity> CorrigirNotaDuplicada(NotaFiscal notaFiscal, string qrCode, string nFeNamespaceName, X509Certificate2 certificado, TNFe nfe, int idNotaCopiaSeguranca, NotaFiscalEntity notaFiscalEntity)
        {
            var retornoConsulta = NFeConsulta.ConsultarNotaFiscal(notaFiscal.Identificacao.Chave, notaFiscal.Emitente.Endereco.CodigoUF, certificado,
                                                                  notaFiscal.Identificacao.Ambiente, notaFiscal.Identificacao.Modelo);

            var protSerialized   = XmlUtil.Serialize(retornoConsulta.Protocolo, nFeNamespaceName);
            var protDeserialized = (XmlSchemas.NfeAutorizacao.Retorno.TProtNFe)XmlUtil.Deserialize <XmlSchemas.NfeAutorizacao.Retorno.TProtNFe>(protSerialized);

            var notaFiscalService = new NotaFiscalService();

            notaFiscalEntity = await notaFiscalService.GetNotaFiscalByIdAsync(idNotaCopiaSeguranca, false);

            notaFiscalEntity.Status          = (int)Status.ENVIADA;
            notaFiscalEntity.DataAutorizacao = retornoConsulta.DhAutorizacao;

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

            await notaFiscalService.SalvarAsync(notaFiscalEntity, xmlNFeProc);

            return(notaFiscalEntity);
        }
示例#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);
            }
        }