{
  "info": {
    "name": "FacturaX.app API",
    "description": "Colección oficial de FacturaX.app — Extracción OCR, generación Facturae 3.2.2 y firma XAdES-BES.\n\n## Configuración rápida\n1. Importa esta colección en Postman\n2. Ve a la pestaña \"Variables\" y pega tu API Key en `api_key`\n3. Ejecuta cualquier request\n\n## Base URL\nhttps://api.facturax.app\n\n## Docs completas\nhttps://facturax.app/api-docs\n\n## Firmador interactivo\nhttps://facturax.app/firmador-erp",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
    "_postman_id": "facturax-api-v2"
  },
  "variable": [
    {
      "key": "base_url",
      "value": "https://api.facturax.app",
      "type": "string"
    },
    {
      "key": "api_key",
      "value": "fct_PEGA_TU_API_KEY_AQUI",
      "type": "string",
      "description": "Tu API Key de FacturaX. Encuéntrala en Dashboard → API Keys"
    },
    {
      "key": "certificate_id",
      "value": "",
      "type": "string",
      "description": "ID del certificado gestionado. Se obtiene con POST /certificates"
    }
  ],
  "item": [
    {
      "name": "🔍 Extracción OCR",
      "item": [
        {
          "name": "PDF → JSON estructurado",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "body": {
              "mode": "formdata",
              "formdata": [
                {
                  "key": "file",
                  "type": "file",
                  "src": "",
                  "description": "Factura en PDF, JPG o PNG (máx. 20MB)"
                }
              ]
            },
            "url": {
              "raw": "{{base_url}}/extract",
              "host": ["{{base_url}}"],
              "path": ["extract"]
            },
            "description": "Extrae los datos de una factura PDF usando OCR + IA.\n\nDevuelve: emisor, receptor, número de factura, fecha, importes, IVA, IRPF, IBAN, líneas de detalle y categorización PGC.\n\n⚠️ Consume 1 crédito."
          },
          "response": [
            {
              "name": "200 OK — Datos extraídos",
              "status": "OK",
              "code": 200,
              "_postman_previewlanguage": "json",
              "body": "{\n  \"vendor_name\": \"Suministros García S.L.\",\n  \"vendor_vat\": \"B12345678\",\n  \"vendor_address\": \"Calle Mayor 1, Madrid\",\n  \"buyer_name\": \"Mi Empresa S.A.\",\n  \"buyer_vat\": \"A87654321\",\n  \"invoice_number\": \"F2024-0892\",\n  \"invoice_date\": \"2024-06-15\",\n  \"subtotal\": 1000.00,\n  \"tax_rate\": 21,\n  \"tax\": 210.00,\n  \"total\": 1210.00,\n  \"currency\": \"EUR\",\n  \"iban\": \"ES21 0049 0001 5021 0001 3303\",\n  \"pgc_category\": \"628 - Suministros\",\n  \"confidence_score\": 0.97,\n  \"warnings\": [],\n  \"log_id\": 1234\n}"
            }
          ]
        },
        {
          "name": "Batch — múltiples PDFs",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "body": {
              "mode": "formdata",
              "formdata": [
                {
                  "key": "files",
                  "type": "file",
                  "src": [],
                  "description": "Hasta 50 PDFs en una sola llamada"
                }
              ]
            },
            "url": {
              "raw": "{{base_url}}/extract/batch",
              "host": ["{{base_url}}"],
              "path": ["extract", "batch"]
            },
            "description": "Envía hasta 50 facturas en una sola llamada. Procesamiento en background.\n\nDevuelve un `job_id` — consulta el estado con GET /extract/batch/{job_id}.\n\n⚠️ Consume 1 crédito por factura procesada."
          },
          "response": []
        },
        {
          "name": "Estado de un batch",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "url": {
              "raw": "{{base_url}}/extract/batch/:job_id",
              "host": ["{{base_url}}"],
              "path": ["extract", "batch", ":job_id"],
              "variable": [
                {
                  "key": "job_id",
                  "value": "job_abc123",
                  "description": "ID del job devuelto por POST /extract/batch"
                }
              ]
            },
            "description": "Consulta el estado de un job de batch. Cuando `status` es `done`, incluye los resultados de todas las facturas."
          },
          "response": []
        }
      ]
    },
    {
      "name": "📄 Generar Facturae XML",
      "item": [
        {
          "name": "JSON → Facturae firmado",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              },
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"vendor_name\": \"Tu Empresa S.L.\",\n  \"vendor_vat\": \"B12345678\",\n  \"vendor_address\": \"Calle Mayor 1\",\n  \"vendor_city\": \"Madrid\",\n  \"vendor_postal_code\": \"28001\",\n  \"vendor_country\": \"ESP\",\n  \"buyer_name\": \"Ayuntamiento de Alcobendas\",\n  \"buyer_vat\": \"P2800200B\",\n  \"buyer_address\": \"Plaza Mayor 1\",\n  \"buyer_city\": \"Alcobendas\",\n  \"buyer_postal_code\": \"28100\",\n  \"invoice_number\": \"F2024-001\",\n  \"invoice_date\": \"2024-06-15\",\n  \"due_date\": \"2024-07-15\",\n  \"subtotal\": 1000.00,\n  \"tax\": 210.00,\n  \"total\": 1210.00,\n  \"currency\": \"EUR\",\n  \"payment_method\": \"transferencia\",\n  \"iban\": \"ES21 0049 0001 5021 0001 3303\",\n  \"line_items\": [\n    {\n      \"description\": \"Servicio de mantenimiento\",\n      \"quantity\": 10,\n      \"unit_price\": 100.00,\n      \"total\": 1000.00,\n      \"tax_rate\": 21\n    }\n  ]\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{base_url}}/convert",
              "host": ["{{base_url}}"],
              "path": ["convert"]
            },
            "description": "Genera un Facturae 3.2.2 firmado con XAdES-BES a partir de datos JSON.\n\nSi tienes un certificado .p12 guardado en el perfil o pasas `X-Certificate-ID`, el XML se firma automáticamente.\n\n⚠️ Consume 1 crédito."
          },
          "response": [
            {
              "name": "200 OK — XML firmado",
              "status": "OK",
              "code": 200,
              "_postman_previewlanguage": "json",
              "body": "{\n  \"xml\": \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>...<ds:Signature>...</ds:Signature>\",\n  \"xml_base64\": \"PD94bWwg...\",\n  \"signed\": true,\n  \"source\": \"json\",\n  \"filename\": \"facturae_F2024-001.xml\",\n  \"log_id\": 1234,\n  \"invoice\": {\n    \"vendor_name\": \"Tu Empresa S.L.\",\n    \"invoice_number\": \"F2024-001\",\n    \"total\": 1210.0\n  },\n  \"warnings\": [],\n  \"confidence\": 1.0\n}"
            }
          ]
        },
        {
          "name": "PDF → Facturae firmado",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "body": {
              "mode": "formdata",
              "formdata": [
                {
                  "key": "file",
                  "type": "file",
                  "src": "",
                  "description": "Factura PDF (máx. 20MB)"
                }
              ]
            },
            "url": {
              "raw": "{{base_url}}/convert",
              "host": ["{{base_url}}"],
              "path": ["convert"]
            },
            "description": "Sube un PDF, la IA extrae los datos y genera el Facturae 3.2.2 firmado en una sola llamada.\n\n⚠️ Consume 1 crédito."
          },
          "response": []
        },
        {
          "name": "JSON → Facturae con certificado gestionado",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              },
              {
                "key": "X-Certificate-ID",
                "value": "{{certificate_id}}",
                "type": "text",
                "description": "ID del certificado gestionado (recomendado para ERPs multi-cliente)"
              },
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"vendor_name\": \"Tu Empresa S.L.\",\n  \"vendor_vat\": \"B12345678\",\n  \"buyer_name\": \"Ministerio de Hacienda\",\n  \"buyer_vat\": \"S2800012B\",\n  \"invoice_number\": \"F2024-001\",\n  \"invoice_date\": \"2024-06-15\",\n  \"subtotal\": 1000.00,\n  \"tax\": 210.00,\n  \"total\": 1210.00\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{base_url}}/convert",
              "host": ["{{base_url}}"],
              "path": ["convert"]
            },
            "description": "Para ERPs multi-cliente. Usa un certificado gestionado por su ID.\n\nFlujo:\n1. POST /certificates → obtén `certificate_id`\n2. Guárdalo en tu BD asociado al cliente\n3. Úsalo en cada llamada con `X-Certificate-ID`\n\nEl cliente no necesita interactuar — todo transparente."
          },
          "response": []
        }
      ]
    },
    {
      "name": "✍️ Firmar XML existente",
      "item": [
        {
          "name": "XML → XML firmado (fichero)",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              },
              {
                "key": "X-Certificate-ID",
                "value": "{{certificate_id}}",
                "type": "text",
                "description": "Opcional si tienes certificado gestionado"
              },
              {
                "key": "X-External-Ref",
                "value": "F2024-001",
                "type": "text",
                "description": "Tu ID interno — se incluye en el webhook invoice.signed"
              }
            ],
            "body": {
              "mode": "formdata",
              "formdata": [
                {
                  "key": "file",
                  "type": "file",
                  "src": "",
                  "description": "XML Facturae sin firmar (.xml)"
                }
              ]
            },
            "url": {
              "raw": "{{base_url}}/sign",
              "host": ["{{base_url}}"],
              "path": ["sign"]
            },
            "description": "Para ERPs que ya generan su propio XML Facturae pero no tienen firma XAdES-BES integrada.\n\nEnvía el XML sin firmar, recibe el mismo .xml con la firma XAdES-BES incrustada, listo para subir a FACe.\n\n**Prioridad de certificado:**\n1. `X-Certificate-ID` (recomendado para ERPs)\n2. `X-P12-B64` + `X-P12-Password`\n3. Certificado del perfil del usuario\n\n⚠️ Consume 1 crédito."
          },
          "response": [
            {
              "name": "200 OK — XML firmado",
              "status": "OK",
              "code": 200,
              "_postman_previewlanguage": "json",
              "body": "{\n  \"xml\": \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>...<ds:Signature>...</ds:Signature>\",\n  \"xml_base64\": \"PD94bWwg...\",\n  \"signed\": true,\n  \"source\": \"sign\",\n  \"filename\": \"factura.xml\",\n  \"log_id\": 1234\n}"
            }
          ]
        },
        {
          "name": "XML → XML firmado (body directo)",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              },
              {
                "key": "X-Certificate-ID",
                "value": "{{certificate_id}}",
                "type": "text"
              },
              {
                "key": "Content-Type",
                "value": "application/xml",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<fe:Facturae xmlns:fe=\"http://www.facturae.gob.es/formato/Version3_2_2/Facturae_v3_2_2.xsd\">\n  <!-- Tu XML Facturae sin firmar -->\n</fe:Facturae>",
              "options": {
                "raw": {
                  "language": "xml"
                }
              }
            },
            "url": {
              "raw": "{{base_url}}/sign",
              "host": ["{{base_url}}"],
              "path": ["sign"]
            },
            "description": "Alternativa a subir el fichero: envía el XML directamente en el body con Content-Type: application/xml.\n\nMás cómodo para integraciones server-to-server donde ya tienes el XML en memoria."
          },
          "response": []
        }
      ]
    },
    {
      "name": "🔐 Certificados gestionados",
      "item": [
        {
          "name": "Subir certificado .p12",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "body": {
              "mode": "formdata",
              "formdata": [
                {
                  "key": "file",
                  "type": "file",
                  "src": "",
                  "description": "Certificado .p12 o .pfx del cliente"
                },
                {
                  "key": "password",
                  "value": "contraseña_del_p12",
                  "type": "text",
                  "description": "Contraseña del certificado"
                },
                {
                  "key": "name",
                  "value": "Empresa Cliente S.L.",
                  "type": "text",
                  "description": "Nombre identificativo (opcional)"
                }
              ]
            },
            "url": {
              "raw": "{{base_url}}/certificates",
              "host": ["{{base_url}}"],
              "path": ["certificates"]
            },
            "description": "Sube el .p12 de un cliente una vez y obtén un `certificate_id`.\n\nGuarda el `certificate_id` en tu BD asociado al cliente. A partir de ahí, úsalo en `X-Certificate-ID` en cada llamada a /sign o /convert.\n\nEl cliente no necesita volver a subir el certificado — proceso transparente.\n\n**Requiere plan Pro o Business.**"
          },
          "response": [
            {
              "name": "200 OK — Certificado guardado",
              "status": "OK",
              "code": 200,
              "_postman_previewlanguage": "json",
              "body": "{\n  \"certificate_id\": \"cert_abc123def456\",\n  \"name\": \"Empresa Cliente S.L.\",\n  \"subject\": \"CN=EMPRESA CLIENTE SL, O=EMPRESA CLIENTE SL, C=ES\",\n  \"expires_at\": \"2027-05-15T00:00:00Z\",\n  \"active\": true\n}"
            }
          ]
        },
        {
          "name": "Listar certificados",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "url": {
              "raw": "{{base_url}}/certificates",
              "host": ["{{base_url}}"],
              "path": ["certificates"]
            },
            "description": "Lista todos los certificados gestionados de tu cuenta con su estado y fecha de caducidad."
          },
          "response": []
        },
        {
          "name": "Eliminar certificado",
          "request": {
            "method": "DELETE",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "url": {
              "raw": "{{base_url}}/certificates/:certificate_id",
              "host": ["{{base_url}}"],
              "path": ["certificates", ":certificate_id"],
              "variable": [
                {
                  "key": "certificate_id",
                  "value": "{{certificate_id}}"
                }
              ]
            },
            "description": "Elimina un certificado gestionado. No se puede deshacer."
          },
          "response": []
        }
      ]
    },
    {
      "name": "📥 Descargar facturas firmadas",
      "item": [
        {
          "name": "Descargar XML firmado por log_id",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "url": {
              "raw": "{{base_url}}/invoices/:log_id/facturae",
              "host": ["{{base_url}}"],
              "path": ["invoices", ":log_id", "facturae"],
              "variable": [
                {
                  "key": "log_id",
                  "value": "1234",
                  "description": "ID del log devuelto en la respuesta de /convert o /sign"
                }
              ]
            },
            "description": "Descarga el XML Facturae firmado de una factura ya procesada.\n\nEl `log_id` se obtiene en la respuesta de /convert o /sign. También llega en el webhook `invoice.signed`."
          },
          "response": []
        }
      ]
    },
    {
      "name": "🔔 Webhooks",
      "item": [
        {
          "name": "Listar webhooks",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "url": {
              "raw": "{{base_url}}/webhooks",
              "host": ["{{base_url}}"],
              "path": ["webhooks"]
            },
            "description": "Lista los webhooks configurados para tu API key."
          },
          "response": []
        },
        {
          "name": "Crear webhook",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              },
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"url\": \"https://tu-servidor.com/webhooks/facturax\",\n  \"events\": [\"invoice.signed\", \"invoice.extracted\", \"invoice.error\"]\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{base_url}}/webhooks",
              "host": ["{{base_url}}"],
              "path": ["webhooks"]
            },
            "description": "Crea un webhook. FacturaX enviará un POST a tu URL con cada evento.\n\n**Eventos disponibles:**\n- `invoice.signed` — XML firmado listo\n- `invoice.extracted` — datos extraídos del PDF\n- `invoice.error` — error en el procesamiento\n- `*` — todos los eventos\n\nGuarda el `secret` de la respuesta para verificar la firma HMAC-SHA256 de cada entrega."
          },
          "response": [
            {
              "name": "200 OK — Webhook creado",
              "status": "OK",
              "code": 200,
              "_postman_previewlanguage": "json",
              "body": "{\n  \"id\": 42,\n  \"url\": \"https://tu-servidor.com/webhooks/facturax\",\n  \"events\": [\"invoice.signed\"],\n  \"secret\": \"whsec_abc123...\",\n  \"active\": true\n}"
            }
          ]
        },
        {
          "name": "Eliminar webhook",
          "request": {
            "method": "DELETE",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "url": {
              "raw": "{{base_url}}/webhooks/:webhook_id",
              "host": ["{{base_url}}"],
              "path": ["webhooks", ":webhook_id"],
              "variable": [
                {
                  "key": "webhook_id",
                  "value": "42"
                }
              ]
            },
            "description": "Elimina un webhook."
          },
          "response": []
        }
      ]
    },
    {
      "name": "🔑 API Keys",
      "item": [
        {
          "name": "Info de mi key",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "url": {
              "raw": "{{base_url}}/keys/me",
              "host": ["{{base_url}}"],
              "path": ["keys", "me"]
            },
            "description": "Devuelve información de tu API key actual: plan, cuota usada, cuota restante, fecha de reset.\n\nÚtil para mostrar al usuario el consumo en tu software."
          },
          "response": [
            {
              "name": "200 OK",
              "status": "OK",
              "code": 200,
              "_postman_previewlanguage": "json",
              "body": "{\n  \"id\": 95,\n  \"name\": \"Mi integración\",\n  \"plan\": \"business\",\n  \"quota\": 7000,\n  \"used\": 142,\n  \"remaining\": 6858,\n  \"quota_reset_at\": \"2024-07-01T00:00:00Z\",\n  \"active\": true\n}"
            }
          ]
        },
        {
          "name": "Listar todas mis keys",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "X-API-Key",
                "value": "{{api_key}}",
                "type": "text"
              }
            ],
            "url": {
              "raw": "{{base_url}}/keys/list",
              "host": ["{{base_url}}"],
              "path": ["keys", "list"]
            },
            "description": "Lista todas las API keys de tu cuenta con su uso y estado."
          },
          "response": []
        }
      ]
    },
    {
      "name": "⚙️ Sistema",
      "item": [
        {
          "name": "Health check",
          "request": {
            "method": "GET",
            "header": [],
            "url": {
              "raw": "{{base_url}}/status",
              "host": ["{{base_url}}"],
              "path": ["status"]
            },
            "description": "Comprueba que la API está operativa. No requiere autenticación.\n\nÚtil para monitorización — si devuelve 200, la API está funcionando."
          },
          "response": [
            {
              "name": "200 OK",
              "status": "OK",
              "code": 200,
              "_postman_previewlanguage": "json",
              "body": "{\n  \"status\": \"ok\",\n  \"version\": \"1.0\",\n  \"b2\": \"ok\",\n  \"stripe\": \"ok\"\n}"
            }
          ]
        }
      ]
    }
  ]
}