Example #1
0
        private static bool requiereNuevoToken(OAuth2.OAuth2Config config)
        {
            bool requiereToken = false;

            if (config == null)
            {
                requiereToken = true;
                return(requiereToken);
            }

            DateTime fechaCreacionToken;

            if (System.Web.HttpContext.Current.Session["tokenTime"] != null)
            {
                fechaCreacionToken = (DateTime)System.Web.HttpContext.Current.Session["tokenTime"];
            }
            else
            {
                fechaCreacionToken = Date.DateTimeNow();
            }

            TimeSpan diferencia = Date.DateTimeNow().Subtract(fechaCreacionToken);

            if (diferencia.TotalSeconds > config.token.expires_in - 10)
            {
                requiereToken = true;
            }


            return(requiereToken);
        }
Example #2
0
        // <summary>
        /// optiene el TOKEN de autorizacion
        /// </summary>
        /// <param name="authorization"> objeto de tipo OAuth2Config con la configuracion para la connexion</param>
        /// <returns>un objeto de tpo OAuth2Config.Token dentro del mismo parametro de entrada authorization</returns>
        public static async Task getTokenWeb(OAuth2Config authorization)
        {
            try {
                HttpContent httpContent = new FormUrlEncodedContent(
                    new[]
                {
                    new KeyValuePair <string, string>("grant_type", "password"),
                    new KeyValuePair <string, string>("username", authorization.username),
                    new KeyValuePair <string, string>("password", authorization.password),
                    new KeyValuePair <string, string>("client_id", authorization.clientId),
                    new KeyValuePair <string, string>("scope", authorization.scope),
                    new KeyValuePair <string, string>("client_secret", authorization.clientSecret)
                });

                using (HttpClient httpClient = new HttpClient())
                {
                    //HttpClient httpClient = new HttpClient();
                    HttpRequestMessage tokenRequest = new HttpRequestMessage(HttpMethod.Post, authorization.server);

                    tokenRequest.Content = httpContent;

                    HttpResponseMessage response = await httpClient.SendAsync(tokenRequest);

                    string tokenResult = await response.Content.ReadAsStringAsync();

                    authorization.token = JsonConvert.DeserializeObject <OAuth2Token>(tokenResult);
                }
            }
            catch (Exception e)
            {
                authorization = null;
            }
        }
Example #3
0
        protected async void btnEnviar_Click(object sender, EventArgs e)
        {
            try
            {
                using (var conexion = new DataModelFE())
                {
                    EmisorReceptorIMEC  emisor   = (EmisorReceptorIMEC)Session["elEmisor"];
                    string              ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
                    OAuth2.OAuth2Config config   = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
                    config.username = emisor.usernameOAuth2;
                    config.password = emisor.passwordOAuth2;

                    await OAuth2.OAuth2Config.getTokenWeb(config);

                    string xmlFile = Session["xmlFile"].ToString();
                    WSDomain.WSRecepcionPOST trama = new WSDomain.WSRecepcionPOST();
                    trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile);

                    string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xmlFile);
                    trama.emisor.tipoIdentificacion   = emisorIdentificacion.Substring(0, 2);
                    trama.emisor.numeroIdentificacion = emisorIdentificacion.Substring(2);
                    trama.emisorTipo           = trama.emisor.tipoIdentificacion;
                    trama.emisorIdentificacion = trama.emisor.numeroIdentificacion;

                    string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xmlFile);
                    trama.receptor.tipoIdentificacion   = receptorIdentificacion.Substring(0, 2);
                    trama.receptor.numeroIdentificacion = receptorIdentificacion.Substring(2);
                    trama.receptorTipo           = trama.receptor.tipoIdentificacion;
                    trama.receptorIdentificacion = trama.receptor.numeroIdentificacion;

                    trama.comprobanteXml = EncodeXML.XMLUtils.base64Encode(xmlFile);

                    string jsonTrama = JsonConvert.SerializeObject(trama);

                    using (var conexion2 = new DataModelFE())
                    {
                        WSRecepcionPOST tramaObjeto = JsonConvert.DeserializeObject <WSRecepcionPOST>(jsonTrama);
                        conexion2.WSRecepcionPOST.Add(tramaObjeto);
                        conexion2.SaveChanges();
                    }

                    string responsePost = await Services.postRecepcion(config.token, jsonTrama);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
        }
Example #4
0
        /// <summary>
        /// optiene el TOKEN de autorizacion
        /// </summary>
        /// <returns>un objeto de tpo OAuth2Config.Token</returns>
        public static OAuth2Token getToken()
        {
            //authorization server parameters owned from the client
            OAuth2Config authorization = new OAuth2Config();

            authorization.loadParameter();

            //access token request
            string tokenStr = requestTokenToAuthorizationServer(authorization)
                              .GetAwaiter()
                              .GetResult();

            // authorizationServer token
            OAuth2Token token = JsonConvert.DeserializeObject <OAuth2Token>(tokenStr);

            return(token);
        }
Example #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="xmlFile">XML sin firmar</param>
        /// <param name="responsePost">respuesta del webs ervices</param>
        /// <param name="receptorTipoIdentificacion">tipoo identificacion del receptor</param>
        public static async Task <string> enviarMensajeReceptor(string xmlFile, EmisorReceptorIMEC emisor, string receptorTipoIdentificacion)
        {
            String responsePost = "";

            try
            {
                using (var conexion = new DataModelFE())
                {
                    string ambiente            = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
                    OAuth2.OAuth2Config config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
                    config.username = emisor.usernameOAuth2;
                    config.password = emisor.passwordOAuth2;

                    await OAuth2.OAuth2Config.getTokenWeb(config);

                    WSDomain.WSRecepcionPOST trama = new WSDomain.WSRecepcionPOST();
                    trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile);

                    trama.emisor.tipoIdentificacion   = emisor.identificacionTipo;
                    trama.emisor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("MensajeReceptor", "NumeroCedulaEmisor", xmlFile);

                    trama.receptor.tipoIdentificacion   = receptorTipoIdentificacion;
                    trama.receptor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("MensajeReceptor", "NumeroCedulaReceptor", xmlFile);

                    xmlFile = FirmaXML.getXMLFirmadoWeb(xmlFile, emisor.llaveCriptografica, emisor.claveLlaveCriptografica.ToString());

                    trama.consecutivoReceptor = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "NumeroConsecutivoReceptor", xmlFile);
                    trama.comprobanteXml      = EncodeXML.XMLUtils.base64Encode(xmlFile);

                    string jsonTrama = JsonConvert.SerializeObject(trama);

                    responsePost = await Services.postRecepcion(config.token, jsonTrama);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
            return(responsePost);
        }
Example #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="authorization"></param>
        /// <returns>token authorization json</returns>
        private static async Task <string> requestTokenToAuthorizationServer(OAuth2Config authorization)
        {
            HttpResponseMessage responseMessage;

            using (HttpClient client = new HttpClient())
            {
                HttpRequestMessage tokenRequest = new HttpRequestMessage(HttpMethod.Post, authorization.server);
                HttpContent        httpContent  = new FormUrlEncodedContent(
                    new[]
                {
                    new KeyValuePair <string, string>("grant_type", "password"),
                    new KeyValuePair <string, string>("username", authorization.username),
                    new KeyValuePair <string, string>("password", authorization.password),
                    new KeyValuePair <string, string>("client_id", authorization.clientId),
                    new KeyValuePair <string, string>("scope", authorization.scope),
                    new KeyValuePair <string, string>("client_secret", authorization.clientSecret)
                });
                tokenRequest.Content = httpContent;
                responseMessage      = await client.SendAsync(tokenRequest);
            }
            return(await responseMessage.Content.ReadAsStringAsync());
        }
Example #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tieneFirma">determina si el XML esta firmado o no</param>
        /// <param name="documento">puede ser cualquer tipo de documento electronico</param>
        /// <param name="responsePost">respuesta del webs ervices</param>
        /// <param name="tipoDocumento">Facura, Nota Crédito, Nota Débito</param>
        public static async Task <string> enviarDocumentoElectronico(bool tieneFirma, DocumentoElectronico documentoElectronico, EmisorReceptorIMEC emisor, string tipoDocumento, string usuario)
        {
            String responsePost = "";

            try
            {
                string xmlFile = EncodeXML.XMLUtils.getXMLFromObject(documentoElectronico);

                using (var conexion = new DataModelFE())
                {
                    string ambiente            = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
                    OAuth2.OAuth2Config config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
                    config.username = emisor.usernameOAuth2;
                    config.password = emisor.passwordOAuth2;

                    await OAuth2.OAuth2Config.getTokenWeb(config);

                    WSDomain.WSRecepcionPOST trama = new WSDomain.WSRecepcionPOST();
                    trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile);
                    trama.fecha = DateTime.ParseExact(XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "FechaEmision", xmlFile), "yyyy-MM-ddTHH:mm:ss-06:00",
                                                      System.Globalization.CultureInfo.InvariantCulture);


                    string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xmlFile);
                    trama.emisor.tipoIdentificacion   = emisorIdentificacion.Substring(0, 2);
                    trama.emisor.numeroIdentificacion = emisorIdentificacion.Substring(2);
                    trama.emisorTipo           = trama.emisor.tipoIdentificacion;
                    trama.emisorIdentificacion = trama.emisor.numeroIdentificacion;

                    string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xmlFile);

                    if (!string.IsNullOrWhiteSpace(receptorIdentificacion))
                    {
                        trama.receptor.tipoIdentificacion   = receptorIdentificacion.Substring(0, 2);
                        trama.receptor.numeroIdentificacion = receptorIdentificacion.Substring(2);
                    }
                    else
                    {
                        trama.receptor.tipoIdentificacion   = "99";
                        trama.receptor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "IdentificacionExtranjero", xmlFile);
                    }

                    trama.receptorTipo           = trama.receptor.tipoIdentificacion;
                    trama.receptorIdentificacion = trama.receptor.numeroIdentificacion;
                    trama.tipoDocumento          = tipoDocumento;

                    //trama.callbackUrl = ConfigurationManager.AppSettings["ENVIROMENT_URL"].ToString();

                    if (!tieneFirma)
                    {
                        xmlFile = FirmaXML.getXMLFirmadoWeb(xmlFile, emisor.llaveCriptografica, emisor.claveLlaveCriptografica.ToString());
                    }
                    trama.consecutivoReceptor = null;
                    // SE CODIFICA ENVIO HACIENDA
                    trama.comprobanteXml = XMLUtils.base64Encode(xmlFile);

                    string jsonTrama = JsonConvert.SerializeObject(trama);

                    if (config.token.access_token != null)
                    {
                        responsePost = await Services.postRecepcion(config.token, jsonTrama);
                    }
                    else
                    {
                        // facturar guardada para envio en linea
                        trama.indEstado = 9;
                    }
                    // SE DECODIFICA PARA GUARDAR A BASE DE DATOS
                    trama.comprobanteXml = xmlFile;

                    WSRecepcionPOST tramaExiste = conexion.WSRecepcionPOST.Find(trama.clave);
                    documentoElectronico.resumenFactura.clave = documentoElectronico.clave;
                    trama.cargarEmisorReceptor();

                    if (tramaExiste != null)
                    {// si existe
                        trama.fechaModificacion           = Date.DateTimeNow();
                        trama.usuarioModificacion         = usuario;
                        trama.indEstado                   = 0;
                        conexion.Entry(tramaExiste).State = EntityState.Modified;

                        conexion.Entry(documentoElectronico.resumenFactura).State = EntityState.Modified;
                    }
                    else//si no existe
                    {
                        trama.fechaCreacion   = Date.DateTimeNow();
                        trama.usuarioCreacion = usuario;
                        conexion.WSRecepcionPOST.Add(trama);

                        conexion.ResumenFactura.Add(documentoElectronico.resumenFactura);

                        Plan plan = conexion.Plan.Find(emisor.identificacion);
                        if (plan != null)
                        {
                            plan.cantidadDocEmitido   += 1;
                            conexion.Entry(plan).State = EntityState.Modified;
                        }
                    }
                    conexion.SaveChanges();

                    //guarda la relacion de clientes asociados al emisor
                    Cliente cliente = conexion.Cliente.Where(x => x.emisor == trama.emisor.numeroIdentificacion).Where(x => x.receptor == trama.receptor.numeroIdentificacion).FirstOrDefault();
                    if (cliente == null && !string.IsNullOrWhiteSpace(trama.receptor.numeroIdentificacion))
                    {
                        cliente          = new Cliente();
                        cliente.emisor   = trama.emisor.numeroIdentificacion;
                        cliente.receptor = trama.receptor.numeroIdentificacion;
                        conexion.Cliente.Add(cliente);
                        conexion.SaveChanges();
                    }
                }
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                                    .SelectMany(x => x.ValidationErrors)
                                    .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);
                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors);
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
            return(responsePost);
        }
Example #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tieneFirma">determina si el XML esta firmado o no</param>
        /// <param name="documento">puede ser cualquer tipo de documento electronico</param>
        /// <param name="responsePost">respuesta del webs ervices</param>
        /// <param name="tipoDocumento">Facura, Nota Crédito, Nota Débito</param>
        public static async Task <string> enviarDocumentoElectronico(bool tieneFirma, DocumentoElectronico documento, EmisorReceptorIMEC emisor, string tipoDocumento, string usuario)
        {
            String responsePost = "";

            try
            {
                string xmlFile = EncodeXML.XMLUtils.getXMLFromObject(documento);

                using (var conexion = new DataModelFE())
                {
                    OAuth2.OAuth2Config config = null;
                    if (System.Web.HttpContext.Current.Session["token"] != null)
                    {
                        config = (OAuth2.OAuth2Config)System.Web.HttpContext.Current.Session["token"];
                    }

                    if (requiereNuevoToken(config))
                    {
                        //Sessison["horaToken"]
                        string ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
                        config          = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
                        config.username = emisor.usernameOAuth2;
                        config.password = emisor.passwordOAuth2;

                        await OAuth2.OAuth2Config.getTokenWeb(config);

                        System.Web.HttpContext.Current.Session["token"]     = config;
                        System.Web.HttpContext.Current.Session["tokenTime"] = Date.DateTimeNow();
                    }

                    Models.WS.WSRecepcionPOST trama = new Models.WS.WSRecepcionPOST();
                    trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile);
                    trama.fecha = DateTime.ParseExact(XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "FechaEmision", xmlFile), "yyyy-MM-ddTHH:mm:ss-06:00",
                                                      System.Globalization.CultureInfo.InvariantCulture);


                    string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xmlFile);
                    trama.emisor.tipoIdentificacion   = emisorIdentificacion.Substring(0, 2);
                    trama.emisor.numeroIdentificacion = emisorIdentificacion.Substring(2);
                    trama.emisorTipo           = trama.emisor.tipoIdentificacion;
                    trama.emisorIdentificacion = trama.emisor.numeroIdentificacion;

                    string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xmlFile);

                    if (!string.IsNullOrWhiteSpace(receptorIdentificacion))
                    {
                        trama.receptor.tipoIdentificacion   = receptorIdentificacion.Substring(0, 2);
                        trama.receptor.numeroIdentificacion = receptorIdentificacion.Substring(2);
                    }
                    else
                    {
                        trama.receptor.tipoIdentificacion   = "99";
                        trama.receptor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "IdentificacionExtranjero", xmlFile);
                    }

                    trama.receptorTipo           = trama.receptor.tipoIdentificacion;
                    trama.receptorIdentificacion = trama.receptor.numeroIdentificacion;
                    trama.tipoDocumento          = tipoDocumento;

                    //trama.callbackUrl = ConfigurationManager.AppSettings["ENVIROMENT_URL"].ToString();

                    if (!tieneFirma)
                    {
                        xmlFile = FirmaXML.getXMLFirmadoWeb(xmlFile, emisor.llaveCriptografica, emisor.claveLlaveCriptografica.ToString());
                    }

                    trama.comprobanteXml = EncodeXML.XMLUtils.base64Encode(xmlFile);

                    string jsonTrama = JsonConvert.SerializeObject(trama);

                    if (config.token.access_token != null)
                    {
                        responsePost = await postRecepcion(config.token, jsonTrama);

                        Models.WS.WSRecepcionPOST tramaExiste = conexion.WSRecepcionPOST.Find(trama.clave);

                        if (tramaExiste != null)
                        {// si existe
                            trama.fechaModificacion   = Date.DateTimeNow();
                            trama.usuarioModificacion = usuario;
                            trama.indEstado           = 0;
                            trama.cargarEmisorReceptor();
                            conexion.Entry(tramaExiste).State = EntityState.Modified;

                            documento.resumenFactura.clave = documento.clave;
                            conexion.Entry(documento.resumenFactura).State = EntityState.Modified;
                        }
                        else//si no existe
                        {
                            trama.fechaCreacion   = Date.DateTimeNow();
                            trama.usuarioCreacion = usuario;
                            trama.cargarEmisorReceptor();
                            conexion.WSRecepcionPOST.Add(trama);              //trama

                            documento.resumenFactura.clave = documento.clave; //resumen
                            conexion.ResumenFactura.Add(documento.resumenFactura);
                        }
                        conexion.SaveChanges();
                    }
                    else
                    {
                        // error de conexion de red
                        responsePost = "net_error";
                        return(responsePost);
                    }
                }
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                                    .SelectMany(x => x.ValidationErrors)
                                    .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);
                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors);
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
            return(responsePost);
        }