コード例 #1
0
        private string ConcatenaTimbreRet(XElement entrada, string xmlFinal, XElement addenda, string rfc, string uuid)
        {
            XElement timbre      = XElement.Load(new StringReader(xmlFinal));
            XElement complemento = entrada.Elements(Constantes.RetencionNamesPace + "Complemento").FirstOrDefault <XElement>();

            if (complemento == null)
            {
                entrada.Add(new XElement(Constantes.RetencionNamesPace + "Complemento"));
                complemento = entrada.Elements(Constantes.RetencionNamesPace + "Complemento").FirstOrDefault <XElement>();
            }
            complemento.Add(timbre);
            if (addenda != null)
            {
                entrada.Add(addenda);
            }
            SidetecStringWriter tw = new SidetecStringWriter(Encoding.UTF8);

            entrada.Save(tw, SaveOptions.DisableFormatting);
            return(tw.ToString());
        }
コード例 #2
0
        public string CadenaOriginal(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                throw new ArgumentException("Archivo XML Inválido", "xml");
            }
            StringReader xmlInput = new StringReader(xml);

            XmlTextReader       xmlReader      = new XmlTextReader(xmlInput);
            SidetecStringWriter stringWriter   = new SidetecStringWriter(Encoding.UTF8);
            XmlTextWriter       transformedXml = new XmlTextWriter(stringWriter);

            try
            {
                xsltTransform.Transform(xmlReader, transformedXml);
            }
            catch (Exception ex)
            {
                Log.Error("Error(CadenaOriginal)" + ex);
                throw;
            }
            return(HttpUtility.HtmlDecode(stringWriter.ToString()));
        }
コード例 #3
0
        public static string TimbraRetencionString(string comprobante, empresa emp, bool consumeSaldo, bool vaidarUsuario)
        {
            ValidadorDatosRetencion val = new ValidadorDatosRetencion();
            string result = null;

            ServicioLocal.Business.TimbreRetenciones.TimbreFiscalDigital timbre = null;
            string   acuseSat = "";
            string   hash     = null;
            XElement element  = XElement.Parse(comprobante);

            Retenciones.Retenciones comp = TimbradoUtils.DesSerializarRetenciones(element);
            if (vaidarUsuario)
            {
                TimbradoUtils.ValidarUsuario(comp.Emisor.RFCEmisor);
            }
            Dictionary <int, string> dict = val.ProcesarCadenaRetencion(comprobante, ref result, ref timbre, ref acuseSat, ref hash);
            string result2;

            if (timbre != null && timbre.selloSAT != null && dict.Count == 0)
            {
                SerializadorTimbres sert = new SerializadorTimbres();
                if (ConfigurationManager.AppSettings["Pruebas"] == "true")
                {
                    timbre.selloSAT = "Inválido, Ambiente de pruebas";
                }
                string res          = sert.GetTimbreRenecionesXml(timbre);
                string cfdiTimbrado = result;
                string fecha        = comp.FechaExp;
                string rfcReceptor  = string.Empty;
                if (comp.Receptor.Nacionalidad == RetencionesReceptorNacionalidad.Nacional)
                {
                    RetencionesReceptorNacional rec = (RetencionesReceptorNacional)comp.Receptor.Item;
                    rfcReceptor = rec.RFCRecep;
                }
                else
                {
                    rfcReceptor = "XEXX010101000";
                }
                if (!TimbradoUtils.GuardaFactura(fecha, comp.Emisor.RFCEmisor, rfcReceptor, timbre.UUID, cfdiTimbrado, hash, emp, consumeSaldo, true))
                {
                    throw new Exception("Error al abrir el comprobante");
                }
                result2 = res;
            }
            else
            {
                if (timbre != null && timbre.selloSAT == null && dict.Count == 0)
                {
                    XElement el          = XElement.Parse(result);
                    XElement complemento = el.Elements(Constantes.RetencionNamesPace + "Complemento").FirstOrDefault <XElement>();
                    if (complemento != null)
                    {
                        XElement t = complemento.Elements(Constantes.CFDTimbreFiscalVersionNamespace + "TimbreFiscalDigital").FirstOrDefault <XElement>();
                        if (t != null)
                        {
                            SidetecStringWriter sw = new SidetecStringWriter(Encoding.UTF8);
                            t.Save(sw, SaveOptions.DisableFormatting);
                            result2 = sw.ToString();
                            return(result2);
                        }
                    }
                }
                if (dict.Count > 0)
                {
                    StringBuilder res2 = new StringBuilder();
                    foreach (KeyValuePair <int, string> d in dict)
                    {
                        res2.AppendLine(d.Key.ToString() + " - " + d.Value.ToString());
                    }
                    result2 = res2.ToString();
                }
                else
                {
                    TimbradoUtils.Logger.Error("Error al abrir el comprobante:" + comprobante);
                    result2 = "Error al abrir el comprobante";
                }
            }
            return(result2);
        }
