public string CancelaRetencion(string userName, string password, string uuid, string rfc)
        {
            string result;

            try
            {
                CertificadorApps.Logger.Debug(userName);
                MembershipUser x = NtLinkLogin.ValidateUser(userName, password);
                if (x == null)
                {
                    throw new FaultException("Nombre de usuario o contraseña incorrecta");
                }
                empresa empresa = NtLinkUsuarios.GetEmpresaByUserId(x.ProviderUserKey.ToString());
                if (empresa == null)
                {
                    throw new FaultException("300 - El usuario con el que se quiere conectar es inválido");
                }
                if (empresa.Bloqueado)
                {
                    CertificadorApps.Logger.Info(empresa.RFC + "-> Bloqueado");
                    throw new FaultException("El RFC del emisor se encuentra bloqueado, favor de ponerse en contacto con atención al cliente");
                }
                NtLinkSistema nls     = new NtLinkSistema();
                Sistemas      sistema = nls.GetSistema((int)empresa.idSistema.Value);
                if (sistema.Bloqueado)
                {
                    CertificadorApps.Logger.Info(sistema.Rfc + "-> Bloqueado");
                    throw new FaultException("El RFC del emisor se encuentra dado de baja, favor de ponerse en contacto con atención a clientes");
                }
                Cancelador cancelador = new Cancelador();
                string     respuesta  = null;
                string     acuse      = null;
                int        resultado  = cancelador.CancelarRet(uuid, rfc, ref respuesta, ref acuse);
                CertificadorApps.Logger.Info(acuse);
                if (resultado == 1201 || resultado == 1202)
                {
                    result = acuse;
                }
                else
                {
                    result = respuesta;
                }
            }
            catch (FaultException ex)
            {
                CertificadorApps.Logger.Error(ex);
                result = ex.Message;
            }
            catch (Exception ex2)
            {
                CertificadorApps.Logger.Error("Error al cancelar el comprobante:" + uuid, ex2);
                result = "Error al abrir el comprobante";
            }
            return(result);
        }
Example #2
0
 public ClienteNtLink ObtenerDatosCliente(string userName, string password)
 {
     try
     {
         Logger.Debug(userName);
         var x = NtLinkLogin.ValidateUser(userName, password);
         if (x == null)
         {
             throw new FaultException("Nombre de usuario o contraseña incorrecta");
         }
         var           empresa = NtLinkUsuarios.GetEmpresaByUserId(x.ProviderUserKey.ToString());
         NtLinkSistema sis     = new NtLinkSistema();
         var           sistema = sis.GetSistema((int)empresa.idSistema.Value);
         if (sistema != null)
         {
             return(new ClienteNtLink
             {
                 Ciudad = sistema.Ciudad,
                 Colonia = sistema.Colonia,
                 Estado = sistema.Estado,
                 Contacto = sistema.Contacto,
                 Cp = sistema.Cp,
                 RazonSocial = sistema.RazonSocial,
                 Direccion = sistema.Direccion,
                 Email = sistema.Email,
                 Empresas = sistema.Empresas.HasValue ? sistema.Empresas.Value : 0,
                 FechaContrato = sistema.FechaContrato.HasValue ? sistema.FechaContrato.Value : DateTime.MinValue,
                 //Folios = sistema.Folios.HasValue ? sistema.Folios.Value : 0,
                 RegimenFiscal = sistema.RegimenFiscal,
                 Rfc = sistema.Rfc,
                 Sucursales = sistema.Sucursales.HasValue ? sistema.Sucursales.Value : 0,
                 Telefono = sistema.Telefono,
                 TimbresContratados = sistema.TimbresContratados.HasValue ? sistema.TimbresContratados.Value : 0,
                 Usuarios = sistema.Usuarios.HasValue ? sistema.Usuarios.Value : 0
             });
         }
         return(null);
     }
     catch (FaultException ee)
     {
         Logger.Warn(ee);
         throw;
     }
     catch (Exception ee)
     {
         Logger.Error(ee);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
         return(null);
     }
 }
Example #3
0
        public void RegistraEmpresa(EmpresaNtLink nuevaEmpresa, byte[] llave, byte[] certificado, string userName, string password)
        {
            Logger.Debug(userName);
            var x = NtLinkLogin.ValidateUser(userName, password);

            if (x == null)
            {
                throw new FaultException("Nombre de usuario o contraseña incorrecta");
            }
            NtLinkEmpresa nle = new NtLinkEmpresa();

            try
            {
                empresa emp = new empresa
                {
                    RazonSocial = nuevaEmpresa.RazonSocial,
                    RFC         = nuevaEmpresa.Rfc,
                    CURP        = nuevaEmpresa.Curp,
                    Ciudad      = nuevaEmpresa.Ciudad,
                    Colonia     = nuevaEmpresa.Colonia,
                    CP          = nuevaEmpresa.Cp,
                    Contacto    = nuevaEmpresa.Contacto,
                    Direccion   = nuevaEmpresa.Direccion,
                    Email       = nuevaEmpresa.Email,
                    Estado      = nuevaEmpresa.Estado,
                    Linea       = "A",

                    RegimenFiscal = nuevaEmpresa.RegimenFiscal,
                    Telefono      = nuevaEmpresa.Telefono
                };
                nle.Save(emp, certificado, llave, null, null);
            }
            catch (FaultException ee)
            {
                Logger.Warn(ee);
                throw;
            }
            catch (Exception ee)
            {
                Logger.Error(ee);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                throw new FaultException("Error al registrar la empresa");
            }
        }
        public string ObtenerEmpresasFolio(string userName, string password, string RFC)
        {
            ServicioTimbradoMovil.Logger.Debug(userName);
            MembershipUser x = NtLinkLogin.ValidateUser(userName, password);

            if (x == null)
            {
                throw new FaultException("Nombre de usuario o contraseña incorrecta");
            }
            empresa empresa = new empresa();

            if (!TimbradoUtils.EmpresaMultipleRFC(RFC))
            {
                empresa = TimbradoUtils.ValidarUsuario(RFC);
            }
            else
            {
                empresa = NtLinkUsuarios.GetEmpresaByUserId(x.ProviderUserKey.ToString());
                empresa = TimbradoUtils.ValidarUsuarioMultiple(empresa);
            }
            if (empresa == null)
            {
                throw new FaultException("300 - El usuario con el que se quiere conectar es inválido");
            }
            if (empresa.Bloqueado)
            {
                ServicioTimbradoMovil.Logger.Info(empresa.RFC + "-> Bloqueado");
                throw new FaultException("El RFC del emisor se encuentra bloqueado, favor de ponerse en contacto con atención al cliente");
            }
            string result;

            if (empresa == null)
            {
                result = null;
            }
            else if (empresa.Folio == null)
            {
                result = "0";
            }
            else
            {
                result = empresa.Folio;
            }
            return(result);
        }
