Skip to content

Início rápido

Valide a sua primeira fatura eletrónica através da API em cerca de cinco minutos.

1. Criar uma conta gratuita e uma chave de teste

Inicie sessão em https://einvoiceengine.com/login com o seu endereço de e-mail. Abra Chaves API e crie uma chave de teste. Começa por einv_test_ e é mostrada uma única vez — guarde-a no seu gestor de segredos.

As chaves de teste utilizam o motor de validação real. São gratuitas, nunca são faturadas e estão limitadas à quota sandbox do seu plano.

export EINV_BASE=https://einvoiceengine.com
export EINV_KEY=einv_test_...

2. Validar uma fatura

Envie o XML como corpo do pedido. Funciona qualquer documento XRechnung 3.0 ou EN 16931 em UBL ou CII, bem como um PDF ZUGFeRD / Factur-X (Content-Type: application/pdf).

validate.sh

#!/usr/bin/env bash
# Validate an invoice with curl.
# EINV_BASE: API base URL (e.g. https://einvoicing.example.com); EINV_KEY: your API key.
set -euo pipefail
curl -sS --fail-with-body "$EINV_BASE/v1/invoices/validate" \
  -H "Authorization: Bearer $EINV_KEY" \
  -H "Content-Type: application/xml" \
  --data-binary @"${1:-invoice.xml}"

Não tem nenhuma fatura à mão? Transfira o exemplo oficial ou o exemplo com erros.

Ou deixe que a API crie faturas de teste por si. POST /v1/testdata devolve faturas sintéticas no formato que indicar, válidas e com erros típicos, cada uma já verificada com as regras oficiais. Não é faturado e nada é guardado.

curl -X POST $EINV_BASE/v1/testdata \
  -H "Authorization: Bearer $EINV_KEY" -H "Content-Type: application/json" \
  -d '{ "target": "xrechnung-ubl" }'

Cada caso contém name, filename, document, expected e actual. GET /v1/testdata/cases lista os casos e os formatos de destino.

3. Ler o resultado

{
  "status": "invalid",
  "valid": false,
  "detected": { "format": "xrechnung-ubl", "syntax": "ubl", "profile": "XRechnung", "version": "3.0" },
  "summary": { "errors": 2, "warnings": 0, "infos": 1 },
  "findings": [
    {
      "severity": "error",
      "ruleId": "BR-DE-15",
      "message": "[BR-DE-15] Das Element \"Buyer reference\" (BT-10) muss übermittelt werden.",
      "explanation": "XRechnung requires the buyer reference (BT-10). For German public buyers this is the Leitweg-ID.",
      "suggestion": "Set cbc:BuyerReference (UBL) or ram:BuyerReference (CII) to the Leitweg-ID or reference supplied by the buyer.",
      "location": { "path": "/Invoice", "line": 2, "column": 1 }
    }
  ]
}
  • status é valid, invalid ou unsupported. Só os conjuntos de regras oficiais o determinam.
  • message é o texto oficial da regra, literal. explanation e suggestion reformulam-no em linguagem simples.
  • Os resultados são devolvidos em inglês, alemão, francês, espanhol, italiano, polaco, neerlandês ou português: acrescente ?lang=pt (ou en, de, fr, es, it, pl, nl) ou envie Accept-Language. O texto oficial da regra mantém-se em message; messageTranslation acrescenta uma tradução não oficial quando existe uma.
  • coverage lista exatamente que conjuntos de regras foram executados e o que não foi verificado.

4. O mesmo em TypeScript e Python

validate.ts

// Validate an invoice with TypeScript (Node 20+, no dependencies).
// Run: EINV_BASE=… EINV_KEY=… npx tsx validate.ts invoice.xml
import { readFile } from "node:fs/promises";

const base = process.env.EINV_BASE!;
const key = process.env.EINV_KEY!;
const xml = await readFile(process.argv[2] ?? "invoice.xml");

const res = await fetch(`${base}/v1/invoices/validate`, {
  method: "POST",
  headers: { authorization: `Bearer ${key}`, "content-type": "application/xml" },
  body: xml,
});
if (!res.ok) {
  const { error } = await res.json();
  throw new Error(`${error.code}: ${error.message} (request ${error.requestId})`);
}
const result = await res.json();
console.log(result.status, `${result.summary.errors} errors`);
for (const f of result.findings.filter((f: { severity: string }) => f.severity === "error")) {
  console.log(`- ${f.ruleId}: ${f.explanation} (line ${f.location?.line ?? "?"})`);
}

validate.py

"""Validate an invoice with Python (standard library only).

Run: EINV_BASE=... EINV_KEY=... python3 validate.py invoice.xml
"""
import json
import os
import sys
import urllib.error
import urllib.request

base = os.environ["EINV_BASE"]
key = os.environ["EINV_KEY"]
path = sys.argv[1] if len(sys.argv) > 1 else "invoice.xml"

with open(path, "rb") as f:
    body = f.read()

req = urllib.request.Request(
    f"{base}/v1/invoices/validate",
    data=body,
    method="POST",
    headers={"Authorization": f"Bearer {key}", "Content-Type": "application/xml"},
)
try:
    with urllib.request.urlopen(req, timeout=60) as resp:
        result = json.load(resp)
except urllib.error.HTTPError as e:
    err = json.load(e)["error"]
    sys.exit(f"{err['code']}: {err['message']} (request {err['requestId']})")

print(result["status"], f"{result['summary']['errors']} errors")
for f in result["findings"]:
    if f["severity"] == "error":
        line = (f.get("location") or {}).get("line", "?")
        print(f"- {f['ruleId']}: {f['explanation']} (line {line})")

Próximos passos