コード例 #4
0
        public static string TimbraCfdiString(string comprobante, empresa emp)
        {
            ValidadorCFDi32 val    = new ValidadorCFDi32();
            string          result = null;

            ServicioLocal.Business.TimbreFiscalDigital timbre = null;
            string      acuseSat          = "";
            string      hash              = null;
            XElement    element           = XElement.Parse(comprobante);
            Comprobante comp              = TimbradoUtils.DesSerializar(element);
            Dictionary <int, string> dict = val.ProcesarCadena(comp.Emisor.Rfc, comprobante, ref result, ref timbre, ref acuseSat, ref hash);
            string result2;

            if (timbre != null && timbre.SelloSAT != null && dict.Count == 0)
            {
                if (!string.IsNullOrEmpty(comp.Confirmacion))
                {
                    using (NtLinkLocalServiceEntities db = new NtLinkLocalServiceEntities())
                    {
                        ConfirmacionTimbreWs33 C = db.ConfirmacionTimbreWs33.FirstOrDefault((ConfirmacionTimbreWs33 p) => p.Folio == comp.Folio && p.RfcEmisor == comp.Emisor.Rfc && p.RfcReceptor == comp.Receptor.Rfc);
                        C.procesado = new bool?(true);
                        db.ConfirmacionTimbreWs33.ApplyCurrentValues(C);
                        db.SaveChanges();
                    }
                }
                SerializadorTimbres sert = new SerializadorTimbres();
                if (ConfigurationManager.AppSettings["Pruebas"] == "true")
                {
                    timbre.SelloSAT = "Inválido, Ambiente de pruebas";
                }
                string res          = sert.GetTimbreXml(timbre);
                string cfdiTimbrado = result;
                if (ConfigurationManager.AppSettings["EnvioSat"] == "false")
                {
                    if (!TimbradoUtils.GuardaFactura(comp.Fecha, comp.Emisor.Rfc, comp.Receptor.Rfc, timbre.UUID, cfdiTimbrado, hash, emp, true, false))
                    {
                        throw new Exception("Error al abrir el comprobante");
                    }
                }
                result2 = res;
            }
            else
            {
                if (timbre != null && timbre.SelloSAT == null && dict.Count == 0)
                {
                    XElement el          = XElement.Parse(result);
                    XElement complemento = el.Elements(Constantes.CFDVersionNamespace + "Complemento").FirstOrDefault <XElement>();
                    if (complemento != null)
                    {
                        XElement t = complemento.Elements(Constantes.CFDTimbreFiscalVersionNamespace + "TimbreFiscalDigital").FirstOrDefault <XElement>();
                        if (t != null)
                        {
                            SidetecStringWriter sw = new SidetecStringWriter(Encoding.UTF8);
                            t.Save(sw, SaveOptions.DisableFormatting);
                            result2 = sw.ToString();
                            return(result2);
                        }
                    }
                }
                if (dict.Count > 0)
                {
                    StringBuilder res2 = new StringBuilder();
                    foreach (KeyValuePair <int, string> d in dict)
                    {
                        res2.AppendLine(d.Key.ToString() + " - " + d.Value.ToString());
                    }
                    result2 = res2.ToString();
                }
                else
                {
                    TimbradoUtils.Logger.Error("Error al abrir el comprobante:" + comprobante);
                    result2 = "Error al abrir el comprobante";
                }
            }
            return(result2);
        }
コード例 #5
0
        /// <summary>
        /// Timbra un comprobante
        /// </summary>
        /// <param name="comprobante">Documento para validar y timbrar</param>
        /// <returns>Una cadena con el timbre fiscal digital (TFD)</returns>
        public string TimbraCfdi(string comprobante, string userName, string password, string LLave, string aplicacion)
        {
            string result2;

            try
            {
                if (string.IsNullOrEmpty(userName))
                {
                    return("Nombre de usuario o contraseña incorrecta");
                }
                CertificadorService.Logger.Debug(userName);
                if (aplicacion == "CON")
                {
                    var Licencia = ValidarLicencia(LLave);
                    if (Licencia == false)
                    {
                        return("Licencia no valida");
                    }
                }
                MembershipUser x = NtLinkLogin.ValidateUser(userName, password);
                if (x == null)
                {
                    throw new FaultException("Nombre de usuario o contraseña incorrecta");
                }


                XElement element = XElement.Load(new StringReader(comprobante));
                ServicioLocal.Business.Comprobante comp = this.DesSerializar(element);
                empresa empres = new empresa();
                if (comp.Emisor != null && comp.Emisor.Rfc != null)
                {
                    string vemp = ValidarUsuario(comp.Emisor.Rfc, x, ref empres);
                    if (vemp != "OK")
                    {
                        return(vemp);
                    }
                }
                else
                {
                    return("Error: Los datos del emisor incompletos");
                }
                //-------------------------

                if (comprobante.Contains("<ieeh:IngresosHidrocarburos"))
                {
                    string erroIH = "";
                    IngresosHidrocarburos       I  = this.DesSerializarIH(element, ref erroIH);
                    ValidarIngresoHidrocarburos VI = new ValidarIngresoHidrocarburos();
                    erroIH = VI.ProcesarIngresoHidrocarburos(I, comp.Version, comp.TipoDeComprobante, comp.Total);
                    if (erroIH != "0")
                    {
                        result2 = erroIH;
                        return(result2);
                    }
                }
                if (comprobante.Contains("<gceh:GastosHidrocarburos"))
                {
                    string erroGH = "";
                    GastosHidrocarburos        I2  = this.DesSerializarGH(element, ref erroGH);
                    ValidarGastosHidrocarburos VI2 = new ValidarGastosHidrocarburos();
                    erroGH = VI2.ProcesarGastosHidrocarburos(I2, comp.Version, comp.TipoDeComprobante);
                    if (erroGH != "0")
                    {
                        result2 = erroGH;
                        return(result2);
                    }
                }
                ImpuestosLocales IL = null;
                if (comprobante.Contains("<implocal:ImpuestosLocales"))
                {
                    IL = this.DesSerializarImpuestosLocales(element);
                }
                bool pago10 = comprobante.Contains("pago10:Pagos");
                if (comp.TipoDeComprobante == "P" && !pago10)
                {
                    result2 = "CFDI no contiene el complemento PAGO";
                    return(result2);
                }
                if (pago10)
                {
                    ServicioLocal.Business.Pagoo.Comprobante pagoDatos = this.DesSerializarP(element);
                    ServicioLocal.Business.Complemento.Pagos pagoss    = this.DesSerializarPagos(element);
                    ValidarPago VP         = new ValidarPago();
                    string      ErrorPagos = VP.ProcesarPago(comp, pagoss, pagoDatos);
                    if (ErrorPagos != "0")
                    {
                        result2 = ErrorPagos;
                        return(result2);
                    }
                }
                bool          ComerExt    = comprobante.Contains("cce11:ComercioExterior");
                ValidarCFDI33 valida      = new ValidarCFDI33();
                string        errorCFDI33 = valida.ProcesarCFDI33(comp, comprobante, pago10, ComerExt, IL);
                if (errorCFDI33 != "0")
                {
                    CertificadorService.Logger.Error("Error al abrir el comprobante: " + errorCFDI33);
                    return(errorCFDI33);
                }
                bool          nomin12 = comprobante.Contains("nomina12:Nomina");
                List <Nomina> nom     = new List <Nomina>();
                if (nomin12)
                {
                    string erroresNom = null;
                    var    nomx       = this.DesSerializarNomina12(element, ref erroresNom);
                    nom.Add(nomx);
                    if (erroresNom != null)
                    {
                        result2 = erroresNom;
                        return(result2);
                    }
                }

                NtLinkSistema       nls           = new NtLinkSistema();
                string              result        = null;
                TimbreFiscalDigital timbre        = null;
                string              acuseSat      = "";
                string              hash          = null;
                string              erroresNomina = "0";
                if (ComerExt && erroresNomina == "0")
                {
                    string erroresComer           = null;
                    ValidarComercioExterior val   = new ValidarComercioExterior();
                    ComercioExterior        Comer = this.DesSerializarComercioExterior(element, ref erroresComer);
                    if (erroresComer != null)
                    {
                        result2 = erroresComer;
                        return(result2);
                    }
                    erroresNomina = val.ProcesarComercioExterior(Comer, comp);
                }
                if (nomin12 && erroresNomina == "0")
                {
                    erroresNomina = this.val.ProcesarNomina(nom, comp);
                    if (erroresNomina != "0")
                    {
                        return(erroresNomina);
                    }
                }

                Dictionary <int, string> dict = this.val.ProcesarCadena(comp.Emisor.Rfc, comprobante, ref result, ref timbre, ref acuseSat, ref hash);
                if (timbre != null && timbre.SelloSAT != null && dict.Count == 0)
                {
                    SerializadorTimbres sert = new SerializadorTimbres();
                    if (ConfigurationManager.AppSettings["Pruebas"] == "true")
                    {
                        timbre.SelloSAT = "Inválido, Ambiente de pruebas";
                    }
                    string res          = sert.GetTimbreXml(timbre);
                    string cfdiTimbrado = result;
                    if (ConfigurationManager.AppSettings["EnvioSat"] == "false")
                    {
                        if (!TimbradoUtils.GuardaFactura(comp.Fecha, comp.Emisor.Rfc, comp.Receptor.Rfc, timbre.UUID, cfdiTimbrado, hash, empres, true, false))
                        {
                            throw new Exception("Error al abrir el comprobante");
                        }
                    }
                    result2 = res;
                }
                else
                {
                    if (timbre != null && timbre.SelloSAT == null && dict.Count == 0)
                    {
                        XElement el          = XElement.Parse(result);
                        XElement complemento = el.Elements(Constantes.CFDVersionNamespace + "Complemento").FirstOrDefault <XElement>();
                        if (complemento != null)
                        {
                            XElement t = complemento.Elements(Constantes.CFDTimbreFiscalVersionNamespace + "TimbreFiscalDigital").FirstOrDefault <XElement>();
                            if (t != null)
                            {
                                SidetecStringWriter sw = new SidetecStringWriter(Encoding.UTF8);
                                t.Save(sw, SaveOptions.DisableFormatting);
                                result2 = sw.ToString();
                                return(result2);
                            }
                        }
                    }
                    if (dict.Count > 0)
                    {
                        StringBuilder res2 = new StringBuilder();
                        foreach (KeyValuePair <int, string> d in dict)
                        {
                            res2.AppendLine(d.Key.ToString() + " - " + d.Value.ToString());
                        }
                        result2 = res2.ToString();
                    }
                    else
                    {
                        CertificadorService.Logger.Error("Error al abrir el comprobante: " + comprobante);
                        result2 = "Error al abrir el comprobante";
                    }
                }
            }
            catch (Exception ex)
            {
                CertificadorService.Logger.Error(ex);
                result2 = "Error al abrir el comprobante: " + ex.Message;
            }
            return(result2);
        }
