public static TEnviNFe AssinaNotas(this TEnviNFe envi, X509Certificate2 certificate) { foreach (var nfe in envi.NFe) { nfe.GeraAssinatura(certificate); } return(envi); }
/// <summary> /// Tag principal <enviNFe> /// </summary> /// <returns></returns> public TEnviNFe enviarNfe() { //Objeto Principal - tag <enviNFe> TEnviNFe envioNfe = new TEnviNFe(); envioNfe.idLote = "000000000003605"; envioNfe.indSinc = TEnviNFeIndSinc.Item0; envioNfe.NFe = tnfeLista(); envioNfe.versao = "3.10"; //Retorna o objeto EnviarLoteRpsEnvio return(envioNfe); }
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); }
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."); } }
private MensagemRetornoTransmissaoNotasContingencia TransmitirLoteNotasFiscaisContingencia(List<string> nfeList, Modelo modelo) { var lote = new TEnviNFe { idLote = "999999", indSinc = TEnviNFeIndSinc.Item0, versao = "4.00", NFe = new TNFe[1] }; //qual a regra pra gerar o id? //apenas uma nota no lote lote.NFe[0] = new TNFe(); //Gera tag <NFe /> vazia para usar no replace var 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(); var ambiente = config.IsProducao ? Ambiente.Producao : Ambiente.Homologacao; var codigoUf = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), _emissorService.GetEmissor().Endereco.UF); X509Certificate2 certificado; var certificadoEntity = _certificadoRepository.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, Servico.AUTORIZACAO, codigoUf, certificado); var client = (NFeAutorizacao4SoapClient)servico.SoapClient; var result = client.nfeAutorizacaoLote(node); var retorno = (TRetEnviNFe)XmlUtil.Deserialize<TRetEnviNFe>(result.OuterXml); return new MensagemRetornoTransmissaoNotasContingencia { RetEnviNFeInfRec = (TRetEnviNFeInfRec)retorno.Item, TipoMensagem = TipoMensagem.Sucesso }; } catch (Exception e) { log.Error(e); if (!_isFirstTimeResending) { _isFirstTimeResending = true; return TransmitirLoteNotasFiscaisContingencia(nfeList, modelo); } _isFirstTimeResending = false; return new MensagemRetornoTransmissaoNotasContingencia { TipoMensagem = TipoMensagem.ServicoIndisponivel }; } }
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); } }
/** <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); }
/// <summary> /// Grava o lote no banco para envio.. /// </summary> /// <param name="notas"></param> /// <returns></returns> public bool GerarLoteEnvio(List <NFeEstadual> notas) { try { XmlSerializer xmlSerializer; //cria o lote.. var loteEnvio = new TEnviNFe() { idLote = getNewLoteEnvioNFeNumber(), indSinc = TEnviNFeIndSinc.Item1, versao = "3.10", NFe = new TNFe[notas.Count] }; //posicao do array de notas var i = 0; //percorro cada nf selecionada, já que serializei, vou deserializar.. foreach (var nf in notas) { //sei que eh um TNFe xmlSerializer = new XmlSerializer(typeof(TNFe)); //passo o conteudo do xml para StringReader e dps pro txtReaader TextReader r = new StringReader(nf.XmlNfe); //deSerializando... var nfDeserialized = xmlSerializer.Deserialize(r); //definindo o valor da posicao 'i' loteEnvio.NFe[i] = (TNFe)nfDeserialized; i++; } using (MemoryStream str = new MemoryStream()) { xmlSerializer = new XmlSerializer(typeof(TEnviNFe)); var setting = new XmlWriterSettings() { OmitXmlDeclaration = false, Encoding = Encoding.UTF8, Indent = false, NewLineHandling = NewLineHandling.None, NewLineChars = string.Empty }; var writer = XmlWriter.Create(str, setting); //configuracao do namespace do XML XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces(); xmlSerializerNamespaces.Add("", "http://www.portalfiscal.inf.br/nfe"); //serializando. xmlSerializer.Serialize(writer, loteEnvio, xmlSerializerNamespaces); //gravar o XML em string str.Position = 0; var sr = new StreamReader(str); var stringLote = sr.ReadToEnd(); var loteSave = new LoteEnvioNFe() { ConteudoLote = stringLote, NumeroLote = loteEnvio.idLote }; var ctx = new BalcaoContext(); var result = ctx.LoteEnvioNFeDao.Save(loteSave); if (result) { //se criou o lote com sucesso, atualize no painel o numero do lote notas.ForEach(n => { var nfPainelBd = ctx.NFeEstadualDao.Find(n.IdNfe); if (nfPainelBd != null) { nfPainelBd.IdLoteEnvio = loteSave.IdLoteNfe; ctx.NFeEstadualDao.Update(nfPainelBd); } }); return(true); } } return(false); } catch (Exception ex) { XMessageIts.ExceptionMessageDetails(ex, "Erro ao gerar o lote para envio das notas selecionadas", "Erro gerar lote para envio"); return(false); } }