Skip to content

About

Administra XMLs basados en UBL y los estándares de la SUNAT respecto a la facturación electrónica.

Topics

Resources

Code of conduct

Contributing

Stars

21 stars

Watchers

2 watching

Forks

Repository files navigation

xhandler-rust

License CI

Crea, firma y envía los comprobantes electrónicos (XML UBL) de la SUNAT del Perú, desde Rust o desde la línea de comandos (xhandler). También hay librerías para Go, Python y Java.

Línea de comandos: xhandler

Instalación

cargo install --locked --git https://github.com/project-openubl/xhandler-rust xhandler-cli

Necesita Rust y un compilador de C.

Uso

Describe el comprobante en YAML o JSON:

# factura.yaml
kind: Invoice
spec:
  serie_numero: "F001-1"
  proveedor:
    ruc: "12345678912"
    razon_social: "Softgreen S.A.C."
  cliente:
    tipo_documento_identidad: "6"
    numero_documento_identidad: "12121212121"
    nombre: "Carlos Feria"
  detalles:
    - descripcion: "Item1"
      cantidad: 10
      precio: 100

Los otros tipos (kind) son CreditNote, DebitNote, DespatchAdvice, Perception, Retention, SummaryDocuments, VoidedDocuments y Reversion (ver cli/examples).

# Todo en un paso: crear, firmar y enviar. --beta usa el entorno de pruebas de la SUNAT,
# con credenciales y certificado de prueba.
xhandler apply -f factura.yaml --beta

# O paso a paso
xhandler create -f factura.yaml -o factura.xml
xhandler sign -f factura.xml --pfx certificado.pfx --pfx-password clave -o firmado.xml
xhandler send -f firmado.xml --username 20123456789USUARIO --password clave

# Los resúmenes y las bajas devuelven un ticket: consúltalo después
xhandler verify-ticket --ticket 1703154974517 --beta
  • La salida es JSON. El código de salida es 0 si la SUNAT acepta el comprobante (o devuelve un ticket) y 2 si lo rechaza.
  • Las credenciales y certificados pueden venir de variables de entorno, p. ej. XHANDLER_USERNAME, XHANDLER_PASSWORD, XHANDLER_PFX y XHANDLER_PFX_PASSWORD.
  • Las guías de remisión también necesitan --client-id y --client-secret. La SUNAT no tiene beta para ellas.

xhandler <comando> --help muestra todas las opciones.

Librería

Instalación

[dependencies]
xhandler = { git = "https://github.com/project-openubl/xhandler-rust" }

El ejemplo también usa rust_decimal, rust_decimal_macros, chrono, tokio y anyhow.

Uso

use rust_decimal_macros::dec;
use xhandler::prelude::*;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Crear: solo los datos esenciales, xbuilder calcula el resto
    let mut invoice = Invoice {
        serie_numero: "F001-1".into(),
        proveedor: Proveedor {
            ruc: "12345678912".into(),
            razon_social: "Softgreen S.A.C.".into(),
            ..Default::default()
        },
        cliente: Cliente {
            tipo_documento_identidad: "6".into(), // RUC (Catalog6)
            numero_documento_identidad: "12121212121".into(),
            nombre: "Carlos Feria".into(),
            ..Default::default()
        },
        detalles: vec![Detalle {
            descripcion: "Item".into(),
            cantidad: dec!(2),
            precio: Some(dec!(100)),
            ..Default::default()
        }],
        ..Default::default()
    };
    invoice.enrich(&Defaults::new(chrono::Local::now().date_naive()))?;
    let xml = invoice.render()?;

    // Firmar
    let key = RsaKeyPair::from_pkcs12(&std::fs::read("certificado.pfx")?, "password")?;
    let signed = XSigner { xml_document: xml }.sign(&key)?;

    // Enviar
    let sender = FileSender {
        urls: Urls::beta(),
        credentials: Credentials {
            username: "12345678959MODDATOS".into(),
            password: "MODDATOS".into(),
            ..Default::default()
        },
    };
    match sender.send_file(&UblFile::from_bytes(signed)?).await?.response {
        SendFileAggregatedResponse::Cdr(_, cdr) => println!("{} {}", cdr.status(), cdr.description),
        SendFileAggregatedResponse::Ticket(ticket) => println!("consultar el ticket {ticket} después"),
        SendFileAggregatedResponse::Fault(fault) => println!("{} {}", fault.code, fault.message),
    }
    Ok(())
}
  • xhandler::xbuilder: crea el XML; enrich completa valores por defecto, impuestos y totales.
  • xhandler::xsigner: firma con certificados PKCS#12 (from_pkcs12) o PEM (from_pem).
  • xhandler::xsender: FileSender envía y consulta tickets; SunatClient tiene además los servicios de consulta y validación. Sin la feature http (default-features = false), xsender::exchange arma las peticiones y lee las respuestas para tu propio cliente HTTP.

Contribuir

Revisa CONTRIBUTING.md.

Licencia

Apache License, Version 2.0

About

Administra XMLs basados en UBL y los estándares de la SUNAT respecto a la facturación electrónica.

Topics

Resources

Code of conduct

Contributing

Stars

21 stars

Watchers

2 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages