Skip to content

About

Java library for creating and sending XML files through SOAP - SUNAT

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

28 stars

Watchers

5 watching

Forks

XHandler Java

License CI Maven Central

Crea, firma y envía los comprobantes electrónicos (XML UBL) de la SUNAT del Perú desde Java, con extensiones para Quarkus, Spring Boot y Jakarta EE. Sin código nativo; compatible con GraalVM native.

Instalación

Java 25 o superior.

<dependency>
    <groupId>io.github.project-openubl</groupId>
    <artifactId>xbuilder</artifactId>
    <version>6.0.0</version>
</dependency>
<dependency>
    <groupId>io.github.project-openubl</groupId>
    <artifactId>xsender</artifactId>
    <version>6.0.0</version>
</dependency>

Note

6.0.0 es la próxima versión. La última publicada, 5.1.1, tiene la API anterior: para pasar de 5.x a 6.0 revisa las guías de migración de XBuilder y XSender.

Uso

// Crear
Invoice invoice = Invoice.builder()
        .serieNumero("F001-1")
        .proveedor(Proveedor.builder().ruc("12345678912").razonSocial("Softgreen S.A.C.").build())
        .cliente(Cliente.builder()
                .tipoDocumentoIdentidad("6") // RUC (Catalog6)
                .numeroDocumentoIdentidad("12121212121")
                .nombre("Carlos Feria")
                .build())
        .detalles(List.of(Detalle.builder()
                .descripcion("Item")
                .cantidad(new BigDecimal("2"))
                .precio(new BigDecimal("100.00"))
                .build()))
        .build();
String xml = new XBuilder().build(invoice); // fecha de hoy en Perú y tasas vigentes

// Firmar
SigningKey key = SigningKey.fromPkcs12(Files.readAllBytes(Path.of("certificado.pfx")), "password");
byte[] signed = new XSigner().sign(xml.getBytes(StandardCharsets.UTF_8), key);

// Enviar
FileSender sender = new FileSender(
        URLs.beta(),
        Credentials.builder().username("12345678959MODDATOS").password("MODDATOS").build()
);
SunatResponse response = sender.sendFile(signed);
if (response.isTicket()) { // resúmenes, bajas y guías: consulta el ticket después
    response = sender.verifyFileTicket(signed, response.getSunat().getTicket());
}
System.out.println(response.getStatus()); // ACEPTADO, RECHAZADO, EXCEPCION, EN_PROCESO...
  • Crear: facturas, boletas, notas de crédito y débito, guías de remisión, percepciones, retenciones, resúmenes diarios, bajas y reversiones. new XBuilder().enrich(invoice) devuelve el documento con los valores calculados (impuestos, totales, leyendas) en lugar del XML. Defaults cambia la fecha de emisión o las tasas.
  • Firmar: SigningKey.fromPem(llavePrivada, certificado) o SigningKey.fromKeyStore(keyStore, alias, password).
  • Enviar: sendPack envía varias facturas en un zip. SunatClient también tiene los servicios de consulta y validación (getStatus, getStatusCdr, validateCdp, validateFile). Si envías por varias empresas, comparte un SunatClient (conexiones y tokens) entre sus FileSender.
  • Guías de remisión: usan URLs.production() (la SUNAT no tiene beta para ellas) y el clientId/clientSecret de la API.
  • Errores: los del núcleo son XhandlerException con su ErrorKind (p. ej. VALIDATION para un código de catálogo inválido) y los de red UncheckedIOException. Los rechazos de la SUNAT no son excepciones: llegan en el SunatResponse.

Frameworks

Framework Dependencia Configuración
Spring Boot spring-boot-xsender xsender.company.*
Quarkus quarkus-xbuilder, quarkus-xsender quarkus.xbuilder.*, quarkus.xsender.company.*
WildFly / Jakarta EE / MicroProfile xsender-cdi xsender.company.* (MicroProfile Config)

Exponen un SunatClient compartido y un FileSender para la empresa configurada (Quarkus también un XBuilder):

xsender.company.invoice-url=https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService
xsender.company.username=12345678959MODDATOS
xsender.company.password=MODDATOS
# xsender.company.perception-retention-url, despatch-url, client-id, client-secret

Ejemplos completos en examples/: Spring Boot, WildFly, Tomcat y Java SE.

Contribuir

Revisa CONTRIBUTING.md.

Licencia

Apache License, Version 2.0

About

Java library for creating and sending XML files through SOAP - SUNAT

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

28 stars

Watchers

5 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages