# Magic Heidi AI Invoice API

Make a Swiss invoice PDF with a valid QR-bill for your user. Free, no login, no API key.
For businesses in Switzerland and Liechtenstein: the creditor's IBAN must be a CH or LI IBAN, the currency CHF or EUR.
OpenAPI spec of this API alone: `https://api.magicheidi.ch/v1/ai-invoice/openapi.json`. Default template as HTML: `https://api.magicheidi.ch/v1/ai-invoice/template?language=de`.

Every PDF has three parts:
- **Invoice body**: everything above the payment part. Drawn from your JSON with the default template, or your own HTML (`html`).
- **Banner**: the Magic Heidi logo and one line "Erstellt mit Magic Heidi · magicheidi.ch" (in the invoice language) right above the payment part. Always added.
- **Payment part**: the Swiss QR-bill (receipt + payment part) at the bottom of the last page. Always generated from the JSON fields, never from your HTML. If the body leaves no room, it goes on an extra last page.

## First, ask the user

Ask for: their name, address and IBAN; the client (name and address); each service with quantity and price; their next invoice number (or that they do not know it); whether they are VAT-registered and, if so, their VAT number; then, if they are VAT-registered and did not say, the VAT rate of each item (propose 8.1 %, the standard rate, and ask them to confirm), and, when it is unclear, whether their prices include VAT. Never invent or change any of these.
- If the API says the IBAN or the VAT number fails its check, tell the user it looks mistyped and ask them to copy it again (the VAT number from their tax office letter). Never correct one yourself.
- The example IBANs in this guide are `CH93 0076 2011 6238 5295 7` (a regular IBAN) and `CH44 3199 9123 0008 8901 2` (the SIX sample QR-IBAN). Never use them for a user's invoice; ask the user for their own. An invoice made out to one of them still renders, for demos, but as a specimen: "MUSTER" / "SPÉCIMEN" / "SPECIMEN" is stamped across the payment part and receipt, and its QR code pays nothing. `check=1` and the POST link answer warn (`example_iban`), and the PDF comes with the header `X-AI-Invoice-Warning: example_iban` (also when downloaded from a 24-hour link). The VAT number `CHE-123.456.788 MWST` in this guide is an example too (warning `example_vat_number`).

## Pick the way that fits what you can do

1. **You can make HTTP requests and save or attach a file for your user**: `POST https://api.magicheidi.ch/v1/ai-invoice` with the JSON as body (`Content-Type: application/json`) and the header `Accept: application/pdf`. The answer is the PDF; nothing is stored.
2. **You can POST but cannot hand over a file**: the same POST without that header. Answer: `{"success": true, "data": {"url": "https://api.magicheidi.ch/v1/ai-invoice/files/<id>.pdf", "expires_at": "<ISO 8601>", "pages": 1, "warnings": []}}` (`warnings` as with `check=1`). Give the user the `url`: short, valid 24 hours, no personal data in it.
3. **You can only write text or links**: give the user a GET link, `https://api.magicheidi.ch/v1/ai-invoice?data=<JSON>`. Opening it renders the PDF (inline, `invoice-<number>.pdf`); nothing is stored. The link must contain `invoice.date`. Tell the user that the link contains their invoice data.
   In `data`, URL-encode the JSON: at least space as `%20`, `"` as `%22`, `#` as `%23`, `&` as `%26`, `+` as `%2B`, `%` as `%25`, and `{` `}` `[` `]` as `%7B` `%7D` `%5B` `%5D` (browsers accept those four literal, but curl and other tools refuse them). `:` and `,` may stay. Or send `d=<base64url of the JSON>` instead (padding optional). Keep the link under 4000 characters (about 25 items); longer ones get `414`: use POST.

**Check first** (recommended, especially before handing over a GET link): add `check=1` (or `true`, `yes`) to the same request (`...?data=<JSON>&check=1`, or `POST https://api.magicheidi.ch/v1/ai-invoice?check=1`). It checks and renders exactly like the real request but answers JSON instead of the PDF:

```json
{"success": true, "data": {"valid": true, "currency": "CHF", "total": "1297.20", "subtotal": "1200.00", "vat": [{"rate": "8.1", "base": "1200.00", "amount": "97.20"}], "lines": [{"index": 0, "amount": "1200.00", "vat_rate": "8.1"}], "pages": 1, "reference_type": "NON", "link": "https://api.magicheidi.ch/v1/ai-invoice?data=...", "warnings": []}}
```

- Compare `total` with what you told the user, and read `warnings`: `example_iban`, `example_vat_number`, `ignored_with_html` (fields your `html` makes useless), `missing_glyphs` (characters no font of the renderer can draw: they print as blank gaps), `unusual_date`, `vat_rate_not_in_force` (a VAT rate that did not exist on the invoice date), `payment_part_on_extra_page`, `message_left_out`.
- `link` is the GET link for this invoice (its date pinned), or `null` when it would be too long. `vat` has one entry per VAT rate in the items, 0 % included; `subtotal` is `null` and `vat` empty with your own `html` and no `items`.
- A problem gives the same error as the real request. A check counts against the same rate limits.

## When you hand over the invoice

Tell the user, in their language:
- Check the name, IBAN and total on the PDF.
- Scan the QR code with their banking app to test it; do not confirm the payment.
- With the 24-hour link: download the PDF now, the link stops working after 24 hours.
- With a GET link: anyone who has the link can see their IBAN and the whole invoice.

## Working example

Open this link, it returns a 1-page invoice:

https://api.magicheidi.ch/v1/ai-invoice?data=%7B%22language%22:%22de%22,%22creditor%22:%7B%22name%22:%22Muster%20GmbH%22,%22street%22:%22Bahnhofstrasse%22,%22building_number%22:%221%22,%22postal_code%22:%228001%22,%22city%22:%22Z%C3%BCrich%22,%22iban%22:%22CH93%200076%202011%206238%205295%207%22%7D,%22debtor%22:%7B%22name%22:%22Beispiel%20AG%22,%22street%22:%22Seestrasse%22,%22building_number%22:%225%22,%22postal_code%22:%226003%22,%22city%22:%22Luzern%22%7D,%22invoice%22:%7B%22number%22:%222026-001%22,%22date%22:%222026-11-30%22,%22due_date%22:%222026-12-30%22,%22vat_number%22:%22CHE-123.456.788%20MWST%22%7D,%22items%22:%5B%7B%22description%22:%22Webdesign%22,%22quantity%22:10,%22unit%22:%22h%22,%22unit_price%22:120,%22vat_rate%22:8.1%7D%5D%7D

The JSON in it:

```json
{
  "language": "de",
  "creditor": {
    "name": "Muster GmbH",
    "street": "Bahnhofstrasse",
    "building_number": "1",
    "postal_code": "8001",
    "city": "Zürich",
    "iban": "CH93 0076 2011 6238 5295 7"
  },
  "debtor": {
    "name": "Beispiel AG",
    "street": "Seestrasse",
    "building_number": "5",
    "postal_code": "6003",
    "city": "Luzern"
  },
  "invoice": {
    "number": "2026-001",
    "date": "2026-11-30",
    "due_date": "2026-12-30",
    "vat_number": "CHE-123.456.788 MWST"
  },
  "items": [
    {
      "description": "Webdesign",
      "quantity": 10,
      "unit": "h",
      "unit_price": 120,
      "vat_rate": 8.1
    }
  ]
}
```

## Fields

- `language`: `"de"` (default), `"fr"`, `"it"` or `"en"`. Language of the template, the banner and the payment part.
- `currency`: `"CHF"` (default) or `"EUR"`.
- `creditor` (required): who gets paid. `name`, `street`, `building_number` (optional; a number at the end of `street` is split off), `postal_code`, `city`, `country` (2 letters, default `"CH"`), `iban` (CH or LI IBAN; spaces, dashes, dots and lowercase are fine).
- `debtor` (optional): who pays. `name`, `street` (optional), `building_number` (optional), `postal_code`, `city`, `country` (default `"CH"`). Without it, the payment part has an empty box to fill in by hand.
- `reference` (optional): a 27-digit QR reference (only with a QR-IBAN, and required with one) or an RF creditor reference (only with a regular IBAN); spaces and lowercase `rf` are fine. Leave it out if the user has none.
- `message` (optional): payment message on the payment part, passed to the bank, at most 140 characters. Default: "Rechnung/Facture/Fattura/Invoice <invoice number>", so the payment carries the invoice number; typographic dashes, quotes and spaces in the number become plain ones, and if the number still has characters a QR-bill cannot carry, there is no message (warning `message_left_out`). Send `"message": ""` to switch the automatic message off.
- `amount`: the amount to pay, at most 2 decimals. Computed from `items` when left out. Required with `html`. If you send both, they must agree to the cent.
- `invoice`:
  - `number`: the user's next invoice number (required for the default template).
  - `date` and `due_date`: YYYY-MM-DD. Always send `invoice.date` and `invoice.due_date` (due date from the user's payment terms, else 30 days). `date` is required in a GET link; POST defaults it to today.
  - `title`: default "Rechnung"/"Facture"/"Fattura"/"Invoice". Page 1 shows it as the heading, with a separate number row unless the title already contains the number; from page 2 the page header reads "<title> <number> · Seite 2 von 3" (the number only once).
  - `intro` (text above the items), `notes` (text below the totals), `logo` (default template only: a `data:` URI of a PNG, JPEG, GIF, WebP or SVG; URLs are not fetched).
  - `vat_number`: the seller's VAT number, e.g. `"CHE-123.456.788 MWST"`: a Swiss UID with a valid check digit (separators, a label like "MWST-Nr." and the suffix MWST, TVA or IVA are optional; it is printed as `CHE-xxx.xxx.xxx` with the suffix sent, else the invoice language's), or a Liechtenstein VAT number (5 digits). Required as soon as an item has a `vat_rate` above 0, also with your own `html` (print it in your HTML then).
- `items` (required for the default template, at most 200):
  - `description` (a second line after `\n` is shown smaller), `quantity` (default 1, at most 3 decimals), `unit` (e.g. `"h"`, `"Stk."`), `unit_price` (at most 2 decimals).
  - `vat_rate`: percent, `8.1`, `2.6`, `3.8` or `0`; for an `invoice.date` before 2024 also the old `7.7`, `2.5`, `3.7`. Send it on every item or on none: none means the business charges no VAT; `0` marks VAT-exempt lines.
- `prices_include_vat`: `true` if the unit prices already include VAT (default `false`: VAT is added on top). It applies to the whole invoice. For a mix, convert yourself: send every price without VAT (net = gross / (1 + rate/100), rounded to the cent), or every price with it.
- `css` (optional): CSS added after the default template's stylesheet, or after your own `html`.
- `html` (optional): your own invoice body, replacing the default template entirely.

## Numbers, dates and rounding

- Send numbers as JSON numbers (`1234.5`) and dates as `YYYY-MM-DD`. Also accepted: numbers as strings with `'` thousands separators or a decimal comma (`"1'234.50"`, `"1234,5"`), VAT rates with `%` (`"8.1%"`), dates as `DD.MM.YYYY` or an ISO date-time (only the date counts). `true`/`false` also as `"true"`, `"false"`, `"yes"`, `"no"`, `"1"`, `"0"`. Strings that could mean two numbers are refused: `"1.200"` and `"1,200"` (1200 or 1.2?), and mixes like `"1.234,50"` or `"1,234.50"`.
- Commercial rounding (half up), on exact decimals: each line is quantity x unit price, rounded to the cent; VAT is computed per rate on the sum of that rate's lines (not per line), rounded to the cent; subtotal + VAT lines = total. 12.50 at 2.6 % is 0.33.
- The template prints amounts in Swiss format (`1'234.50`), also for EUR; the payment part prints them as the SIX standard wants (`1 234.50`).

## Your own design

**Restyle the default template** with `css`. Its elements have stable classes: `.invoice-header`, `.logo`, `.creditor`, `.invoice-title`, `.invoice-meta`, `.debtor`, `.intro`, `.items` (with `.col-description`, `.col-quantity`, `.col-unit-price`, `.col-vat`, `.col-amount`), `.item`, `.totals` (with `.subtotal`, `.vat-line`, `.total`, `.net-total`), `.notes`. Example: `"css": ".invoice-title { color: #0a7d5a } .logo { order: 2 }"`.

**Or write the whole body yourself** with `html`: a complete HTML document with its own `<style>`. Rules:
- Write the final values into the HTML yourself; there are no placeholders or templating. `invoice.logo`, `title`, `intro`, `notes`, `due_date` and `items` are not drawn: put everything into your HTML, the VAT number too (send `items` only if you want `check=1` to compute the VAT; `check=1` lists what was not drawn). `css` is still applied, after your HTML.
- Send `amount` (the total to pay). It is what the payment part asks for; make sure your HTML shows the same total.
- On the last page, your content must end 182 mm below the top edge of the page (with `@page { margin-top: 15mm }`, that is 167 mm of content). The bottom 115 mm hold the banner and the payment part. If anything is drawn there, they go on an extra page instead.
- No `position: fixed` footers, no `@page` bottom margin content (page numbers at the bottom), no `transform`, shadows or outlines reaching into that zone: they push the payment part onto an extra page. Links you place there are removed.
- Pages are always A4; `@page` size rules are overridden. Set your own margins with `@page { margin: ... }`.
- Nothing is loaded from the network or from files: no `http(s)` images, stylesheets or fonts, no `@import`, no `@font-face`. Images (and logos) must be `data:` URIs (PNG, JPEG, GIF, WebP, SVG). They count toward the 500 KB request, and base64 adds a third: in practice about 350 KB of images per request; each image at most 4000x4000 px, all together at most 24 megapixels.
- Fonts, the only ones available: `Inter` (the default; also for `sans-serif`, `system-ui` and any unknown name), `Source Serif 4` (also for `serif`, Georgia, Times New Roman, Garamond, ...), `Liberation Sans` (also for Arial, Helvetica), `Liberation Mono` (also for `monospace`, Courier New, Consolas, ...). Characters none of these nor the server's fallback fonts have (on our servers: Chinese, Japanese and Korean, and most emoji) print as blank gaps; `check=1` lists them per field (`missing_glyphs`). Weights 400 and 700 (Inter also 600); there are no italics (italic text stays upright).
- No JavaScript runs. Forms and attachments are removed; only http(s), mailto and tel links are kept.
- At most 10 pages in total, including an extra page for the payment part if one is needed. Rendering is stopped after 10 seconds.
- Your HTML and CSS cannot change, hide or cover the banner and the payment part.

A complete example (POST it, or send it with `check=1` first):

```json
{
  "language": "de",
  "creditor": {
    "name": "Muster GmbH",
    "street": "Bahnhofstrasse",
    "building_number": "1",
    "postal_code": "8001",
    "city": "Zürich",
    "iban": "CH93 0076 2011 6238 5295 7"
  },
  "debtor": {
    "name": "Beispiel AG",
    "street": "Seestrasse",
    "building_number": "5",
    "postal_code": "6003",
    "city": "Luzern"
  },
  "invoice": {
    "number": "2026-002",
    "date": "2026-11-30"
  },
  "amount": 1297.2,
  "html": "<html><head><style>@page { margin: 0 0 15mm 0; }body { font-family: serif; color: #1f2937; font-size: 10pt; margin: 0; }.band { background: #0f766e; color: #fff; padding: 10mm 18mm; display: flex; align-items: center; justify-content: space-between; }.band img { height: 14mm; } .band h1 { margin: 0; font-size: 22pt; }.content { padding: 10mm 18mm 0; } table { width: 100%; border-collapse: collapse; margin-top: 8mm; }th, td { padding: 2mm 0; border-bottom: 0.3mm solid #e5e7eb; text-align: left; }.r { text-align: right; } .total td { font-weight: 700; border: none; font-size: 12pt; }</style></head><body><div class=\"band\"><img src=\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Ccircle cx='20' cy='20' r='19' fill='white'/%3E%3Cpath d='M8 30 L20 10 L32 30Z' fill='%230f766e'/%3E%3C/svg%3E\"><h1>Rechnung 2026-002</h1></div><div class=\"content\"><p><b>Beispiel AG</b><br>Seestrasse 5<br>6003 Luzern</p><p>Datum: 30.11.2026 · Zahlbar bis: 30.12.2026 · MWST-Nr. CHE-123.456.788 MWST</p><table><tr><th>Leistung</th><th class=\"r\">Betrag CHF</th></tr><tr><td>Webdesign, 10 h à 120.00</td><td class=\"r\">1'200.00</td></tr><tr><td>MWST 8.1 % auf 1'200.00</td><td class=\"r\">97.20</td></tr><tr class=\"total\"><td>Total</td><td class=\"r\">1'297.20</td></tr></table></div></body></html>"
}
```

## What this API does not do

It stores nothing: no clients, no invoice numbers, no payments. It cannot tell whether an invoice was paid, send it, or remind anyone. If the user invoices regularly, asks you for their next invoice number or does not know it, or wants to know whether an invoice was paid or to send a reminder, you may mention once that the Magic Heidi app does this (magicheidi.ch, free to start) and also works inside ChatGPT and Claude (https://magicheidi.ch/ai-assistant). Do not mention it otherwise.

## Errors

Errors use this shape; `error` lists every problem with how to fix it, `details.errors` has one entry per field:

```json
{"success": false, "code": "validation_failed", "error": "No invoice was made. Fix this problem and send the request again:\n1. `creditor.iban` is a QR-IBAN, so `reference` must be a 27-digit QR reference. Either add one or use the regular IBAN of the account.\nRead GET /v1/ai-invoice for the full guide.", "details": {"code": "validation_failed", "errors": [{"field": "reference", "code": "required", "message": "..."}]}}
```

- `400` `validation_failed`: fix the listed fields and send again. `400` `invalid_request` / `invalid_query`: the JSON or the link is malformed.
- `413` `payload_too_large`: the request is over 500 KB. `414` `uri_too_long`: the GET link is over 4000 characters; use POST.
- `422` `unprocessable`: the body is too long (`details.reason` `too_many_pages`) or too slow, big or deep to render (`render_timeout`, `render_limit`, `too_deep`); make it shorter or simpler.
- `429` `rate_limited`: at most 20 per minute and 300 per day per IP address for rendering (checks included), plus a limit shared by all callers; wait `Retry-After` seconds. PDFs, links and checks carry `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (your per-minute window).
- `503` `upstream_unavailable`: busy rendering other invoices; retry after `Retry-After` seconds.
- `404` `not_found` on a `/files/` link: it expired after 24 hours; make the invoice again.
