# Lector y Validador de Facturas CFDI 4.0 (XML a Excel/CSV/JSON) (`integriapps/cfdi-parser`) Actor

Convierte facturas CFDI 4.0 (XML del SAT) a Excel, CSV o JSON: emisor, receptor, conceptos, IVA/ISR, UUID, Pagos 2.0 y Nómina 1.2, con validación de cálculos y catálogos. Acepta ZIP de descarga masiva. Por IntegriApps.

- **URL**: https://apify.com/integriapps/cfdi-parser.md
- **Developed by:** [IntegriApps .com](https://apify.com/integriapps) (community)
- **Categories:** Developer tools, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$2.00 / 1,000 cfdi parseds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Lector y Validador de Facturas CFDI 4.0 (XML a Excel, CSV y JSON)

Convierte tus **facturas electrónicas CFDI 4.0 (XML del SAT)** en datos limpios y ordenados en segundos. Sube archivos XML, archivos ZIP (por ejemplo, el ZIP de la **Descarga masiva del SAT**) o pega el XML directamente, y obtén una fila por factura o una fila plana por concepto, lista para Excel, Google Sheets, tu ERP, una base de datos o un agente de IA.

Forma parte de **[IntegriApps MicroApps](https://integriapps.com/microapps/)**, herramientas pequeñas y prácticas para MiPyMEs mexicanas.

### Qué hace

- Lee **CFDI 4.0** (y CFDI 3.3, con una advertencia) de todos los tipos: Ingreso, Egreso, Traslado, Nómina y Pago.
- Extrae emisor y receptor (RFC, nombre, régimen fiscal, código postal), serie, folio, fechas, **UUID / folio fiscal** y datos del timbre, moneda, tipo de cambio, forma y método de pago, uso del CFDI, subtotal, descuento y total.
- Desglosa impuestos: **IVA trasladado, IEPS, IVA retenido, ISR retenido** e impuestos locales (implocal).
- Procesa el **Complemento de Pagos 2.0** (pagos y documentos relacionados con saldos) y **Nómina 1.2** (percepciones, deducciones y otros pagos).
- Agrega la descripción de los catálogos del SAT (por ejemplo, `G03` = "Gastos en general", `612` = "Personas Físicas con Actividades Empresariales y Profesionales").
- Aplica **validaciones** a cada CFDI y te dice qué está mal (ver abajo).
- Descomprime archivos **ZIP**, omite UUID duplicados y nunca detiene toda la ejecución por un archivo dañado.

### Validaciones

Cada resultado incluye `validation.status` = `valid`, `valid_with_warnings`, `invalid` o `parse_error`, con la lista de errores y advertencias:

- Atributos obligatorios de CFDI 4.0 (Exportación, DomicilioFiscalReceptor, RegimenFiscalReceptor, UsoCFDI, entre otros).
- Formato de RFC, códigos postales de 5 dígitos, moneda ISO y TipoCambio cuando la moneda no es MXN.
- Valores válidos de TipoDeComprobante, MétodoPago, FormaPago, UsoCFDI, RégimenFiscal y Exportación.
- Las facturas PPD deben usar FormaPago 99.
- Cálculos: el SubTotal es igual a la suma de importes de los conceptos, el Descuento a la suma de descuentos, los totales de impuestos a la suma de sus líneas y **Total = SubTotal - Descuento + traslados - retenciones** (incluyendo impuestos locales).
- Pagos 2.0: ImpSaldoAnt - ImpPagado = ImpSaldoInsoluto.
- Timbre presente (TimbreFiscalDigital con un UUID bien formado).

**Lo que NO hace:** no verifica criptográficamente los sellos digitales y no consulta el estatus del CFDI (vigente/cancelado) ante el SAT. Un resultado `valid` significa que el archivo está bien formado y que sus cifras cuadran, no que el SAT lo haya aceptado.

### Cómo usarlo

1. Agrega tus archivos en **URLs de archivos XML o ZIP** (enlaces de descarga directa, o sube un archivo) o pega el XML en **Contenido XML pegado**.
2. Elige el **Modo de salida**: una fila por factura o una fila plana por concepto (ideal para Excel).
3. Haz clic en **Start** y descarga los resultados en Excel, CSV, JSON o XML desde la pestaña del dataset, o consúltalos con la API de Apify.

Si lo ejecutas sin entrada, procesa una factura de ejemplo como demostración (gratis, sin cobro).

#### Ejemplo de entrada

```json
{
  "xmlUrls": [{ "url": "https://example.com/facturas-octubre.zip" }],
  "outputMode": "concepts"
}
```

#### Ejemplo de salida (modo facturas, resumido)

```json
{
  "uuid": "6B1F3C2A-1D2E-4F5A-9B8C-7D6E5F4A3B21",
  "version": "4.0",
  "tipoDeComprobante": "I",
  "serie": "A", "folio": "1001", "fecha": "2026-10-20T10:15:00",
  "emisorRfc": "EKU9003173C9", "emisorNombre": "ESCUELA KEMPER URGATE",
  "receptorRfc": "CACX7605101P8", "usoCFDI": "G03", "usoCFDINombre": "Gastos en general",
  "metodoPago": "PUE", "formaPago": "03", "moneda": "MXN",
  "subTotal": 1500, "descuento": 100, "total": 1484,
  "ivaTrasladado": 224, "ivaRetenido": 50, "isrRetenido": 90,
  "conceptosCount": 2,
  "validation": { "status": "valid", "errors": [], "warnings": [] },
  "sourceFile": "https://example.com/facturas-octubre.zip#cfdi_1.xml"
}
```

En el key-value store se guarda un registro `RUN_SUMMARY` con los totales por estatus y el resultado de cada URL.

### Precio

Pago por evento: **USD 0.002 por CFDI procesado** (USD 2 por cada 1,000 facturas), sin otros cargos. Los archivos dañados, los que no son CFDI y los UUID duplicados no se cobran, y la ejecución de demostración es gratis. Puedes fijar un costo máximo por ejecución en las opciones; el Actor se detiene al alcanzarlo.

### Privacidad

Los archivos se procesan solo dentro de tu propia ejecución en Apify y los resultados se guardan solo en el dataset de tu ejecución. El Actor no envía tus facturas a ningún otro lugar ni guarda copias. Los CFDI pueden contener datos personales (nombres, RFC, CURP en nómina); eres responsable de tratarlos conforme a la legislación mexicana de protección de datos.

### Preguntas frecuentes

**¿Puedo usar el ZIP de la Descarga masiva del SAT?** Sí. Pon el enlace del ZIP en la entrada (o súbelo) y se procesan todos los XML que contenga.

**¿Funciona con CFDI 3.3?** Sí, con una advertencia de que la versión no es 4.0. Las validaciones exclusivas de 4.0 se omiten.

**¿Me dice si una factura fue cancelada?** Todavía no. Esta versión no consulta al SAT.

**¿Lo puede usar un agente de IA?** Sí, mediante la API de Apify o el servidor MCP de Apify; envía el XML en `xmlTexts`.

**¿Qué tan rápido es?** En nuestras pruebas, unas 2,000 facturas de un solo ZIP tardaron unos segundos con 256 MB de memoria.

### Soporte

Abre un reporte en la pestaña **Issues**. Soporte de domingo a viernes. Hecho por [IntegriApps](https://integriapps.com).

### In English

**CFDI parser and validator: convert Mexican invoice XML (CFDI 4.0, SAT facturas) to JSON, CSV or Excel.** Parse XML files or the SAT bulk-download ZIP and get issuer, receiver, line items, VAT (IVA), ISR withholdings, UUID, Payments 2.0 and Payroll 1.2 complements, with arithmetic and catalog checks. Price: USD 0.002 per CFDI. It does not verify digital seals or check SAT cancellation status.

# Changelog

This Actor's version history is a separate document: https://apify.com/integriapps/cfdi-parser/changelog.md

# Actor input Schema

## `xmlUrls` (type: `array`):

Enlaces de descarga directa a archivos XML de CFDI o ZIP con XML (por ejemplo, el ZIP de la 'Descarga masiva' del SAT o un enlace de Dropbox/Google Drive/S3 con descarga directa). También puedes subir un archivo aquí.

## `xmlTexts` (type: `array`):

Pega el XML completo de uno o más CFDI, uno por elemento del arreglo. Útil para llamadas por API y agentes de IA.

## `outputMode` (type: `string`):

'invoices' = una fila por CFDI (conceptos anidados). 'concepts' = una fila plana por concepto con los datos de la factura repetidos, ideal para CSV/Excel.

## `includeConcepts` (type: `boolean`):

En modo 'invoices', incluye la lista anidada de conceptos con sus impuestos.

## `deduplicateByUuid` (type: `boolean`):

Procesa y cobra cada UUID (folio fiscal) solo una vez por ejecución.

## `maxFiles` (type: `integer`):

Se detiene después de procesar esta cantidad de CFDI.

## `maxConcurrency` (type: `integer`):

Cuántas URLs descargar al mismo tiempo.

## Actor input object example

```json
{
  "outputMode": "invoices",
  "includeConcepts": true,
  "deduplicateByUuid": true,
  "maxFiles": 10000,
  "maxConcurrency": 5
}
```

# Actor output Schema

## `results` (type: `string`):

Un elemento por CFDI (o por concepto en modo 'concepts').

## `runSummary` (type: `string`):

Registro RUN_SUMMARY: totales por estatus de validación y estatus de descarga por URL.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("integriapps/cfdi-parser").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("integriapps/cfdi-parser").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call integriapps/cfdi-parser --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,integriapps/cfdi-parser"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Op5M4zKHrKtFZXAeN/builds/qS2lPmj49mLwbrsd9/openapi.json