コード例 #6
0
        public bool EnvioSAT(TimbreWs33 topPComprobante)
        {
            try
            {
                GeneradorCadenasCfd gen = new GeneradorCadenasCfd();
                string     strLAcuseReciboSAT;
                byte[]     result;
                int        idErrorSAT;
                Encabezado encLMetadata;
                //SHA1 sha = new SHA1CryptoServiceProvider();
                string strComprobante = null;
                if (string.IsNullOrEmpty(topPComprobante.Xml))
                {
                    var directorio = Path.Combine(ConfigurationManager.AppSettings["RutaTimbrado"],
                                                  topPComprobante.RfcEmisor, topPComprobante.FechaFactura.ToString("yyyyMMdd"));
                    if (!Directory.Exists(directorio))
                    {
                        Directory.CreateDirectory(directorio);
                    }
                    var fileName = Path.Combine(directorio, "Comprobante_" + topPComprobante.Uuid + ".xml");
                    strComprobante = File.ReadAllText(fileName, Encoding.UTF8);
                }
                else
                {
                    strComprobante = topPComprobante.Xml;
                }

                Comprobante comprobante = GeneradorCfdi.GetComprobanteFromString(strComprobante);
                //byte[] bytLCadenaOriginal = Encoding.UTF8.GetBytes(gen.CadenaOriginal(strComprobante));
                //result = sha.ComputeHash(bytLCadenaOriginal);
                string strLRfcEmisor = comprobante.Emisor.Rfc;
                //  string strLHash = topPComprobante.Hash;
                //  string version = comprobante.Version;
                string version = "3.3";

                //string strLCertificadoSAT = comprobante.Complemento.timbreFiscalDigital.NoCertificadoSAT;
                string strLCertificadoSAT = ConfigurationManager.AppSettings["NoCertificadoPac"];

                string   strLUUID          = comprobante.Complemento.timbreFiscalDigital.UUID;
                DateTime datLFechaTimbrado = comprobante.Complemento.timbreFiscalDigital.FechaTimbrado;
                string   strLPathArchivo   = AppDomain.CurrentDomain.BaseDirectory +
                                             ConfigurationManager.AppSettings["PathXMLTemporales"] + Guid.NewGuid() + ".xml";
                //Quitar addenda si tiene
                XElement xe      = XElement.Load(new StringReader(strComprobante));
                XElement addenda = xe.Elements(Constantes.CFDVersionNamespace + "Addenda").FirstOrDefault();

                if (addenda != null)
                {
                    addenda.Remove();
                }
                var tw = new SidetecStringWriter(Encoding.UTF8);
                xe.Save(tw, SaveOptions.DisableFormatting);
                string xml = tw.ToString();
                //escribimos el archivo en una carpeta para que el proceso de envio SAT lo tome//
                File.WriteAllText(strLPathArchivo, xml, Encoding.UTF8);
                //armamos el encabezado//
                encLMetadata = new Encabezado(strLRfcEmisor, version, strLCertificadoSAT, strLUUID, datLFechaTimbrado, strLPathArchivo);

                Log.Info("Enviando CFDI al SAT.");
                Log.Info("Se enviará el comprobante con el identificador: " + topPComprobante.IdTimbre);
                Log.Info("Encabezado." + encLMetadata.version + "|" + encLMetadata.UUID + "|" + encLMetadata.NumeroCertificado + "|" + encLMetadata.RfcEmisor + "|" + encLMetadata.Xml);

                var acuseReciboSAT = EnviarCFDIalSAT(encLMetadata);

                if (acuseReciboSAT != null)
                {
                    idErrorSAT = acuseReciboSAT.CodEstatus.Equals("Comprobante Rechazado",
                                                                  StringComparison.InvariantCultureIgnoreCase)
                                     ? Convert.ToInt32(acuseReciboSAT.Incidencia[0].CodigoError)
                                     : 0;
                    if (idErrorSAT != 501 || idErrorSAT != 502)
                    {
                    }
                    var acuseStream   = new MemoryStream();
                    var xmlSerializer = new XmlSerializer(typeof(SAT.CFDI.Cliente.Procesamiento.ServicioRecepcionCFDI.Acuse));
                    xmlSerializer.Serialize(acuseStream, acuseReciboSAT);
                    acuseStream.Seek(0, SeekOrigin.Begin);
                    var acuseReader = new StreamReader(acuseStream);
                    strLAcuseReciboSAT = acuseReader.ReadToEnd();
                    var directorio = Path.Combine(ConfigurationManager.AppSettings["RutaTimbrado"],
                                                  topPComprobante.RfcEmisor, topPComprobante.FechaFactura.ToString("yyyyMMdd"));
                    if (!Directory.Exists(directorio))
                    {
                        Directory.CreateDirectory(directorio);
                    }
                    var fileName = Path.Combine(directorio, "Acuse_" + topPComprobante.Uuid + ".xml");
                    File.WriteAllText(fileName, strLAcuseReciboSAT);
                }
                else
                {
                    idErrorSAT         = 103;
                    strLAcuseReciboSAT = "";
                }
                //idErrorSAT = TraerEstatusSAT(strLAcuseReciboSAT);

                Log.Info("Código de retorno SAT: " + idErrorSAT);
                GuardarInformacion(topPComprobante, idErrorSAT, strLAcuseReciboSAT, acuseReciboSAT);

                File.Delete(strLPathArchivo);

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("Error al intentar enviar el CFD al SAT, Err:" + ex.ToString());
                return(false);
            }
        }
