コード例 #1
0
        public void Sign(string unsignedXmlPath, string signedXmlPath, string pfxPath, string pfxPassword)
        {
            PrivateKey      privateKey;
            Provider        provider;
            X509Certificate certificate = _LoadCertificate(pfxPath, pfxPassword, out privateKey, out provider);

            if (certificate != null)
            {
                TrustFactory.instance             = es.mityc.javasign.trust.TrustExtendFactory.newInstance();
                TrustFactory.truster              = es.mityc.javasign.trust.MyPropsTruster.getInstance();
                PoliciesManager.POLICY_SIGN       = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager();
                PoliciesManager.POLICY_VALIDATION = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager();

                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                Document unsignedDocument = dbf.newDocumentBuilder().parse(new BufferedInputStream(new FileInputStream(unsignedXmlPath)));

                DataToSign dataToSign = new DataToSign();
                dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES);
                dataToSign.setEsquema(XAdESSchemas.XAdES_132);
                dataToSign.setPolicyKey("facturae31");
                dataToSign.setAddPolicy(true);
                dataToSign.setXMLEncoding("UTF-8");
                dataToSign.setEnveloped(true);
                dataToSign.addObject(new ObjectToSign(new AllXMLToSign(), "Description", null, "text/xml", null));
                dataToSign.setDocument(unsignedDocument);

                Object[] res = new FirmaXML().signFile(certificate, dataToSign, privateKey, provider);

                UtilidadTratarNodo.saveDocumentToOutputStream((Document)res[0], new FileOutputStream(signedXmlPath), true);
            }
        }
コード例 #2
0
ファイル: Signer.cs プロジェクト: javierpuntonet/nFacturae
        public void Sign(string unsignedXmlPath, string signedXmlPath, string pfxPath, string pfxPassword)
        {
            PrivateKey privateKey;
            Provider provider;
            X509Certificate certificate = _LoadCertificate(pfxPath, pfxPassword, out privateKey, out provider);

            if (certificate != null)
            {
                TrustFactory.instance = es.mityc.javasign.trust.TrustExtendFactory.newInstance();
                TrustFactory.truster = es.mityc.javasign.trust.MyPropsTruster.getInstance();
                PoliciesManager.POLICY_SIGN = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager();
                PoliciesManager.POLICY_VALIDATION = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager();

				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				dbf.setNamespaceAware(true);
				Document unsignedDocument = dbf.newDocumentBuilder().parse(new BufferedInputStream(new FileInputStream(unsignedXmlPath)));
				
                DataToSign dataToSign = new DataToSign();
                dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES);
                dataToSign.setEsquema(XAdESSchemas.XAdES_132);
                dataToSign.setPolicyKey("facturae31");
                dataToSign.setAddPolicy(true);
                dataToSign.setXMLEncoding("UTF-8");
                dataToSign.setEnveloped(true);
                dataToSign.addObject(new ObjectToSign(new AllXMLToSign(), "Description", null, "text/xml", null));
                dataToSign.setDocument(unsignedDocument);

                Object[] res = new FirmaXML().signFile(certificate, dataToSign, privateKey, provider);

                UtilidadTratarNodo.saveDocumentToOutputStream((Document)res[0], new FileOutputStream(signedXmlPath), true);
            }
        }
コード例 #3
0
 public Boolean Firmar(string RutaCertificado, string Clave, string RutaXML, string RutaFirmado, ref string mensaje)
 {
     try
     {
         X509Certificate certificate = default(X509Certificate);
         PrivateKey      key         = default(PrivateKey);
         Provider        provider    = default(Provider);
         string          str         = Clave;
         KeyStore        store       = KeyStore.getInstance("PKCS12");
         store.load(new FileInputStream(RutaCertificado), str.ToCharArray());
         Enumeration enumeration = store.aliases();
         while (enumeration.hasMoreElements())
         {
             string alias1 = Convert.ToString(enumeration.nextElement());
             if (store.isKeyEntry(alias1))
             {
                 //certificate = (X509Certificate)store.getCertificate(alias1);
                 certificate = (X509Certificate)store.getCertificate(alias1);
                 key         = (PrivateKey)store.getKey(alias1, str.ToCharArray());
                 provider    = store.getProvider();
                 break;
             }
         }
         PrivateKey key2      = key;
         Provider   provider2 = provider;
         if (certificate != null)
         {
             TrustFactory.instance = TrustFactory.newInstance();
             TrustFactory.truster  = PropsTruster.getInstance();
             DataToSign dataToSign = new DataToSign();
             dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES);
             dataToSign.setEsquema(XAdESSchemas.XAdES_132);
             dataToSign.setPolicyKey("facturae31");
             dataToSign.setXMLEncoding("UTF-8");
             dataToSign.setEnveloped(true);
             dataToSign.addObject(new ObjectToSign(new InternObjectToSign("comprobante"), "contenido comprobante", null, "text/xml", null));
             dataToSign.setParentSignNode("comprobante");
             dataToSign.setDocument(LoadXML(RutaXML));
             object[]         objArray     = new FirmaXML().signFile(certificate, dataToSign, key, provider);
             FileOutputStream outputStream = new FileOutputStream(RutaFirmado);
             UtilidadTratarNodo.saveDocumentToOutputStream((Document)objArray[0], outputStream, true);
             outputStream.flush();
             outputStream.close();
         }
         return(true);
     }
     catch (Exception exception1)
     {
         //ProjectData.SetProjectError(exception1);
         //Exception exception = exception1;
         mensaje = "Error al Firmar el Documento : " + exception1.Message;
         //ProjectData.ClearProjectError();
         return(false);
         //ProjectData.ClearProjectError();
     }
 }
コード例 #4
0
        public static void firmar(string Archivo)
        {
            string     path = @"C:\Firma\fabricio_fortunato_mero_mosquera.p12";
            PrivateKey privatekey;
            Provider   provider;

            java.security.cert.X509Certificate certificate = LayerLogic.ClassLibrary.Complementos.Firmar.loadCertificate(path, "FFmm_1978", out privatekey, out provider);
            if (certificate != null)
            {
                //Creamos el documento a firmar
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                DocumentBuilder db = dbf.newDocumentBuilder();

                //C#
                var    base64 = System.Convert.FromBase64String(Archivo);
                string bytes  = System.Text.Encoding.UTF8.GetString(base64);

                ByteArrayInputStream bs        = new ByteArrayInputStream(System.Text.Encoding.UTF8.GetBytes(bytes));
                Document             documento = dbf.newDocumentBuilder().parse(bs);
                //Creamos datos a firmar

                DataToSign dataToSign = new DataToSign();
                dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES); //XAdES-EPES
                dataToSign.setAddPolicy(false);
                dataToSign.setXMLEncoding(encoding);
                dataToSign.setEnveloped(true);
                dataToSign.addObject(new ObjectToSign(new InternObjectToSign(nodoFirma), "comprobante", null, "text/xml", null));
                dataToSign.setParentSignNode(nodoFirma);
                //dataToSign.setDocument(LoadXML(NombreArchivo));
                dataToSign.setDocument(documento);

                //Firmar
                Object[] res = new FirmaXML().signFile(certificate, dataToSign, privatekey, provider);

                Document doc = (Document)res[0];
                //Transformar a string
                org.w3c.dom.ls.DOMImplementationLS domImplementation = (org.w3c.dom.ls.DOMImplementationLS)doc.getImplementation();
                org.w3c.dom.ls.LSSerializer        lsSerializer      = domImplementation.createLSSerializer();
                Archivo = lsSerializer.writeToString(doc).Replace("UTF-16", "UTF-8");

                //C#

                var    ArchivoFirmado = Encoding.UTF8.GetBytes(Archivo);
                string firmado        = Convert.ToBase64String(ArchivoFirmado);

                var    base642 = System.Convert.FromBase64String(firmado);
                string bytes2  = System.Text.Encoding.UTF8.GetString(base642);
            }
        }
コード例 #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);
        }
コード例 #6
0
ファイル: FrmCargarXML.aspx.cs プロジェクト: yeco96/FE
        protected void btnFirmar_Click(object sender, EventArgs e)
        {
            try
            {
                string xmlFile = Session["xmlFile"].ToString();

                EmisorReceptorIMEC dato = null;
                using (var conexion = new DataModelFE())
                {
                    string usuario = Session["usuario"].ToString();
                    dato = conexion.EmisorReceptorIMEC.Where(x => x.identificacion == usuario).FirstOrDefault();
                }

                string xmlFileSigned = FirmaXML.getXMLFirmadoWeb(xmlFile, dato.llaveCriptografica, dato.claveLlaveCriptografica.ToString());
                Session["xmlFile"] = xmlFileSigned;

                this.loadHTML();
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
        }
コード例 #7
0
        /// <summary>
        /// envia documento a hacienda, requiere de una factura en xml y firmada , codebase64
        /// </summary>
        public static void enviarDocumento(OAuth2Token token)
        {
            WSRecepcionPOST post = new WSRecepcionPOST();

            post.clave = "50613021800060354097400100002010000000003188888888";
            post.emisor.tipoIdentificacion     = "01";
            post.emisor.numeroIdentificacion   = "603540974";
            post.receptor.tipoIdentificacion   = "01";
            post.receptor.numeroIdentificacion = "601230863";

            FacturaElectronica fact = new FacturaElectronica();

            fact.iniciarParametros();

            string path = Path.Combine(Path.GetFullPath("fact.xml"));

            string xmlData = File.ReadAllText(path);
            //string xmlData = XMLUtilsgetXMLFromObject(fact);

            //XMLUtilsvalidadXMLXSD(xmlData);

            string xmlDataSigned = FirmaXML.getXMLFirmado(xmlData);



            // guarda xml firmado para pruebas
            File.WriteAllText(Path.GetFullPath("fact_firma.xml"), xmlDataSigned);

            post.comprobanteXml = EncodeXML.XMLUtils.base64Encode(xmlDataSigned);

            string jsonTrama = JsonConvert.SerializeObject(post);

            string responsePost = postRecepcion(token, jsonTrama)
                                  .GetAwaiter()
                                  .GetResult();
        }
コード例 #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 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);
        }
コード例 #9
0
        public bool SignXml(string RutaCertificado, string Clave, string RutaXML, string RutaFirmado, ref string mensaje)
        {
            //if (!ValidateAccessKey)
            //    return false;

            PrivateKey privateKey;
            Provider   provider;

            try
            {
                //X509Certificate certificate = LoadCertificate("","", out privateKey, out provider);

                X509Certificate certificate = null;
                provider   = null;
                privateKey = null;

                //Cargar certificado de fichero PFX
                KeyStore ks = KeyStore.getInstance("PKCS12");
                ks.load(new FileInputStream(RutaCertificado), Clave.ToCharArray());
                IPKStoreManager storeManager = new KSStore(ks, new PassStoreKS(Clave));
                List            certificates = storeManager.getSignCertificates();

                //Si encontramos el certificado...
                if (certificates.size() >= 1)
                {
                    certificate = (X509Certificate)certificates.get(0);

                    // Obtención de la clave privada asociada al certificado
                    privateKey = storeManager.getPrivateKey(certificate);

                    // Obtención del provider encargado de las labores criptográficas
                    provider = storeManager.getProvider(certificate);
                }

                if (certificate != null)
                {
                    TrustFactory.instance       = es.mityc.javasign.trust.TrustExtendFactory.newInstance();
                    TrustFactory.truster        = es.mityc.javasign.trust.MyPropsTruster.getInstance();
                    PoliciesManager.POLICY_SIGN = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager();

                    [email protected] s = new [email protected]();

                    PoliciesManager.POLICY_VALIDATION = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager();

                    DataToSign dataToSign = new DataToSign();
                    dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES); //XAdES-EPES
                    dataToSign.setEsquema(XAdESSchemas.XAdES_132);
                    dataToSign.setPolicyKey("facturae31");
                    //dataToSign.setAddPolicy(true);
                    dataToSign.setAddPolicy(false);
                    dataToSign.setXMLEncoding("UTF-8");
                    dataToSign.setEnveloped(true);
                    dataToSign.addObject(new ObjectToSign(new InternObjectToSign("comprobante"), "contenido comprobante", null, "text/xml", null));

                    //string fileToSign = Path.Combine("", fileName);

                    Document doc = LoadXML(RutaXML);
                    dataToSign.setDocument(doc);

                    //dataToSign.setDocument(IDocumentoElectronicoExtensions.LoadXml(fileToSign));

                    Object[] res = new FirmaXML().signFile(certificate, dataToSign, privateKey, provider);

                    java.io.FileOutputStream file = new FileOutputStream(RutaFirmado);

                    UtilidadTratarNodo.saveDocumentToOutputStream((Document)res[0], file, true);
                    file.flush();
                    file.close();

                    //DeleteFile(fileToSign);
                }

                return(true);
            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show(ex.Message);
                Console.WriteLine(ex.Message);

                //System.Diagnostics.EventLog.WriteEntry("BcLog", "SignXml - Error en Certificado " + ex.Message);
                return(false);
            }
        }
コード例 #10
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);
        }