Example #5
0
 public List <EmpresaNtLink> ObtenerEmpresas(string userName, string password)
 {
     try
     {
         Logger.Debug(userName);
         var x = NtLinkLogin.ValidateUser(userName, password);
         if (x == null)
         {
             throw new FaultException("Nombre de usuario o contraseña incorrecta");
         }
         var           empresa = NtLinkUsuarios.GetEmpresaByUserId(x.ProviderUserKey.ToString());
         NtLinkSistema sis     = new NtLinkSistema();
         var           sistema = sis.GetSistema((int)empresa.idSistema.Value);
         var           nle     = new NtLinkEmpresa();
         var           lista   = nle.GetList("Administrador", empresa.IdEmpresa, sistema.IdSistema);
         if (lista != null)
         {
             return(lista.Select(p => new EmpresaNtLink()
             {
                 Ciudad = p.Ciudad,
                 Colonia = p.Colonia,
                 Estado = p.Estado,
                 Contacto = p.Contacto,
                 Cp = p.CP,
                 RazonSocial = p.RazonSocial,
                 Direccion = p.Direccion,
                 Email = p.Email,
                 RegimenFiscal = p.RegimenFiscal,
                 Rfc = p.RFC,
                 Telefono = p.Telefono,
                 //PassKey = p.PassKey
             }).ToList());
         }
         return(null);
     }
     catch (Exception ee)
     {
         Logger.Error(ee);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
         return(null);
     }
 }
        public ResultadoValidacion Validar(string userName, string password, string comprobante)
        {
            Logger.Debug(userName);
            Logger.Info("Timbrando:" + comprobante);
            var x = NtLinkLogin.ValidateUser(userName, password);

            if (x == null)
            {
                throw new FaultException("Nombre de usuario o contraseña incorrecta");
            }
            try
            {
                Logger.Info("Validando: " + comprobante);
                ValidadorCfdi val = new ValidadorCfdi();
                comprobante = comprobante.Replace("\ufeff", "");
                string version = null;
                using (var reader = new XmlTextReader(new StringReader(comprobante)))
                {
                    while (reader.Read())
                    {
                        if (reader.LocalName == "Comprobante")
                        {
                            version = reader.GetAttribute("version");
                            break;
                        }
                    }
                }

                return(val.Validar(comprobante, version));
            }
            catch (Exception ee)
            {
                Logger.Error(ee);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                return(new ResultadoValidacion()
                {
                    Valido = false, Entrada = null
                });
            }
        }
        public TimbradoResponse TimbraCfdiMovil(string userName, string password, string comprobante)
        {
            TimbradoResponse result2;

            try
            {
                string erroresNomina = "0";
                ServicioTimbradoMovil.Logger.Debug(userName);
                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);
                ImpuestosLocales IL = null;
                if (comprobante.Contains("<ine:INE "))
                {
                    string     erroINE = "";
                    INE        I       = this.DesSerializarINE(element, ref erroINE);
                    ValidarINE VI      = new ValidarINE();
                    erroINE = VI.ProcesarINE(I);
                    if (erroINE != "0")
                    {
                        result2 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = erroINE
                        };
                        return(result2);
                    }
                }
                if (comprobante.Contains("<ecc11: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 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = erroECC
                        };
                        return(result2);
                    }
                }
                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 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = ErrorPagos
                        };
                        return(result2);
                    }
                }
                NtLinkClientes nlc     = new NtLinkClientes();
                clientes       cliente = nlc.GetCliente(comp.Receptor.Rfc);
                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 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = erroresNom
                        };
                        return(result2);
                    }
                }
                bool ComerExt = comprobante.Contains("cce11:ComercioExterior");
                if (comp.Emisor != null && comp.Emisor.Rfc != null)
                {
                    empresa empresa = new empresa();
                    if (!TimbradoUtils.EmpresaMultipleRFC(comp.Emisor.Rfc))
                    {
                        empresa = TimbradoUtils.ValidarUsuario(comp.Emisor.Rfc);
                    }
                    else
                    {
                        empresa = NtLinkUsuarios.GetEmpresaByUserId(x.ProviderUserKey.ToString());
                        empresa = TimbradoUtils.ValidarUsuarioMultiple(empresa);
                    }
                    if (empresa == null)
                    {
                        result2 = null;
                    }
                    else
                    {
                        string result = null;
                        TimbreFiscalDigital timbre = null;
                        string acuseSat            = "";
                        string hash = null;
                        if (ComerExt && erroresNomina == "0")
                        {
                            string erroresComer           = null;
                            ValidarComercioExterior val   = new ValidarComercioExterior();
                            ComercioExterior        Comer = this.DesSerializarComercioExterior(element, ref erroresComer);
                            if (erroresComer != null)
                            {
                                result2 = new TimbradoResponse
                                {
                                    Valido           = false,
                                    DescripcionError = erroresComer
                                };
                                return(result2);
                            }
                            erroresNomina = val.ProcesarComercioExterior(Comer, comp);
                        }
                        if (nomin12 && erroresNomina == "0")
                        {
                            erroresNomina = this._val.ProcesarNomina(nom, comp);
                        }
                        if (erroresNomina == "0")
                        {
                            try
                            {
                                string           path      = Path.Combine(ConfigurationManager.AppSettings["Resources"], empresa.RFC, "Certs");
                                X509Certificate2 cert      = new X509Certificate2(Path.Combine(path, "csd.cer"));
                                string           rutaLlave = Path.Combine(path, "csd.key");
                                if (File.Exists(rutaLlave + ".pem"))
                                {
                                    rutaLlave += ".pem";
                                }
                                ServicioTimbradoMovil.Logger.Debug("Ruta Llave " + rutaLlave);
                                if (!File.Exists(rutaLlave))
                                {
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = "Error certificado de la empresa no está cargado en el sistema"
                                    };
                                    return(result2);
                                }
                                GeneradorCfdi gen     = new GeneradorCfdi();
                                string        sellado = gen.GenerarCfdSinTimbre(comp, cert, rutaLlave, empresa.PassKey, comprobante);
                                if (sellado == null)
                                {
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = "Error al sellar el comprobante: al sellar"
                                    };
                                    return(result2);
                                }
                                comprobante = sellado;
                            }
                            catch (FaultException ex)
                            {
                                ServicioTimbradoMovil.Logger.Error(ex);
                                result2 = new TimbradoResponse
                                {
                                    Valido           = false,
                                    DescripcionError = ex.Message
                                };
                                return(result2);
                            }
                            ValidarCFDI33 valida      = new ValidarCFDI33();
                            string        errorCFDI33 = valida.ProcesarCFDI33(comp, comprobante, pago10, ComerExt, IL);
                            if (errorCFDI33 != "0")
                            {
                                result2 = new TimbradoResponse
                                {
                                    Valido           = false,
                                    DescripcionError = errorCFDI33
                                };
                            }
                            else
                            {
                                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();
                                        }
                                    }
                                    if (ConfigurationManager.AppSettings["Pruebas"] == "true")
                                    {
                                        timbre.SelloSAT = "Inválido, Ambiente de pruebas";
                                    }
                                    string cfdiTimbrado = result;
                                    if (ConfigurationManager.AppSettings["EnvioSat"] == "false")
                                    {
                                        if (!TimbradoUtils.GuardaFactura(comp.Fecha, comp.Emisor.Rfc, comp.Receptor.Rfc, timbre.UUID, cfdiTimbrado, hash, empresa, true, false))
                                        {
                                            throw new Exception("Error al abrir el comprobante");
                                        }
                                        NtLinkFactura fac = new NtLinkFactura(0);
                                        if (string.IsNullOrEmpty(empresa.RegimenFiscal))
                                        {
                                            throw new FaultException("Debes capturar el regimen fiscal de la empresa");
                                        }
                                        fac.Emisor      = empresa;
                                        fac.Receptor    = cliente;
                                        fac.Factura     = this.CrearFactura(comp, empresa.IdEmpresa, cliente.idCliente);
                                        fac.Factura.Uid = timbre.UUID;
                                        fac.Save();
                                        comp.Complemento = new ComprobanteComplemento();
                                        comp.Complemento.timbreFiscalDigital = timbre;
                                        comp.XmlString            = cfdiTimbrado;
                                        comp.CadenaOriginalTimbre = timbre.cadenaOriginal;
                                        string saldo = comp.Total.ToString(CultureInfo.InvariantCulture);
                                        comp.CantidadLetra = CantidadLetra.Enletras(saldo.ToString(), comp.Moneda);
                                        comp.Regimen       = empresa.RegimenFiscal;
                                        if (comp.TipoDeComprobante.ToString() == "ingreso")
                                        {
                                            comp.Titulo = "Factura";
                                        }
                                        else if (comp.TipoDeComprobante.ToString() == "egreso")
                                        {
                                            comp.Titulo = "Nota de Crédito";
                                        }
                                        string ruta = Path.Combine(ConfigurationManager.AppSettings["Salida"], empresa.RFC);
                                        if (!Directory.Exists(ruta))
                                        {
                                            Directory.CreateDirectory(ruta);
                                        }
                                        string xmlFile = Path.Combine(ruta, timbre.UUID + ".xml");
                                        ServicioTimbradoMovil.Logger.Debug(comp.XmlString);
                                        StreamWriter sw = new StreamWriter(xmlFile, false, Encoding.UTF8);
                                        sw.Write(comp.XmlString);
                                        sw.Close();
                                        byte[] pdf = new byte[0];
                                        try
                                        {
                                            long          id  = 0L;
                                            GeneradorCfdi gen = new GeneradorCfdi();
                                            pdf = gen.GetPdfFromComprobante(comp, empresa.Orientacion, fac.Factura.TipoDocumento, ref id, fac.Factura.Metodo);
                                            string pdfFile = Path.Combine(ruta, timbre.UUID + ".pdf");
                                            File.WriteAllBytes(pdfFile, pdf);
                                        }
                                        catch (Exception ee)
                                        {
                                            ServicioTimbradoMovil.Logger.Error(ee);
                                            if (ee.InnerException != null)
                                            {
                                                ServicioTimbradoMovil.Logger.Error(ee.InnerException);
                                            }
                                        }
                                    }
                                    string totalLetra = comp.Total.ToString(CultureInfo.InvariantCulture);
                                    string enteros;
                                    string decimales;
                                    if (totalLetra.IndexOf('.') == -1)
                                    {
                                        enteros   = "0";
                                        decimales = "0";
                                    }
                                    else
                                    {
                                        enteros   = totalLetra.Substring(0, totalLetra.IndexOf('.'));
                                        decimales = totalLetra.Substring(totalLetra.IndexOf('.') + 1);
                                    }
                                    string total        = enteros.PadLeft(18, '0') + "." + decimales.PadRight(6, '0');
                                    int    tam_var      = comp.Sello.Length;
                                    string Var_Sub      = comp.Sello.Substring(tam_var - 8, 8);
                                    string URL          = "https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx";
                                    string cadenaCodigo = string.Concat(new string[]
                                    {
                                        URL,
                                        "?&id=",
                                        timbre.UUID,
                                        "&fe=",
                                        Var_Sub,
                                        "&re=",
                                        comp.Emisor.Rfc,
                                        "&rr=",
                                        comp.Receptor.Rfc,
                                        "&tt=",
                                        total
                                    });
                                    string qr = this.GetQrCode(cadenaCodigo);
                                    result2 = new TimbradoResponse
                                    {
                                        Valido       = true,
                                        QrCodeBase64 = qr,
                                        CadenaTimbre = timbre.cadenaOriginal,
                                        Cfdi         = cfdiTimbrado
                                    };
                                }
                                else if (timbre != null && timbre.SelloSAT == null && dict.Count == 0)
                                {
                                    string totalLetra = comp.Total.ToString(CultureInfo.InvariantCulture);
                                    string enteros;
                                    string decimales;
                                    if (totalLetra.IndexOf('.') == -1)
                                    {
                                        enteros   = "0";
                                        decimales = "0";
                                    }
                                    else
                                    {
                                        enteros   = totalLetra.Substring(0, totalLetra.IndexOf('.'));
                                        decimales = totalLetra.Substring(totalLetra.IndexOf('.') + 1);
                                    }
                                    string total        = enteros.PadLeft(18, '0') + "." + decimales.PadRight(6, '0');
                                    int    tam_var      = comp.Sello.Length;
                                    string Var_Sub      = comp.Sello.Substring(tam_var - 8, 8);
                                    string URL          = "https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx";
                                    string cadenaCodigo = string.Concat(new string[]
                                    {
                                        URL,
                                        "?&id=",
                                        timbre.UUID,
                                        "&fe=",
                                        Var_Sub,
                                        "&re=",
                                        comp.Emisor.Rfc,
                                        "&rr=",
                                        comp.Receptor.Rfc,
                                        "&tt=",
                                        total
                                    });
                                    string qr = this.GetQrCode(cadenaCodigo);
                                    result2 = new TimbradoResponse
                                    {
                                        Valido       = true,
                                        QrCodeBase64 = qr,
                                        CadenaTimbre = timbre.cadenaOriginal,
                                        Cfdi         = result
                                    };
                                }
                                else if (dict.Count > 0)
                                {
                                    StringBuilder res = new StringBuilder();
                                    foreach (KeyValuePair <int, string> d in dict)
                                    {
                                        res.AppendLine(d.Key.ToString() + " - " + d.Value.ToString());
                                    }
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = res.ToString()
                                    };
                                }
                                else
                                {
                                    ServicioTimbradoMovil.Logger.Error("Error al abrir el comprobante:" + comprobante);
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = "Error al abrir el comprobante"
                                    };
                                }
                            }
                        }
                        else
                        {
                            ServicioTimbradoMovil.Logger.Error("Error al abrir el comprobante: " + erroresNomina);
                            result2 = new TimbradoResponse
                            {
                                Valido           = false,
                                DescripcionError = erroresNomina
                            };
                        }
                    }
                }
                else
                {
                    ServicioTimbradoMovil.Logger.Error("Error al abrir el comprobante:" + comprobante);
                    result2 = new TimbradoResponse
                    {
                        Valido           = false,
                        DescripcionError = "Error al abrir el comprobante"
                    };
                }
            }
            catch (FaultException ex)
            {
                ServicioTimbradoMovil.Logger.Error(ex);
                result2 = new TimbradoResponse
                {
                    Valido           = false,
                    DescripcionError = ex.Message
                };
            }
            catch (Exception ex2)
            {
                ServicioTimbradoMovil.Logger.Error(ex2);
                throw new FaultException("Error al abrir el comprobante");
            }
            return(result2);
        }