コード例 #7
0
        public bool EnvioSatRet(TimbreWs33 topPComprobante)
        {
            try
            {
                GeneradorCadenasCfd gen = new GeneradorCadenasCfd();
                string     strLAcuseReciboSAT;
                byte[]     result;
                int        idErrorSAT;
                Encabezado encLMetadata;
                SHA1       sha            = new SHA1CryptoServiceProvider();
                string     strComprobante = null;
                if (string.IsNullOrEmpty(topPComprobante.Xml))
                {
                    var directorio = Path.Combine(ConfigurationManager.AppSettings["RutaTimbrado"],
                                                  topPComprobante.RfcEmisor, topPComprobante.FechaFactura.ToString("yyyyMMdd"));
                    if (!Directory.Exists(directorio))
                    {
                        Directory.CreateDirectory(directorio);
                    }
                    var fileName = Path.Combine(directorio, "Comprobante_" + topPComprobante.Uuid + ".xml");
                    strComprobante = File.ReadAllText(fileName, Encoding.UTF8);
                }
                else
                {
                    strComprobante = topPComprobante.Xml;
                }
                Retenciones comprobante = TimbradoUtils.DesSerializarRetenciones(strComprobante);
                //byte[] bytLCadenaOriginal = Encoding.UTF8.GetBytes(gen.CadenaOriginal(strComprobante));
                //result = sha.ComputeHash(bytLCadenaOriginal);
                string strLRfcEmisor = comprobante.Emisor.RFCEmisor;
                string strLHash      = topPComprobante.Hash;
                //Quitar addenda si tiene
                XElement xe      = XElement.Load(new StringReader(strComprobante));
                XElement addenda = xe.Elements(Constantes.CFDVersionNamespace + "Addenda").FirstOrDefault();

                if (addenda != null)
                {
                    addenda.Remove();
                }
                var tw = new SidetecStringWriter(Encoding.UTF8);
                xe.Save(tw, SaveOptions.DisableFormatting);
                Log.Info("Enviando CFDI al SAT.");
                Log.Info("Se enviará el comprobante con el identificador: " + topPComprobante.IdTimbre);

                var acuseReciboSAT = ret.EnviarRetencion(strComprobante, topPComprobante.Uuid);
                if (acuseReciboSAT != null)
                {
                    idErrorSAT = acuseReciboSAT.codEstatus.Equals("Comprobante Rechazado",
                                                                  StringComparison.InvariantCultureIgnoreCase)
                                     ? Convert.ToInt32(acuseReciboSAT.listaIncidencia[0].CodigoError)
                                     : 0;
                    var acuseStream   = new MemoryStream();
                    var xmlSerializer = new XmlSerializer(typeof(CertificadorWs.Business.Retenciones.AcuseRecepcionRetencion));
                    xmlSerializer.Serialize(acuseStream, acuseReciboSAT);
                    acuseStream.Seek(0, SeekOrigin.Begin);
                    var acuseReader = new StreamReader(acuseStream);
                    strLAcuseReciboSAT = acuseReader.ReadToEnd();
                    var directorio = Path.Combine(ConfigurationManager.AppSettings["RutaTimbrado"],
                                                  topPComprobante.RfcEmisor, topPComprobante.FechaFactura.ToString("yyyyMMdd"));
                    if (!Directory.Exists(directorio))
                    {
                        Directory.CreateDirectory(directorio);
                    }
                    var fileName = Path.Combine(directorio, "Acuse_" + topPComprobante.Uuid + ".xml");
                    File.WriteAllText(fileName, strLAcuseReciboSAT);
                }
                else
                {
                    idErrorSAT         = 103;
                    strLAcuseReciboSAT = "";
                }
                //idErrorSAT = TraerEstatusSAT(strLAcuseReciboSAT);

                Log.Info("Código de retorno SAT: " + idErrorSAT);
                GuardarInformacion(topPComprobante, idErrorSAT, strLAcuseReciboSAT, acuseReciboSAT);

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("Error al intentar enviar el CFD al SAT, Err:" + ex.ToString());
                return(false);
            }
        }
コード例 #8
0
        public string TimbraCfdi(string userName, string password, string comprobante)
        {
            string erroresNomina = "0";

            if (!this.ValidCredentials(userName, password))
            {
                throw new UnauthorizedAccessException("Invalid Ntlink internal user and password combination");
            }
            string result2;

            try
            {
                XElement element = XElement.Load(new StringReader(comprobante));
                ServicioLocal.Business.Comprobante comp = this.DesSerializar(element);
                if (comprobante.Contains("<ieeh:IngresosHidrocarburos"))
                {
                    string erroIH = "";
                    IngresosHidrocarburos       I  = this.DesSerializarIH(element, ref erroIH);
                    ValidarIngresoHidrocarburos VI = new ValidarIngresoHidrocarburos();
                    erroIH = VI.ProcesarIngresoHidrocarburos(I, comp.Version, comp.TipoDeComprobante, comp.Total);
                    if (erroIH != "0")
                    {
                        result2 = erroIH;
                        return(result2);
                    }
                }
                if (comprobante.Contains("<gceh:GastosHidrocarburos"))
                {
                    string erroGH = "";
                    GastosHidrocarburos        I2  = this.DesSerializarGH(element, ref erroGH);
                    ValidarGastosHidrocarburos VI2 = new ValidarGastosHidrocarburos();
                    erroGH = VI2.ProcesarGastosHidrocarburos(I2, comp.Version, comp.TipoDeComprobante);
                    if (erroGH != "0")
                    {
                        result2 = erroGH;
                        return(result2);
                    }
                }
                ImpuestosLocales IL = null;
                if (comprobante.Contains("<implocal:ImpuestosLocales"))
                {
                    IL = this.DesSerializarImpuestosLocales(element);
                }
                bool pago10 = comprobante.Contains("pago10:Pagos");
                if (pago10)
                {
                    ServicioLocal.Business.Pagoo.Comprobante pagoDatos = this.DesSerializarP(element);
                    ServicioLocal.Business.Complemento.Pagos pagoss    = this.DesSerializarPagos(element);
                    ValidarPago VP         = new ValidarPago();
                    string      ErrorPagos = VP.ProcesarPago(comp, pagoss, pagoDatos);
                    if (ErrorPagos != "0")
                    {
                        result2 = ErrorPagos;
                        return(result2);
                    }
                }
                if (comprobante.Contains("<ine:INE "))
                {
                    string     erroINE = "";
                    INE        I3      = this.DesSerializarINE(element, ref erroINE);
                    ValidarINE VI3     = new ValidarINE();
                    erroINE = VI3.ProcesarINE(I3);
                    if (erroINE != "0")
                    {
                        result2 = erroINE;
                        return(result2);
                    }
                }
                bool          ComerExt    = comprobante.Contains("cce11:ComercioExterior");
                ValidarCFDI33 valida      = new ValidarCFDI33();
                string        errorCFDI33 = valida.ProcesarCFDI33(comp, comprobante, pago10, ComerExt, IL);
                if (errorCFDI33 != "0")
                {
                    CertificadorApps.Logger.Error("Error al abrir el comprobante: " + errorCFDI33);
                    result2 = errorCFDI33;
                }
                else
                {
                    if (comprobante.Contains("<ecc12:EstadoDeCuentaCombustible"))
                    {
                        string erroECC = "";
                        EstadoDeCuentaCombustible E = this.DesSerializarECC(element, ref erroECC);
                        ValidarECC VE = new ValidarECC();
                        erroECC = VE.ProcesarECC(E, comp.TipoDeComprobante, comp.Version);
                        if (erroECC != "0")
                        {
                            result2 = erroECC;
                            return(result2);
                        }
                    }
                    if (comp.Emisor != null && comp.Emisor.Rfc != null)
                    {
                        empresa empresa = TimbradoUtils.ValidarUsuarioSinSaldo(comp.Emisor.Rfc);
                        if (empresa == null)
                        {
                            CertificadorApps.Logger.Info(comp.Emisor.Rfc + " No encontrado");
                            result2 = "300 - El usuario con el que se quiere conectar es inválido";
                        }
                        else
                        {
                            string result = null;
                            TimbreFiscalDigital timbre = null;
                            string        acuseSat     = "";
                            string        hash         = null;
                            bool          nomin12      = comprobante.Contains("nomina12:Nomina");
                            List <Nomina> nom          = new List <Nomina>();
                            if (nomin12)
                            {
                                string erroresNom = null;
                                var    nomx       = this.DesSerializarNomina12(element, ref erroresNom);
                                nom.Add(nomx);
                                if (erroresNom != null)
                                {
                                    result2 = erroresNom;
                                    return(result2);
                                }
                            }
                            if (ComerExt && erroresNomina == "0")
                            {
                                string erroresComer           = null;
                                ValidarComercioExterior val   = new ValidarComercioExterior();
                                ComercioExterior        Comer = this.DesSerializarComercioExterior(element, ref erroresComer);
                                if (erroresComer != null)
                                {
                                    CertificadorApps.Logger.Error("Error al abrir el comprobante: " + erroresComer);
                                    result2 = erroresComer;
                                    return(result2);
                                }
                                erroresNomina = val.ProcesarComercioExterior(Comer, comp);
                            }
                            if (nomin12 && erroresNomina == "0")
                            {
                                erroresNomina = this._val.ProcesarNomina(nom, comp);
                            }
                            if (erroresNomina == "0")
                            {
                                Dictionary <int, string> dict = this._val.ProcesarCadena(comp.Emisor.Rfc, comprobante, ref result, ref timbre, ref acuseSat, ref hash);
                                if (timbre != null && timbre.SelloSAT != null && dict.Count == 0)
                                {
                                    if (!string.IsNullOrEmpty(comp.Confirmacion))
                                    {
                                        using (NtLinkLocalServiceEntities db = new NtLinkLocalServiceEntities())
                                        {
                                            ConfirmacionTimbreWs33 C = db.ConfirmacionTimbreWs33.FirstOrDefault((ConfirmacionTimbreWs33 p) => p.Folio == comp.Folio && p.RfcEmisor == comp.Emisor.Rfc && p.RfcReceptor == comp.Receptor.Rfc);
                                            C.procesado = new bool?(true);
                                            db.ConfirmacionTimbreWs33.ApplyCurrentValues(C);
                                            db.SaveChanges();
                                        }
                                    }
                                    SerializadorTimbres sert = new SerializadorTimbres();
                                    if (ConfigurationManager.AppSettings["Pruebas"] == "true")
                                    {
                                        timbre.SelloSAT = "Inválido, Ambiente de pruebas";
                                    }
                                    string res          = sert.GetTimbreXml(timbre);
                                    string cfdiTimbrado = result;
                                    if (ConfigurationManager.AppSettings["EnvioSat"] == "false")
                                    {
                                        if (!TimbradoUtils.GuardaFactura(comp.Fecha, comp.Emisor.Rfc, comp.Receptor.Rfc, timbre.UUID, cfdiTimbrado, hash, empresa, false, false))
                                        {
                                            throw new Exception("Error al abrir el comprobante");
                                        }
                                    }
                                    result2 = res;
                                }
                                else
                                {
                                    if (timbre != null && timbre.SelloSAT == null && dict.Count == 0)
                                    {
                                        XElement el          = XElement.Parse(result);
                                        XElement complemento = el.Elements(Constantes.CFDVersionNamespace + "Complemento").FirstOrDefault <XElement>();
                                        if (complemento != null)
                                        {
                                            XElement t = complemento.Elements(Constantes.CFDTimbreFiscalVersionNamespace + "TimbreFiscalDigital").FirstOrDefault <XElement>();
                                            if (t != null)
                                            {
                                                SidetecStringWriter sw = new SidetecStringWriter(Encoding.UTF8);
                                                t.Save(sw, SaveOptions.DisableFormatting);
                                                result2 = sw.ToString();
                                                return(result2);
                                            }
                                        }
                                    }
                                    if (dict.Count > 0)
                                    {
                                        StringBuilder res2 = new StringBuilder();
                                        foreach (KeyValuePair <int, string> d in dict)
                                        {
                                            res2.AppendLine(d.Key.ToString() + " - " + d.Value.ToString());
                                        }
                                        result2 = res2.ToString();
                                    }
                                    else
                                    {
                                        CertificadorApps.Logger.Error("Error al abrir el comprobante: " + comprobante);
                                        result2 = "Error al abrir el comprobante";
                                    }
                                }
                            }
                            else
                            {
                                CertificadorApps.Logger.Error("Error al abrir el comprobante: " + erroresNomina);
                                result2 = erroresNomina;
                            }
                        }
                    }
                    else
                    {
                        CertificadorApps.Logger.Error("Error al abrir el comprobante: " + comprobante);
                        result2 = "Error al abrir el comprobante";
                    }
                }
            }
            catch (Exception ex)
            {
                CertificadorApps.Logger.Error(ex);
                result2 = "Error al abrir el comprobante";
            }
            return(result2);
        }