Criar faturas a partir de JSON
POST /v1/invoices/generate?target=… cria uma fatura eletrónica a partir dos seus próprios dados. Envie a fatura em JSON no modelo canónico EN 16931 — a mesma estrutura que POST /v1/invoices/parse devolve, publicada como components.schemas.Invoice no documento OpenAPI.
target |
Resultado |
|---|---|
xrechnung-ubl, xrechnung-cii |
XRechnung 3.0 |
en16931-ubl, en16931-cii |
EN 16931 core |
peppol-bis-billing |
Peppol BIS Billing 3.0 (UBL) |
zugferd-facturx |
ZUGFeRD / Factur-X PDF/A-3b, perfil EN 16931 (predefinição) ou XRECHNUNG via profile= |
generate.ts
// Create an XRechnung from your own invoice data (Node 20+). The JSON follows the canonical
// EN 16931 model; here it is built from minimal fields. Missing data is reported, never invented.
import { writeFile } from "node:fs/promises";
const invoice = {
documentKind: "invoice",
id: "RE-2026-0042",
issueDate: "2026-11-22",
typeCode: "380",
currency: "EUR",
dueDate: "2026-12-22",
buyerReference: "04011000-12345-34", // Leitweg-ID of the public buyer
seller: {
name: "Muster Software GmbH",
vatId: "DE123456789",
electronicAddress: { value: "[email protected]", scheme: "EM" },
address: { line1: "Hauptstraße 1", city: "Berlin", postcode: "10115", countryCode: "DE" },
contact: { name: "Buchhaltung", phone: "+49 30 1234567", email: "[email protected]" },
},
buyer: {
name: "Stadtverwaltung Musterstadt",
electronicAddress: { value: "[email protected]", scheme: "EM" },
address: { line1: "Rathausplatz 1", city: "Musterstadt", postcode: "12345", countryCode: "DE" },
},
payment: { meansCode: "58", creditTransfers: [{ accountId: "DE02120300000000202051" }] },
paymentTerms: "Zahlbar innerhalb 30 Tagen ohne Abzug.",
totals: { lineNet: "1000.00", taxExclusive: "1000.00", tax: "190.00", taxInclusive: "1190.00", payable: "1190.00" },
vatBreakdown: [{ taxableAmount: "1000.00", taxAmount: "190.00", category: "S", rate: "19" }],
lines: [
{
id: "1",
quantity: "10",
unitCode: "HUR",
netAmount: "1000.00",
price: { net: "100.00" },
vat: { category: "S", rate: "19" },
item: { name: "Softwareentwicklung" },
},
],
};
const res = await fetch(`${process.env.EINV_BASE}/v1/invoices/generate?target=${process.argv[2] ?? "xrechnung-ubl"}&store=false`, {
method: "POST",
headers: { authorization: `Bearer ${process.env.EINV_KEY}`, "content-type": "application/json" },
body: JSON.stringify({ invoice }),
});
const body = await res.json();
if (!res.ok) {
console.log(body.error.code, body.error.message);
// generated_document_invalid: each finding names the JSON fields to fill
for (const f of body.error.details?.findings ?? []) console.log(f.ruleId, f.fields?.join(", "), f.message);
// invalid_invoice_data: the JSON does not match the model
for (const i of body.error.details?.issues ?? []) console.log(i.path, i.message);
process.exit(1);
}
const file = body.target.encoding === "base64" ? "invoice.pdf" : "invoice-generated.xml";
await writeFile(file, body.target.encoding === "base64" ? Buffer.from(body.document, "base64") : body.document);
console.log(body.validation.status, body.target.format, file);
O que o serviço define, e o que nunca faz
specificationId(BT-24) segue o destino; um valor no seu JSON é substituído.businessProcess(BT-23) assume por predefinição o processo de faturação Peppol para XRechnung e Peppol quando não envia nenhum; a resposta indica-o emwarningscomderived: true.- Nada mais é preenchido. Uma Leitweg-ID, morada ou taxa de IVA em falta continua em falta e a chamada falha.
Quando os dados não são suficientes
O documento é validado com as regras oficiais do destino antes de ser devolvido. Se não passar, recebe 422 generated_document_invalid; cada resultado tem fields, os caminhos JSON envolvidos — por exemplo BR-DE-15 → buyerReference. Se o próprio JSON não corresponder ao modelo, recebe 422 invalid_invoice_data com issues[].path.
Via MCP, a mesma função é a ferramenta create_invoice: um agente pode criar o documento, ler fields, pedir ao utilizador os dados em falta e tentar novamente.
Faturação e armazenamento
Cada documento criado conta como um documento, tal como uma validação ou conversão. Com store=true (ou a predefinição da sua organização), o documento criado é mantido no histórico de faturas durante o período de retenção do seu plano.
Fixar o conjunto de regras
Todos os endpoints de documentos aceitam rules=<version> (consulte validation.ruleset.version, atualmente 2026-11). Um pedido para um conjunto de regras que não está disponível é recusado com 422 unsupported_rules_version em vez de ser verificado com outras regras.
E-Invoicing API