Example #8
0
        public string TimbraRetencion(string comprobante, string userName, string password, string LLave, string aplicacion)
        {
            string result;

            try
            {
                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));
                Retenciones comp    = TimbradoUtils.DesSerializarRetenciones(element);
                empresa     empres  = new empresa();
                if (comp.Emisor != null && comp.Emisor.RFCEmisor != null)
                {
                    string vemp = ValidarUsuario(comp.Emisor.RFCEmisor, x, ref empres);
                    if (vemp != "OK")
                    {
                        return(vemp);
                    }
                }
                else
                {
                    return("Error: Los datos del emisor incompletos");
                }
                //-------------------------

                if (comprobante.Contains("<planesderetiro11:Planesderetiro"))
                {
                    Planesderetiro Plan    = this.DesSerializarPR(element);
                    ValidarPR      validar = new ValidarPR();
                    string         errorPR = validar.ProcesarPR(Plan);
                    if (errorPR != "0")
                    {
                        result = errorPR;
                        return(result);
                    }
                }
                if (comprobante.Contains("<plataformasTecnologicas:ServiciosPlataformasTecnologicas"))
                {
                    ServicioLocal.Business.ComplementoRetencion.Retenciones retencion = this.DesSerializarRetencion(element);

                    string erroECC = "";
                    ServiciosPlataformasTecnologicas E2 = this.DesSerializarSPT(element, ref erroECC);
                    ValidarSPT VE2 = new ValidarSPT();
                    erroECC = VE2.ProcesarSPT(E2, retencion);
                    if (erroECC != "0")
                    {
                        result = erroECC;
                        return(result);
                    }
                }


                result = TimbradoUtils.TimbraRetencionString(comprobante, empres, true, true);
            }
            catch (FaultException ex)
            {
                result = ex.Message;
            }
            catch (Exception ex2)
            {
                result = "Error al abrir el comprobante";
            }
            return(result);
        }
Example #9
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);
        }