SyyPro Rechnungen
Tamaño de fuente
Modo oscuro
EN 16931 · XRechnung 3.0 · Hybrid-PDF
← Documentación API

Referencia API

Documentación completa de la API de SyyPro Rechnungen  ·  v1  ·  EN 16931 konform  ·  XRechnung 3.0  ·  Hybrid-PDF

Base URL: https://rechnung.syypro.com/api/v1
🔑 Autenticación

Todos los endpoints excepto /health y /profiles requieren una clave API en el encabezado HTTP:

X-API-Key: xr_abc123yourkeyhere

Encuentre sus claves API en su Panel de control bajo la pestaña «Claves API». Cada clave siempre comienza con xr_.

⚠ Aviso de seguridad: Trate las claves API como contraseñas. Nunca las exponga en código frontend. Use variables de entorno (XR_API_KEY).
⚡ Limitación de velocidad
EndpointLímiteAlcance
/api/v1/* 60 Requests / Minute Pro API-Key (Token-Bucket)
/extract/upload (Web) 5 Requests / Minute Pro IP (nginx)
/auth/* (Login/Register) 5 Requests / Minute Pro IP (nginx)

Bei Überschreitung: HTTP 429 mit Body {"error":{"code":"rate_limited","message":"..."}}. Nach Ablauf der Minute wird das Bucket automatisch aufgefüllt.

GET /api/v1/health Comprobación de disponibilidad – no requiere autenticación

Endpoint ping simple. Comprueba si el servidor y la base de datos son accesibles. Ideal para monitorización, comprobaciones de salud y servicios de disponibilidad. No se requiere clave API.

Solicitud de ejemplo
curl https://rechnung.syypro.com/api/v1/health
import requests
r = requests.get("https://rechnung.syypro.com/api/v1/health")
print(r.json())
# {"status": "ok", "db": true}
const r = await fetch('https://rechnung.syypro.com/api/v1/health');
const data = await r.json();
// { status: "ok", db: true }
Respuesta
200 OK
{
  "status": "ok",
  "db": true
}
GET /api/v1/profiles Perfiles de factura disponibles – no requiere autenticación

Devuelve todos los perfiles de factura compatibles. Use el valor de key en los campos profile de otros endpoints.

Ejemplo
curl https://rechnung.syypro.com/api/v1/profiles
r = requests.get("https://rechnung.syypro.com/api/v1/profiles")
for p in r.json()["profiles"]:
    print(p["key"], "→", p["name"])
Respuesta
200 OK
{
  "profiles": [
    {
      "key":         "XRECHNUNG",
      "name":        "XRechnung 3.0",
      "standard":    "UBL 2.1",
      "description": "B2G-Pflichtformat für öffentliche Auftraggeber (Leitweg-ID erforderlich)"
    },
    {
      "key":         "B2B_UBL",
      "name":        "B2B (UBL 2.1)",
      "standard":    "UBL 2.1",
      "description": "EN-16931-konformes B2B-Format ohne Leitweg-ID-Pflicht"
    },
    {
      "key":         "ZUGFERD",
      "name":        "Hybrid-PDF (XRechnung eingebettet)",
      "standard":    "UBL 2.1",
      "description": "PDF-Rechnung mit eingebetteter XRechnung (UBL-XML, EN 16931)"
    }
  ]
}
POST /api/v1/invoices Generar factura desde JSON

Crea un XML XRechnung completo y válido EN-16931 a partir de un cuerpo JSON. Opcionalmente como PDF híbrido (XRechnung incrustada). Se requiere clave API.

Campos de solicitud (nivel superior)
CampoTipoObligatorioDescripción
profile string Obligatorio XRECHNUNG | B2B_UBL | ZUGFERD (Name historisch, liefert ein Hybrid-PDF mit eingebetteter XRechnung)
invoice_number string Obligatorio Eindeutige Rechnungsnummer (BT-1), z. B. RE-2026-0042
issue_date string (ISO) Obligatorio Rechnungsdatum, Format YYYY-MM-DD (BT-2)
due_date string (ISO) Obligatorio Fälligkeitsdatum, Format YYYY-MM-DD (BT-9)
currency string Obligatorio ISO 4217 Währungscode, z. B. EUR (BT-5)
buyer_reference string Condicional Leitweg-ID beim Profil XRECHNUNG Pflicht (BT-10). Format: 04011000-1234512345-06
seller Party Obligatorio Rechnungssteller (siehe Party-Objekt)
buyer Party Obligatorio Rechnungsempfänger (siehe Party-Objekt)
lines LineItem[] Obligatorio Mindestens eine Rechnungsposition (siehe LineItem-Objekt)
bank_account object Opcional {"iban": "DE89370400440532013000"} – Zahlungsinformationen
note string Opcional Freitext-Notiz auf der Rechnung (BT-22)
include_pdf boolean Opcional Wenn true: plain PDF als Base64 im Feld pdf_base64
include_zugferd boolean Opcional Wenn true: Hybrid-PDF (PDF mit eingebetteter XRechnung, UBL) als Base64 im Feld zugferd_base64. Feldname historisch. Standard: false
Solicitud de ejemplo
curl -X POST https://rechnung.syypro.com/api/v1/invoices \
  -H "X-API-Key: $XR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "profile": "XRECHNUNG",
    "invoice_number": "RE-2026-0042",
    "issue_date": "2026-05-01",
    "due_date": "2026-05-15",
    "currency": "EUR",
    "buyer_reference": "04011000-1234512345-06",
    "seller": {
      "name": "Mustermann IT GmbH",
      "vat_id": "DE123456789",
      "contact": {"name": "Max Mustermann", "email": "rechnung@mustermann-it.de", "phone": "0711 123456"},
      "address": {
        "street": "Musterstraße 12",
        "postal_code": "70173",
        "city": "Stuttgart",
        "country_code": "DE"
      }
    },
    "buyer": {
      "name": "Landratsamt Musterhausen",
      "contact": {"email": "rechnung@musterhausen.de"},
      "address": {
        "street": "Rathausplatz 1",
        "postal_code": "70173",
        "city": "Musterhausen",
        "country_code": "DE"
      }
    },
    "lines": [{
      "name": "Webentwicklung",
      "quantity": "12",
      "unit_code": "HUR",
      "unit_price": "120.00",
      "tax_percent": "19"
    }],
    "bank_account": { "iban": "DE89370400440532013000" }
  }'
import requests, os

XR_KEY = os.environ["XR_API_KEY"]
BASE    = "https://rechnung.syypro.com/api/v1"

payload = {
    "profile": "XRECHNUNG",
    "invoice_number": "RE-2026-0042",
    "issue_date": "2026-05-01",
    "due_date":   "2026-05-15",
    "currency":   "EUR",
    "buyer_reference": "04011000-1234512345-06",
    "seller": {
        "name": "Mustermann IT GmbH",
        "vat_id": "DE123456789",
        "contact": {"name": "Max Mustermann", "email": "rechnung@mustermann-it.de", "phone": "0711 123456"},
        "address": {
            "street": "Musterstraße 12",
            "postal_code": "70173",
            "city": "Stuttgart",
            "country_code": "DE"
        }
    },
    "buyer": {
        "name": "Landratsamt Musterhausen",
        "contact": {"email": "rechnung@musterhausen.de"},
        "address": {
            "street": "Rathausplatz 1",
            "postal_code": "70173",
            "city": "Musterhausen",
            "country_code": "DE"
        }
    },
    "lines": [{"name": "Webentwicklung", "quantity": "12",
               "unit_code": "HUR", "unit_price": "120.00", "tax_percent": "19"}],
    "bank_account": {"iban": "DE89370400440532013000"}
}

r = requests.post(f"{BASE}/invoices",
                  headers={"X-API-Key": XR_KEY},
                  json=payload)
r.raise_for_status()
data = r.json()

import base64
xml = base64.b64decode(data["xml_base64"])
with open("rechnung.xml", "wb") as f:
    f.write(xml)
print("Validierung:", data["validation"])
const payload = {
  profile: "XRECHNUNG",
  invoice_number: "RE-2026-0042",
  issue_date: "2026-05-01",
  due_date: "2026-05-15",
  currency: "EUR",
  buyer_reference: "04011000-1234512345-06",
  seller: {
    name: "Mustermann IT GmbH",
    vat_id: "DE123456789",
    contact: { name: "Max Mustermann", email: "rechnung@mustermann-it.de", phone: "0711 123456" },
    address: { street: "Musterstraße 12", postal_code: "70173",
               city: "Stuttgart", country_code: "DE" }
  },
  buyer: {
    name: "Landratsamt Musterhausen",
    contact: { email: "rechnung@musterhausen.de" },
    address: { street: "Rathausplatz 1", postal_code: "70173",
               city: "Musterhausen", country_code: "DE" }
  },
  lines: [{ name: "Webentwicklung", quantity: "12",
            unit_code: "HUR", unit_price: "120.00", tax_percent: "19" }],
  bank_account: { iban: "DE89370400440532013000" }
};

const resp = await fetch('https://rechnung.syypro.com/api/v1/invoices', {
  method: 'POST',
  headers: { 'X-API-Key': process.env.XR_API_KEY,
             'Content-Type': 'application/json' },
  body: JSON.stringify(payload)
});
const data = await resp.json();

// Decode XML
const xmlBytes = atob(data.xml_base64);
console.log('Validation OK:', data.validation.ok);
Respuesta
200 OK
{
  "invoice": {
    "invoice_number": "RE-2026-0042",
    "issue_date":     "2026-05-01",
    "total_net":      1440.0,
    "total_tax":      273.6,
    "total_gross":    1713.6
  },
  "validation": {
    "ok":     true,
    "errors": []
  },
  "xml_base64":     "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0...",
  "pdf_base64":     null,
  "zugferd_base64": null,
  "document_id":    1234
}
422 Validierungsfehler
{
  "error": {
    "code":    "invalid_invoice",
    "message": "Rechnungsdaten nicht EN-16931-konform.",
    "errors":  [
      { "level": "error", "code": "BR-04",
        "message": "Seller VAT identifier is mandatory." }
    ]
  }
}
POST /api/v1/validate Solo validar – sin XML, sin PDF

Mismo cuerpo de solicitud que /invoices, pero la respuesta contiene solo el resultado de validación. Útil para pre-verificación antes de la creación real. Se requiere clave API.

Ejemplo
curl -X POST https://rechnung.syypro.com/api/v1/validate \
  -H "X-API-Key: $XR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ ... selber Body wie /invoices ... }'
r = requests.post(f"{BASE}/validate",
                  headers={"X-API-Key": XR_KEY},
                  json=payload)  # gleicher Body wie /invoices
result = r.json()
if result["ok"]:
    print("Rechnung ist EN-16931-konform ✓")
else:
    for e in result["errors"]:
        print(f"[{e['level'].upper()}] {e['code']}: {e['message']}")
Respuesta
200 Validierung bestanden
{
  "ok":     true,
  "errors": []
}
200 Validierung mit Fehlern
{
  "ok": false,
  "errors": [
    {
      "level":   "error",
      "code":    "BR-04",
      "message": "Seller VAT identifier is mandatory."
    },
    {
      "level":   "warning",
      "code":    "BT-10",
      "message": "Buyer reference recommended for XRECHNUNG profile."
    }
  ]
}
POST /api/v1/extract Subir PDF → extraer XML XRechnung

Envía una factura PDF existente como multipart/form-data. El escáner lee el XML de factura electrónica incrustado o reconoce los campos mediante reglas a partir del texto del PDF y los valida. El XML solo se devuelve si todos los valores se reconocieron de forma fiable y son válidos (downloads_advised). Se requiere clave API.

Campos del formulario
CampoTipoObligatorioDescripción
file file (PDF) Obligatorio PDF-Datei, max. 16 MB. Nur application/pdf akzeptiert.
profile string Opcional Ausgabe-Profil: XRECHNUNG | B2B_UBL | ZUGFERD. Standard: XRECHNUNG
include_zugferd string Opcional "1" = Hybrid-PDF erzeugen (Standard: "0"). Achtung: erhöht Verarbeitungszeit.
Ejemplo
curl -X POST https://rechnung.syypro.com/api/v1/extract \
  -H "X-API-Key: $XR_API_KEY" \
  -F "file=@meine-rechnung.pdf" \
  -F "profile=XRECHNUNG" \
  -F "include_zugferd=0"
import requests, base64, os

XR_KEY = os.environ["XR_API_KEY"]

with open("meine-rechnung.pdf", "rb") as f:
    r = requests.post(
        "https://rechnung.syypro.com/api/v1/extract",
        headers={"X-API-Key": XR_KEY},
        files={"file": ("rechnung.pdf", f, "application/pdf")},
        data={"profile": "XRECHNUNG", "include_zugferd": "0"}
    )

data = r.json()
print(f"Konfidenz: {data['confidence']}%")
print(f"Warnungen: {data.get('warnings', [])}")

if r.status_code == 200 and data["downloads_advised"]:
    xml = base64.b64decode(data["xml_base64"])
    with open("output.xml", "wb") as f:
        f.write(xml)
else:
    # 422: Werte unsicher oder ungültig -> Felder in data["invoice"] prüfen
    print("Bitte prüfen:", data.get("gate_reason"), data["validation"]["errors"])
const formData = new FormData();
formData.append('file', pdfFile); // File-Objekt aus input[type=file]
formData.append('profile', 'XRECHNUNG');
formData.append('include_zugferd', '0');

const resp = await fetch('https://rechnung.syypro.com/api/v1/extract', {
  method: 'POST',
  headers: { 'X-API-Key': process.env.XR_API_KEY },
  // Content-Type NICHT setzen – FormData setzt boundary automatisch
  body: formData
});
const data = await resp.json();
console.log(`Konfidenz: ${data.confidence}%`, data.warnings);
if (resp.ok && data.downloads_advised) {
  const xmlBytes = atob(data.xml_base64);
} else {
  console.warn('Bitte prüfen:', data.gate_reason, data.validation.errors);
}
Respuesta
200 OK
{
  "confidence": 87,
  "warnings":   ["due_date konnte nicht sicher erkannt werden"],
  "checklist": {
    "BT-1":  { "name": "invoice_number", "ok": true  },
    "BT-2":  { "name": "issue_date",     "ok": true  },
    "BT-9":  { "name": "due_date",       "ok": false }
  },
  "invoice": { "invoice_number": "RE-2026-0042", ... },
  "validation": { "ok": true, "errors": [] },
  "reliable":          true,
  "downloads_advised": true,
  "xml_base64":     "PD94bWwgdmVyc2lvbj0i...",
  "zugferd_base64": null,
  "document_id":    1234
}

ⓘ Si downloads_advised es false, la API responde con 422, xml_base64 es null y no se consume cuota. gate_reason indica el motivo (validation_failed o uncertain_values). Revisa los campos de invoice y crea la factura con POST /api/v1/invoices. Las facturas válidas aparecen en tu historial (document_id).

📐 Modelo de datos

Objetos reutilizados en los cuerpos de solicitud:

Party (seller / buyer)
CampoTipoObligatorioDescripción
namestringObligatorioFirmenname (BT-27 / BT-44)
vat_idstringCondicionalUSt-IdNr., z. B. DE123456789 – beim Verkäufer Pflicht (BT-31)
tax_numberstringOpcionalSteuernummer, wenn keine VAT-ID vorhanden (BT-32)
addressAddressObligatorioPostanschrift (siehe Address-Objekt)
emailstringOpcionalKontakt-E-Mail
contact_namestringOpcionalAnsprechpartner
Address
CampoTipoObligatorioDescripción
streetstringObligatorioStraße + Hausnummer
postal_codestringObligatorioPostleitzahl
citystringObligatorioStadt
country_codestringObligatorioISO 3166 Alpha-2, z. B. DE
LineItem
CampoTipoObligatorioDescripción
namestringObligatorioBezeichnung der Position (BT-153)
quantitystringObligatorioMenge als Dezimalzahl, z. B. "12" oder "1.5" (BT-129)
unitstringObligatorioUN/CEFACT-Code: HUR Stunde · C62 Stück · KGM kg · DAY Tag (BT-130)
unit_pricestringObligatorioNetto-Einzelpreis, z. B. "120.00" (BT-146)
tax_percentstringObligatorioSteuersatz: "19", "7" oder "0" (BT-152)
descriptionstringOpcionalErweiterte Beschreibung (BT-154)
article_numberstringOpcionalArtikelnummer / SKU (BT-155)
⚠ Códigos de error

Todas las respuestas de error tienen el formato:

{ "error": { "code": "machine_readable_code", "message": "Menschenlesbare Beschreibung." } }
HTTPCódigoSignificado
400invalid_bodyJSON fehlerhaft oder Pflichtfelder fehlen (Feldname im message)
401unauthorizedAPI-Key fehlt (X-API-Key Header) oder ungültig / abgelaufen
413too_largeUpload > 16 MB – nginx-Limit
415wrong_typeNur PDF akzeptiert bei /extract (application/pdf)
422invalid_invoiceRechnungsdaten nicht EN-16931-konform – errors-Array enthält Details
422extract_failedPDF konnte nicht gelesen/geparst werden (beschädigt / verschlüsselt)
422extract_xml_failedExtraktion OK, aber XML-Generierung fehlgeschlagen (Hinweis im message)
429rate_limitedMehr als 60 Requests/Minute – warte und wiederhole
500server_errorUnerwarteter Server-Fehler – bitte an support@syypro.com melden
503api_disabledAPI vorübergehend deaktiviert
🛠 Ejemplos SDK completos

Fragmentos de integración listos para copiar para pilas comunes:

"""
SyyPro XRechnung API – Python-Schnellstart
pip install requests
"""
import requests, base64, os

API_BASE = "https://rechnung.syypro.com/api/v1"
API_KEY  = os.environ["XR_API_KEY"]
HEADERS  = {"X-API-Key": API_KEY, "Content-Type": "application/json"}

def create_invoice(data: dict) -> dict:
    """Erstellt XRechnung XML, gibt Antwort-Dict zurück."""
    r = requests.post(f"{API_BASE}/invoices", headers=HEADERS, json=data)
    r.raise_for_status()
    return r.json()

def save_xml(response: dict, path: str) -> None:
    xml_bytes = base64.b64decode(response["xml_base64"])
    with open(path, "wb") as f:
        f.write(xml_bytes)

def validate(data: dict) -> bool:
    r = requests.post(f"{API_BASE}/validate", headers=HEADERS, json=data)
    result = r.json()
    for e in result.get("errors", []):
        print(f"  [{e['level']}] {e['code']}: {e['message']}")
    return result.get("ok", False)

# Beispiel
payload = {
    "profile": "XRECHNUNG",
    "invoice_number": "RE-2026-0042",
    "issue_date": "2026-05-01",
    "due_date":   "2026-05-15",
    "currency":   "EUR",
    "buyer_reference": "04011000-1234512345-06",
    "seller": {
        "name": "Muster GmbH", "vat_id": "DE123456789",
        "contact": {"name": "Max Mustermann", "email": "rechnung@muster.de", "phone": "0711 123456"},
        "address": {"street": "Str. 1", "postal_code": "70173",
                    "city": "Stuttgart", "country_code": "DE"}
    },
    "buyer": {
        "name": "Behörde XY",
        "contact": {"email": "rechnung@musterhausen.de"},
        "address": {"street": "Amt 1", "postal_code": "10115",
                    "city": "Berlin", "country_code": "DE"}
    },
    "lines": [
        {"name": "Beratung", "quantity": "8", "unit_code": "HUR",
         "unit_price": "150.00", "tax_percent": "19"}
    ],
    "bank_account": {"iban": "DE89370400440532013000"}
}

if validate(payload):
    result = create_invoice(payload)
    save_xml(result, "rechnung.xml")
    print(f"Erstellt: {result['invoice']['total_gross']} EUR")
// SyyPro XRechnung API – Node.js Schnellstart (ESM)
// Kein npm-Package nötig – natives fetch() seit Node 18

const API_BASE = 'https://rechnung.syypro.com/api/v1';
const API_KEY  = process.env.XR_API_KEY;

async function createInvoice(payload) {
  const resp = await fetch(`${API_BASE}/invoices`, {
    method: 'POST',
    headers: {
      'X-API-Key':     API_KEY,
      'Content-Type':  'application/json'
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const err = await resp.json();
    throw new Error(`API Error ${resp.status}: ${err.error?.message}`);
  }
  return resp.json();
}

async function extractPdf(filePath) {
  const { readFileSync } = await import('fs');
  const { Blob } = await import('buffer');
  const fileBytes = readFileSync(filePath);
  const formData  = new FormData();
  formData.append('file', new Blob([fileBytes], { type: 'application/pdf' }),
                  'rechnung.pdf');
  formData.append('profile', 'XRECHNUNG');

  const resp = await fetch(`${API_BASE}/extract`, {
    method: 'POST',
    headers: { 'X-API-Key': API_KEY },
    body: formData
  });
  return resp.json();
}

// Beispiel
const payload = {
  profile: 'XRECHNUNG',
  invoice_number: 'RE-2026-0042',
  issue_date: '2026-05-01', due_date: '2026-05-15',
  currency: 'EUR', buyer_reference: '04011000-1234512345-06',
  seller: { name: 'Muster GmbH', vat_id: 'DE123456789',
            contact: { name: 'Max Mustermann', email: 'rechnung@muster.de', phone: '0711 123456' },
            address: { street: 'Str. 1', postal_code: '70173',
                       city: 'Stuttgart', country_code: 'DE' } },
  buyer:  { name: 'Behörde XY', contact: { email: 'rechnung@behoerde.de' },
            address: { street: 'Amt 1', postal_code: '10115',
                       city: 'Berlin', country_code: 'DE' } },
  lines: [{ name: 'Beratung', quantity: '8', unit_code: 'HUR',
            unit_price: '150.00', tax_percent: '19' }],
  bank_account: { iban: 'DE89370400440532013000' }
};

const result = await createInvoice(payload);
const xmlBuf = Buffer.from(result.xml_base64, 'base64');
require('fs').writeFileSync('rechnung.xml', xmlBuf);
console.log('Total:', result.invoice.total_gross, 'EUR');
<?php
// SyyPro XRechnung API – PHP Schnellstart

$API_BASE = 'https://rechnung.syypro.com/api/v1';
$API_KEY  = getenv('XR_API_KEY');

function xr_post(string $endpoint, array $data, string $apiKey, string $base): array {
    $ch = curl_init("$base/$endpoint");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($data),
        CURLOPT_HTTPHEADER     => [
            "X-API-Key: $apiKey",
            'Content-Type: application/json'
        ]
    ]);
    $body   = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($status >= 400) {
        $err = json_decode($body, true);
        throw new RuntimeException("API Error $status: " . ($err['error']['message'] ?? $body));
    }
    return json_decode($body, true);
}

$payload = [
    'profile'          => 'XRECHNUNG',
    'invoice_number'   => 'RE-2026-0042',
    'issue_date'       => '2026-05-01',
    'due_date'         => '2026-05-15',
    'currency'         => 'EUR',
    'buyer_reference'  => '04011000-1234512345-06',
    'seller' => [
        'name'    => 'Muster GmbH',
        'vat_id'  => 'DE123456789',
        'contact' => ['name' => 'Max Mustermann', 'email' => 'rechnung@muster.de', 'phone' => '0711 123456'],
        'address' => ['street' => 'Str. 1', 'postal_code' => '70173',
                      'city' => 'Stuttgart', 'country_code' => 'DE']
    ],
    'buyer' => [
        'name'    => 'Behörde XY',
        'contact' => ['email' => 'rechnung@behoerde.de'],
        'address' => ['street' => 'Amt 1', 'postal_code' => '10115',
                      'city' => 'Berlin', 'country_code' => 'DE']
    ],
    'lines' => [[
        'name' => 'Beratung', 'quantity' => '8', 'unit_code' => 'HUR',
        'unit_price' => '150.00', 'tax_percent' => '19'
    ]],
    'bank_account' => ['iban' => 'DE89370400440532013000']
];

$result = xr_post('invoices', $payload, $API_KEY, $API_BASE);
file_put_contents('rechnung.xml', base64_decode($result['xml_base64']));
echo "Rechnung erstellt: " . $result['invoice']['total_gross'] . " EUR\n";
#!/bin/bash
# SyyPro XRechnung API – Bash Schnellstart
# Benötigt: curl, jq

API_BASE="https://rechnung.syypro.com/api/v1"
# Key aus Umgebungsvariable laden (nie hartkodieren!)
XR_KEY="${XR_API_KEY}"

# ── Health check ──────────────────────────────────────────────
echo "=== Health ==="
curl -sf "$API_BASE/health" | jq .

# ── Verfügbare Profile auflisten ──────────────────────────────
echo "=== Profile ==="
curl -sf "$API_BASE/profiles" | jq '[.profiles[].key]'

# ── Rechnung erstellen ────────────────────────────────────────
echo "=== Rechnung erstellen ==="
RESPONSE=$(curl -sf -X POST "$API_BASE/invoices" \
  -H "X-API-Key: $XR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "profile": "XRECHNUNG",
    "invoice_number": "RE-SHELL-001",
    "issue_date": "2026-05-12",
    "due_date": "2026-05-26",
    "currency": "EUR",
    "buyer_reference": "04011000-1234512345-06",
    "seller": {
      "name": "Shell Script GmbH",
      "vat_id": "DE999999999",
      "contact": {"name": "Max Mustermann", "email": "rechnung@mustermann-it.de", "phone": "0711 123456"},
      "address": {"street":"Bash-Allee 1","postal_code":"70173",
                  "city":"Stuttgart","country_code":"DE"}
    },
    "buyer": {
      "name": "Testamt",
      "contact": {"email": "rechnung@musterhausen.de"},
      "address": {"street":"Amtstr. 1","postal_code":"10115",
                  "city":"Berlin","country_code":"DE"}
    },
    "lines": [{"name":"Dienst","quantity":"1","unit_code":"C62",
               "unit_price":"100.00","tax_percent":"19"}],
    "bank_account": {"iban":"DE89370400440532013000"}
  }')

echo "$RESPONSE" | jq '{ok: .validation.ok, total: .invoice.total_gross}'

# XML speichern
echo "$RESPONSE" | jq -r '.xml_base64' | base64 -d > rechnung.xml
echo "XML gespeichert: rechnung.xml ($(wc -c < rechnung.xml) Bytes)"