Exemplo n.º 1
0
        public string EnvioSunatDocumento(string Ruc, string TipoDocumento, string DocumentoElectronico, string PassCertificado, string UsuarioSol, string PassSol, string RutaCertificado, string RutaXML)
        {
            try
            {
                // Una vez validado el XML seleccionado procedemos con obtener el Certificado.
                var serializar = new Serializador
                {
                    RutaCertificadoDigital = Convert.ToBase64String(File.ReadAllBytes(RutaCertificado)),
                    PasswordCertificado    = PassCertificado,
                    TipoDocumento          = 1//rbRetenciones.Checked ? 0 : 1
                };

                using (var conexion = new ConexionSunat(Ruc, UsuarioSol, PassSol, ""))
                {
                    var byteArray = File.ReadAllBytes(RutaXML);
                    // Firmamos el XML.
                    // var tramaFirmado = serializar.FirmarXml(Convert.ToBase64String(byteArray));
                    // Le damos un nuevo nombre al archivo
                    //var nombreArchivo = $"{Ruc}-{TipoDocumento}-{DocumentoElectronico}";
                    // Escribimos el archivo XML ya firmado en una nueva ubicación.
                    //using (var fs = File.Create($"{nombreArchivo}.xml"))
                    //{
                    //    var byteFirmado = Convert.FromBase64String(tramaFirmado);
                    //    fs.Write(byteFirmado, 0, byteFirmado.Length);
                    //}
                    //// Ahora lo empaquetamos en un ZIP.
                    //var tramaZip = serializar.GenerarZip(tramaFirmado, nombreArchivo);

                    //var resultado = conexion.EnviarDocumento(tramaZip, $"{nombreArchivo}.zip");

                    //  if (resultado.Item2)
                    //  {
                    //      var returnByte = Convert.FromBase64String(resultado.Item1);

                    //      var rutaArchivo = $"{Directory.GetCurrentDirectory()}\\R-{nombreArchivo}.zip";
                    //      var fs = new FileStream(rutaArchivo, FileMode.Create, FileAccess.Write);
                    //      fs.Write(returnByte, 0, returnByte.Length);
                    //      fs.Close();

                    //      var sb = new StringBuilder();

                    //      // Añadimos la respuesta del Servicio.
                    //      sb.AppendLine(Resources.procesoCorrecto);

                    //      // Extraemos el XML contenido en el archivo de respuesta como un XML.
                    //      var rutaArchivoXmlRespuesta = rutaArchivo.Replace(".zip", ".xml");
                    //      // Procedemos a desempaquetar el archivo y leer el contenido de la respuesta SUNAT.
                    //      using (var streamZip = ZipFile.Read(File.Open(rutaArchivo,
                    //          FileMode.Open,
                    //          FileAccess.ReadWrite)))
                    //      {
                    //          // Nos aseguramos de que el ZIP contiene al menos un elemento.
                    //          if (streamZip.Entries.Any())
                    //          {
                    //              streamZip.Entries.First()
                    //                  .Extract(".", ExtractExistingFileAction.OverwriteSilently);
                    //          }
                    //      }
                    //      // Como ya lo tenemos extraido, leemos el contenido de dicho archivo.
                    //      var xDoc = XDocument.Parse(File.ReadAllText(rutaArchivoXmlRespuesta));

                    //      var respuesta = xDoc.Descendants(XName.Get("DocumentResponse", EspacioNombres.cac))
                    //          .Descendants(XName.Get("Response", EspacioNombres.cac))
                    //          .Descendants().ToList();

                    //      if (respuesta.Any())
                    //      {
                    //          // La respuesta se compone de 3 valores
                    //          // cbc:ReferenceID
                    //          // cbc:ResponseCode
                    //          // cbc:Description
                    //          // Obtendremos unicamente la Descripción (la última).
                    //          sb.AppendLine($"Respuesta de SUNAT a las {DateTime.Now}");
                    //          sb.AppendLine(((XText)respuesta.Nodes().Last()).Value);
                    //      }

                    //      //txtResult.Text = sb.ToString();
                    //      sb.Length = 0; // Limpiamos memoria del StringBuilder.
                    //  }
                    //  else { throw new Exception(resultado.Item1.ToString()); }

                    return("");
                }
            }
            catch (FaultException exSer)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 2
0
        public Response <Documentos> GeneraDocumentoElectronicoXML(InvoiceType Documento)
        {
            String RucEmisor       = Documento.AccountingSupplierParty.Party.PartyIdentification[0].ID.Value;
            String TipoDocumento   = Documento.InvoiceTypeCode.Value;
            String NumeroDocumento = Documento.ID.Value;

            Documento.Cac  = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
            Documento.Cbc  = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
            Documento.Ccts = "urn:un:unece:uncefact:documentation:2";
            Documento.Ds   = "http://www.w3.org/2000/09/xmldsig#";
            Documento.Ext  = "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2";
            Documento.Qdt  = "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2";
            Documento.Udt  = "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2";
            //-----Generando el archivo XML
            XmlWriterSettings setting = new XmlWriterSettings();

            setting.Indent      = true;
            setting.IndentChars = "\t";
            string rutaXML = string.Format(@"{0}{1}-{2}-{3}.xml",
                                           Path.GetTempPath(),//Se creacion en la carpeta temporal
                                           RucEmisor, TipoDocumento, NumeroDocumento);

            using (XmlWriter writer = XmlWriter.Create(rutaXML, setting))
            {
                Type          typeToSerialize = typeof(InvoiceType);
                XmlSerializer xs = new XmlSerializer(typeToSerialize);
                xs.Serialize(writer, Documento);
            }
            if (File.Exists(rutaXML))
            {
                string RutaCertificado = @"D:\FACTURACION ELECTRONICA\20509992461.pfx";
                string PassCertificado = "123456789";

                //ProcesosSunat FacBol = new ProcesosSunat();
                //FacBol.EnvioSunatDocumento(RucEmisor, TipoDocumento, NumeroDocumento, "123456789", "20509992461MODDATOS", "MODDATOS", @"D:\FACTURACION ELECTRONICA\20509992461.pfx", rutaXML);
                var serializar = new Serializador
                {
                    RutaCertificadoDigital = Convert.ToBase64String(File.ReadAllBytes(RutaCertificado)),
                    PasswordCertificado    = PassCertificado,
                    TipoDocumento          = 1//rbRetenciones.Checked ? 0 : 1
                };
                var byteArray = File.ReadAllBytes(rutaXML);
                // Firmamos el XML.
                var tramaFirmado = serializar.FirmarXml(Convert.ToBase64String(byteArray));
                // Le damos un nuevo nombre al archivo
                var nombreArchivo = $"{RucEmisor}-{TipoDocumento}-{NumeroDocumento}";
                // Escribimos el archivo XML ya firmado en una nueva ubicación.
                using (var fs = File.Create($"{nombreArchivo}.xml"))
                {
                    var byteFirmado = Convert.FromBase64String(tramaFirmado[0]);
                    fs.Write(byteFirmado, 0, byteFirmado.Length);
                }
                // Ahora lo empaquetamos en un ZIP.
                var tramaZip = serializar.GenerarZip(tramaFirmado[0], nombreArchivo);
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                };
                Response <Documentos> Respuesta = new Response <Documentos>()
                {
                    Message     = "Operacion exitosa.",
                    CodResponse = "0",
                    Data        = new Documentos
                    {
                        Documento         = NumeroDocumento,
                        Ruc               = RucEmisor,
                        Caja              = "001",
                        Estado            = "GENERADO",
                        TipoDocumento     = TipoDocumento,
                        FechaRegistroSet  = DateTime.UtcNow,
                        FechaRegistro     = DateTime.Now,
                        IdTramaNavigation = new DocumentosTramas
                        {
                            Firmaxml = tramaFirmado[0],
                            Json     = JsonConvert.SerializeObject(Documento, Newtonsoft.Json.Formatting.None, settings),
                            Xml      = System.Text.Encoding.UTF8.GetString(byteArray),
                            Hash     = tramaFirmado[1],
                            Xmlzip   = tramaZip,
                            Cdr      = ""
                        }
                    }
                };
                return(Respuesta);
            }
            else
            {
                Response <Documentos> Respuesta = new Response <Documentos>()
                {
                    Message     = "Error no hay acceso al directorio temporal XML u no existe!",
                    CodResponse = "-1",
                    Data        = new Documentos
                    {
                    }
                };
                return(Respuesta);
            }
        }