public async void EnvioDatosFactura( string Factura, string Tipo, int Empresa) { string res = string.Empty; try { //Obtener Encabezado y Detalle de la Factura objHeader = db.Header(Factura, Tipo, Empresa); Detalle = db.Detalle(Factura, Empresa); objCredenciales = DAL.Credenciales(Empresa); if (objHeader is null) { iError = "El SP: sp_sel_FacturaElectronicaGTDatos no ha devuelto ningun valor."; return; } // Covertir la Clase en XML XmlSerializer serializador = new XmlSerializer(typeof(GTDocumento)); StringBuilder sb = new StringBuilder(); TextWriter tw = new StringWriter(sb); serializador.Serialize(tw, new CrearXmlFactura().FacturaXml(objHeader, Detalle)); tw.Close(); xml = sb.ToString(); // Limpiar XML para que sea igual al formato de Hacienda xml = xml.Substring(198, xml.Length - 198); xml = xml.Replace("<", "<dte:"); xml = xml.Replace("<dte:/", "</dte:"); xml = xml.Replace("<dte:cfc", "<cfc"); xml = xml.Replace("</dte:cfc", "</cfc"); xml = xml.Replace("<dte:AbonosFacturaCambiaria", "<cfc:AbonosFacturaCambiaria"); xml = xml.Replace("</dte:AbonosFacturaCambiaria>", "</cfc:AbonosFacturaCambiaria>"); xml = $"{objHeader.EncabezadoFE}{xml}"; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml")); client.DefaultRequestHeaders.Add("UsuarioFirma", objCredenciales.usuarioFirma); client.DefaultRequestHeaders.Add("LlaveFirma", objCredenciales.tokenFirma); client.DefaultRequestHeaders.Add("UsuarioApi", objCredenciales.usuaarioApi); client.DefaultRequestHeaders.Add("LlaveApi", objCredenciales.llaveApi); client.DefaultRequestHeaders.Add("Identificador", objHeader.Consecutivo); StringContent oString = new StringContent(xml); HttpResponseMessage response = client.PostAsync(new Uri(objCredenciales.urlApi), oString).Result; res = await response.Content.ReadAsStringAsync(); responseApi = JsonConvert.DeserializeObject <ResponseApi>(res); //Actualizar el resultado en Tabla db.Actualizar( objHeader.Id, xml, responseApi.numero, responseApi.resultado ? "aceptado" : "rechazado", res, responseApi.xml_certificado, Empresa); iError = "Ok"; } catch (Exception ex) { iError = ex.Message; //Actualizar el resultado en Tabla en caso de Error. db.Actualizar( objHeader.Id, xml, string.Empty, "sin-respuesta", res.Length == 0 ? iError : res, string.Empty, Empresa); } }
public GTDocumento NotaCDXml(FacturaElectronicaGT Header, DataTable Detalle, ResponseApi Api, string Motivo) { DireccionEmisor direccionEmisor = new DireccionEmisor { Direccion = Header.DireccionEmisor, CodigoPostal = Header.CodigoPostalEmisor, Municipio = Header.MunicipioEmisor, Departamento = Header.DepartamentoEmisor, Pais = Header.PaisEmisor, }; DireccionReceptor direccionReceptor = new DireccionReceptor { Direccion = Header.DireccionReceptor, CodigoPostal = Header.CodigoPostalReceptor, Municipio = Header.MunicipioReceptor, Departamento = Header.DepartamentoReceptor, Pais = Header.PaisReceptor, }; Totales totales = new Totales { TotalImpuestos = new TotalImpuestos { TotalImpuesto = new TotalImpuesto { NombreCorto = "IVA", TotalMontoImpuesto = Header.TotalMontoImpuesto.ToString() }, }, GranTotal = Header.GranTotal.ToString(), }; List <Item> item = new List <Item>(); List <Impuesto> impuesto = new List <Impuesto>(); for (int i = 0; i <= Detalle.Rows.Count - 1; i++) { Impuestos impuestos = new Impuestos { Impuesto = new Impuesto { NombreCorto = "IVA", CodigoUnidadGravable = Convert.ToDouble(Detalle.Rows[i]["Impuesto"]) == 0.00 ? "2" : "1", MontoGravable = Detalle.Rows[i]["Gravable"].ToString(), MontoImpuesto = Detalle.Rows[i]["Impuesto"].ToString(), } }; item.Add(new Item { BienOServicio = Detalle.Rows[i]["Tipo"].ToString().Equals("P") ? "B" : "S", Cantidad = Detalle.Rows[i]["Cantidad"].ToString(), NumeroLinea = (i + 1).ToString(), UnidadMedida = Detalle.Rows[i]["Unidad"].ToString(), Descripcion = Detalle.Rows[i]["Descripcion"].ToString(), PrecioUnitario = Detalle.Rows[i]["Unitario"].ToString(), Precio = Detalle.Rows[i]["Precio"].ToString(), Descuento = Detalle.Rows[i]["Descuento"].ToString(), Impuesto = impuestos, Total = Detalle.Rows[i]["Total"].ToString(), }); } Items items = new Items { Item = item, }; ReferenciasNota referencia = new ReferenciasNota { Cno = "http://www.sat.gob.gt/face2/ComplementoReferenciaNota/0.1.0", FechaEmisionDocumentoOrigen = Api.fecha.Substring(0, 10), MotivoAjuste = Motivo, NumeroAutorizacionDocumentoOrigen = Api.uuid, NumeroDocumentoOrigen = Api.numero, SerieDocumentoOrigen = Api.serie, Version = "0.0", SchemaLocation = Header.SchemaLocation }; Complemento complemento = new Complemento { IDComplemento = "Notas", NombreComplemento = "Notas", URIComplemento = "http://www.sat.gob.gt/fel/notas.xsd", ReferenciasNota = referencia }; Complementos complementos = new Complementos { Complemento = complemento }; DatosEmision datosEmision = new DatosEmision { ID = "DatosEmision", DatosGenerales = new DatosGenerales { CodigoMoneda = Header.CodigoMoneda, FechaHoraEmision = Header.FechaHoraEmision, Tipo = Header.Tipo, }, Emisor = new Emisor { AfiliacionIVA = Header.AfiliacionIVA, CodigoEstablecimiento = Header.CodigoEstablecimiento, CorreoEmisor = Header.CorreoEmisor, NITEmisor = Header.NITEmisor, NombreComercial = Header.NombreComercial, NombreEmisor = Header.NombreEmisor, DireccionEmisor = direccionEmisor, }, Receptor = new Receptor { CorreoReceptor = Header.CorreoReceptor, IDReceptor = Header.IDReceptor, NombreReceptor = Header.NombreReceptor, DireccionReceptor = direccionReceptor, }, Items = items, Totales = totales, Complementos = complementos, }; DTE dte = new DTE { ID = "DatosCertificados", DatosEmision = datosEmision, }; SAT sat = new SAT { ClaseDocumento = "dte", DTE = dte, }; return(new GTDocumento { SAT = sat, }); }
public async void EnvioDatosAnula( string Factura, string Tipo, string NumeroDocumento, string Motivo, DataTable _dt, int Empresa) { if (_dt.Rows.Count == 0) { iError = "El SP: sp_sel_FacturaElectronicaAnulacion no ha devuelto ningun valor."; return; } string res = string.Empty; try { // Covertir la Clase en XML XmlSerializer serializador = new XmlSerializer(typeof(GTAnulacionDocumento)); StringBuilder sb = new StringBuilder(); TextWriter tw = new StringWriter(sb); serializador.Serialize(tw, new CrearXmlAnulacion().AnulacionXml(NumeroDocumento, Motivo, _dt)); tw.Close(); xml = sb.ToString(); // Limpiar XML para que sea igual al formato de Hacienda xml = xml.Substring(206, xml.Length - 206); xml = xml.Replace("<", "<dte:"); xml = xml.Replace("<dte:/", "</dte:"); xml = $"{_dt.Rows[0]["EncabezadoFE"].ToString()}{xml}"; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml")); objCredenciales = DAL.Credenciales(Empresa); client.DefaultRequestHeaders.Add("UsuarioFirma", objCredenciales.usuarioFirma); client.DefaultRequestHeaders.Add("LlaveFirma", objCredenciales.tokenFirma); client.DefaultRequestHeaders.Add("UsuarioApi", objCredenciales.usuaarioApi); client.DefaultRequestHeaders.Add("LlaveApi", objCredenciales.llaveApi); client.DefaultRequestHeaders.Add("Identificador", _dt.Rows[0]["Consecutivo"].ToString()); StringContent oString = new StringContent(xml); HttpResponseMessage response = client.PostAsync(new Uri(objCredenciales.urlApi), oString).Result; res = await response.Content.ReadAsStringAsync(); responseApi = JsonConvert.DeserializeObject <ResponseApi>(res); //Actualizar el resultado en Tabla db.Actualizar( (int)_dt.Rows[0]["Id"], xml, responseApi.numero, responseApi.resultado ? "aceptado" : "rechazado", res, responseApi.xml_certificado, Empresa); iError = "Ok"; } catch (Exception ex) { iError = ex.Message; //Actualizar el resultado en Tabla en caso de Error. db.Actualizar( (int)_dt.Rows[0]["Id"], xml, string.Empty, "sin-respuesta", res.Length == 0 ? iError : res, string.Empty, Empresa); } }