/** <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); } }
internal async Task <int> EnviarNotaContingencia(NotaFiscal notaFiscal, string cscId, string csc) { TNFe nfe = null; string qrCode = string.Empty; string newNodeXml = string.Empty; string nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe"; string digVal = string.Empty; int idNotaCopiaSeguranca = 0; var config = ConfiguracaoService.GetConfiguracao(); notaFiscal.Identificacao.DataHoraEntradaContigencia = config.DataHoraEntradaContingencia; notaFiscal.Identificacao.JustificativaContigencia = config.JustificativaContingencia; notaFiscal.Identificacao.TipoEmissao = notaFiscal.Identificacao.Modelo == Modelo.Modelo65 ? TipoEmissao.ContigenciaNfce : TipoEmissao.FsDa; notaFiscal.CalcularChave(); 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); } if (notaFiscal.Identificacao.Ambiente == Domain.Services.Identificacao.Ambiente.Homologacao) { notaFiscal.Produtos[0].Descricao = "NOTA FISCAL EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL"; } var refUri = "#NFe" + notaFiscal.Identificacao.Chave; var xml = Regex.Replace(XmlUtil.GerarXmlLoteNFe(notaFiscal, nFeNamespaceName), "<motDesICMS>1</motDesICMS>", string.Empty); XmlNode node = AssinaturaDigital.AssinarLoteComUmaNota(xml, refUri, certificado, ref digVal); 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.Replace("<infNFeSupl><qrCode /></infNFeSupl>", ""); } var document = new XmlDocument(); document.LoadXml(newNodeXml); node = document.DocumentElement; TEnviNFe lote = (TEnviNFe)XmlUtil.Deserialize <TEnviNFe>(node.OuterXml); nfe = lote.NFe[0]; //salvar nota PreEnvio aqui notaFiscal.Identificacao.Status = NFe.Repository.Status.CONTINGENCIA; var notaFiscalService = new NotaFiscalService(); idNotaCopiaSeguranca = await notaFiscalService.SalvarNotaFiscalPendenteAsync(notaFiscal, XmlUtil.GerarNfeProcXml(nfe, qrCode), notaFiscal.Identificacao.Ambiente); var notaFiscalEntity = await notaFiscalService.GetNotaFiscalByIdAsync(idNotaCopiaSeguranca, false); notaFiscalEntity.Status = (int)Status.CONTINGENCIA; string nfeProcXml = XmlUtil.GerarNfeProcXml(nfe, qrCode); await notaFiscalService.SalvarAsync(notaFiscalEntity, nfeProcXml); notaFiscal.QrCodeUrl = qrCode; return(idNotaCopiaSeguranca); }