Building a Stripe webhook that outputs EN 16931 XML yourself: what it takes
By evoicely · Last checked 20 October 2026
Listen for invoice.finalized and credit_note.created, verify the signature, store the event ID and answer 200 straight away. Then, in a background job, fetch the invoice again with the expands you need, map it to EN 16931, and refuse to issue anything whose totals don't match Stripe's to the cent.
Write UBL or CII for the format your buyer needs (XRechnung, ZUGFeRD, Peppol BIS), check every file with the official rules (KoSIT's XRechnung configuration and the Peppol schematrons), and keep those rules up to date. After that come delivery and archiving.
The webhook is the easy part. Most of the work is in the mapping and the checks, and that work never really stops. This page goes through each part, with the Stripe API details that matter and the places where things break in practice.
Stripe details are from the webhooks guide, the Invoice, Invoice Line Item and Credit Note objects, and the API version 2025-03-31.basil changelog.
Business terms (BT-xx) and rules (BR-xx) come from EN 16931. If those codes are new to you, start with What is EN 16931?
The moving parts
- A webhook endpoint that verifies, deduplicates and queues events.
- A worker that fetches the full invoice or credit note from the Stripe API, as the right account and with a pinned API version.
- The seller details Stripe doesn't have: your address, contact, IBAN, and often your VAT ID.
- A mapper from Stripe's objects to the EN 16931 model: amounts, dates, lines, VAT categories, totals.
- Writers for each syntax you need: UBL, CII, and for ZUGFeRD a PDF/A-3 with the XML embedded.
- Validation of every file against the official rules, and a way to update those rules.
- Delivery: email, or a Peppol access point.
- An archive, and a status page or alert for documents that couldn't be converted.
Which events: invoice.finalized, not invoice.paid
A Stripe invoice starts as a draft, and you can only edit it while it is one. Finalizing it moves it to open, assigns the invoice number and sends invoice.finalized.
After that, Stripe lets you change very little: amounts and customer fields are locked. The customer's name, email, address, tax_exempt status and tax IDs are copied onto the invoice (customer_name, customer_address, customer_tax_ids and so on) and don't change again.
To change the amount you issue a credit note; to change the customer you void the invoice and create a new one
(Stripe: status transitions and finalization).
So finalization is when the invoice exists as issued, and that's what the e-invoice has to show.
invoice.paid is the wrong trigger for three reasons:
- Invoices sent for manual payment (
collection_method: send_invoice) need the e-invoice to ask for payment. If you wait until they're paid, the customer never gets it. - Some invoices are never paid, or only after reminders. They still have to be issued.
- Payment comes later than issue, so the e-invoice would carry a different moment than the invoice it represents.
Payment still affects the content. A card-charged subscription invoice may already be paid when you fetch it, or still be waiting for its payment attempt. The paid amount (BT-113) and the amount due (BT-115) depend on which, so decide what your e-invoice says in both cases.
For corrections, listen for credit_note.created. A Stripe credit note has no draft state: its status is either issued or void. Each one becomes an EN 16931 credit note (type code 381) that refers to its invoice. Stripe credit notes as e-invoices covers the mapping and the German rules on corrections.
Also decide what happens when someone voids an invoice in Stripe after you've sent the e-invoice (invoice.voided). The e-invoice is already out there; usually the fix is a credit note, but that's a question for your accountant, not your code.
Checkout and Payment Link sales without a Stripe invoice never send invoice.finalized. They need a different approach, described in E-invoices for Stripe Checkout and Payment Links payments.
The endpoint: signatures, duplicates, order
Stripe signs every delivery with the Stripe-Signature header: a timestamp t and one or more v1 signatures, each an HMAC-SHA256 of "{t}.{raw body}" with your endpoint's signing secret.
Verify it against the raw request body, because a framework that parses and re-serialises the JSON breaks the check. Compare in constant time, and reject old timestamps: Stripe's libraries allow 5 minutes by default.
Stripe also recommends answering with a 2xx quickly, before any slow work, and processing events from a queue
(Stripe: verify events, best practices).
Three delivery properties shape the design:
- Retries. If your endpoint doesn't answer with a 2xx, Stripe retries for up to three days in live mode, with exponential backoff. In a sandbox it retries three times over a few hours.
- Duplicates. The same event can arrive more than once. Store event IDs and skip ones you've seen. Stripe notes that occasionally two separate Event objects are created for the same change, so also key your output on the object: one invoice ID gives one e-invoice, however many events mention it.
- Order. Stripe doesn't guarantee that events arrive in the order they were created, and an event's
createdis in whole seconds, so don't use it for ordering. Whenever you need the current state, fetch the object from the API.
Generating an e-invoice involves several API calls and a validator run, which is too slow for the request itself. A minimal handler, in Python-like pseudocode:
@app.post("/stripe/webhook")
def stripe_webhook(request):
body = request.raw_body() # the exact bytes Stripe sent
if not signature_ok(body, request.headers["Stripe-Signature"], SECRET):
return 400
event = json.loads(body)
# INSERT ... ON CONFLICT (id) DO NOTHING: a redelivery is a no-op
queue.insert_once(event["id"], event)
return 200 # convert later, in a worker
def worker(event):
if event["type"] not in ("invoice.finalized", "credit_note.created"):
return done(event)
obj_id = event["data"]["object"]["id"]
if already_converted(obj_id): # second event, same invoice
return done(event)
try:
doc = fetch_fresh(obj_id, account=event.get("account"))
except StripeUnavailable: # 429, 5xx, timeouts
return retry_later(event) # with backoff
...
Retry what is temporary: timeouts, 429 rate limits and 5xx responses. Don't retry forever on things that won't fix themselves, such as a 404, or an invoice your mapper can't convert. Record those with a reason someone can act on.
Fetch the invoice again, with the right expands
Don't build the e-invoice from the event payload. Stripe never expands properties in webhook events, so you won't find the customer's metadata or the tax rate percentages there, and the snapshot may already be out of date (Stripe: expanding responses). Retrieve the invoice instead:
curl -G https://api.stripe.com/v1/invoices/in_1Example \
-u "$STRIPE_SECRET_KEY:" \
-H "Stripe-Version: 2025-03-31.basil" \
-d "expand[]=customer" \
-d "expand[]=account_tax_ids" \
-d "expand[]=lines.data.discount_amounts.discount"
customergives you the Customer'smetadata. Stripe doesn't copy metadata between objects, so if you keep a buyer reference or Leitweg-ID on the customer, this is the only way to read it.account_tax_idsis an array of Tax ID object IDs; expanded, it givestypeandvalue. It can be null, so have another source for your own VAT ID. VAT IDs, reverse charge and Stripe tax IDs goes into detail.lines.data.discount_amounts.discountgives each discount's coupon, whose name can become the allowance reason text.
Pin the API version on every request with the Stripe-Version header, so the objects keep the shape your mapper expects. Webhook payloads use the API version of the webhook endpoint, which you upgrade separately
(Stripe: webhook versioning).
Stripe ships breaking changes twice a year, and the 2025-03-31.basil release changed exactly the invoice fields an e-invoice needs:
| Before basil | Since 2025-03-31.basil |
|---|---|
line.tax_rates, line.tax_amounts | line.taxes[]: amount, taxable_amount, tax_behavior, taxability_reason, tax_rate_details.tax_rate |
invoice.tax, invoice.total_tax_amounts | invoice.total_taxes[] |
invoice.subscription, invoice.subscription_details | invoice.parent.subscription_details (check parent.type) |
line.price, line.unit_amount_excluding_tax | line.pricing.unit_amount_decimal |
invoice.paid, invoice.payment_intent | invoice.payments (expandable), amount_paid, amount_remaining |
Sources: Stripe changelog entries for
tax fields,
the parent field,
pricing and
partial payments.
Subscription metadata now sits in parent.subscription_details.metadata, a snapshot taken when the invoice was created.
Two more fetches catch people out:
- Tax rate percentages.
taxes[].tax_rate_details.tax_rateis a Tax Rate ID. From the invoice,lines.data.taxes.tax_rate_details.tax_rateis five levels deep, and Stripe allows at most four, so you can't expand it there. Collect the distinct Tax Rate IDs from the lines and retrieve each one. You need itspercentageand itstax_type, so you don't write a US sales tax into a VAT field. - All the lines.
linesis a paginated list. Ifhas_moreis true, page through/v1/invoices/{id}/lineswithstarting_after. An e-invoice that's missing lines won't match the totals, or worse, will match only by accident.
A credit note's invoice field is the invoice ID. Fetch that invoice too: you need its number and issue date for the reference (BT-25, BT-26) and its customer details for the buyer.
Several Stripe accounts: Connect
If your generator serves more than one Stripe account, for example as a Connect platform, register the endpoint for events from connected accounts.
Each event then has a top-level account property, and because the connected account owns the invoice, you fetch it as that account: send its ID in the Stripe-Account header with your platform key.
Production Connect endpoints receive both live and test events, so check livemode before you issue anything, and don't let a test invoice reach a real customer
(Stripe: Connect webhooks, making API calls for connected accounts).
Handle account.application.deauthorized as well: once an account disconnects, you can no longer fetch its invoices.
The mapping
Field by field, this is covered in Mapping a Stripe invoice to EN 16931, so here is just where the effort goes:
- Data Stripe doesn't have. Your street address, a seller contact with phone and email (required by XRechnung), and your IBAN for transfers. Keep them in your own configuration, per account if you serve several.
- Buyer reference (BT-10). XRechnung requires it (BR-DE-15). Decide where it lives in Stripe (invoice, subscription or customer metadata) and in which order you look.
- Dates. Timestamps are Unix seconds; convert them in the time zone you invoice in. Use
effective_atfor the issue date (BT-2), and the line periods for the invoicing period. - Tax-inclusive prices. EN 16931 line amounts and prices are net. With
tax_behavior: "inclusive", the net line amount is the tax entry'staxable_amount, and the unit price has to be restated without VAT. - Discounts and credits. Stripe spreads invoice-level coupons over the lines in
discount_amounts, and since basil also lists credit grants inpretax_credit_amounts, where discounts appear a second time withtype: "discount". Count each reduction once. - Unsupported cases. Several taxes on one line, non-VAT taxes, credit notes for a plain amount without lines (Stripe records no VAT on those). Stop and report them; don't guess.
Minor units, rounding and the sum rules
Stripe amounts are integers in the smallest currency unit: 4900 is €49.00. EN 16931 amounts are decimals with at most two places. Divide using the currency's exponent, not always by 100: Stripe has zero-decimal currencies such as JPY, and a few three-decimal ones
(Stripe: supported currencies). Use a decimal type throughout; floats will cost you a cent somewhere.
The totals are then checked against each other by these EN 16931 rules (rule texts from the CEN validation artefacts, version 1.3.16):
- BR-CO-10: Sum of Invoice line net amount (BT-106) = Σ Invoice line net amount (BT-131).
- BR-CO-11 / BR-CO-12: the sums of document-level allowances (BT-107) and charges (BT-108) equal their individual amounts.
- BR-CO-13: Invoice total amount without VAT (BT-109) = Σ BT-131 − BT-107 + BT-108.
- BR-CO-14: Invoice total VAT amount (BT-110) = Σ VAT category tax amount (BT-117).
- BR-CO-15: Invoice total amount with VAT (BT-112) = BT-109 + BT-110.
- BR-CO-16: Amount due for payment (BT-115) = BT-112 − Paid amount (BT-113) + Rounding amount (BT-114).
These hold to the cent. The per-category VAT check is different: BR-CO-17 says BT-117 = BT-116 × rate ÷ 100, rounded to two decimals, but the current rules accept a difference of less than one currency unit.
That matters because Stripe rounds VAT per line, and its total per rate can differ by a cent or two from the per-category calculation.
The safest approach is to keep the VAT Stripe actually charged, then compare your BT-110, BT-112 and BT-115 with Stripe's total_taxes, total and amount_remaining. If they differ, don't issue the file: an e-invoice that disagrees with what the customer was charged is worse than none.
Don't copy amount_due into BT-115 either: it can include the customer's balance, which isn't part of this invoice.
Here is the result for a fictional paid subscription invoice with two lines, a €49.00 plan and 3 × €9.99 extra seats, both at 19%. Stripe charged VAT per line (931 and 569 cents), which adds up to total_taxes[0].amount 1500, and amount_remaining is 0.
This is an excerpt of the XRechnung (UBL) file generated from that invoice by the same code evoicely uses. The complete file passes the XML schema, the EN 16931 rules 1.3.16 and the XRechnung 3.0.2 rules; the <!-- --> comments were added for this page.
<cac:TaxTotal>
<cbc:TaxAmount currencyID="EUR">15.00</cbc:TaxAmount> <!-- BT-110: total_taxes, 1500 -->
<cac:TaxSubtotal>
<cbc:TaxableAmount currencyID="EUR">78.97</cbc:TaxableAmount> <!-- BT-116 -->
<cbc:TaxAmount currencyID="EUR">15.00</cbc:TaxAmount> <!-- BT-117: 931 + 569 -->
<cac:TaxCategory>
<cbc:ID>S</cbc:ID>
<cbc:Percent>19</cbc:Percent>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:TaxCategory>
</cac:TaxSubtotal>
</cac:TaxTotal>
<cac:LegalMonetaryTotal>
<cbc:LineExtensionAmount currencyID="EUR">78.97</cbc:LineExtensionAmount> <!-- BT-106 = 49.00 + 29.97 -->
<cbc:TaxExclusiveAmount currencyID="EUR">78.97</cbc:TaxExclusiveAmount> <!-- BT-109 -->
<cbc:TaxInclusiveAmount currencyID="EUR">93.97</cbc:TaxInclusiveAmount> <!-- BT-112: total, 9397 -->
<cbc:PrepaidAmount currencyID="EUR">93.97</cbc:PrepaidAmount> <!-- BT-113: total - amount_remaining -->
<cbc:PayableAmount currencyID="EUR">0.00</cbc:PayableAmount> <!-- BT-115 -->
</cac:LegalMonetaryTotal>
<cac:InvoiceLine>
<cbc:ID>2</cbc:ID>
<cbc:InvoicedQuantity unitCode="C62">3</cbc:InvoicedQuantity> <!-- quantity_decimal -->
<cbc:LineExtensionAmount currencyID="EUR">29.97</cbc:LineExtensionAmount> <!-- BT-131: amount, 2997 -->
...
<cac:Price>
<cbc:PriceAmount currencyID="EUR">9.99</cbc:PriceAmount> <!-- BT-146: 29.97 / 3 -->
</cac:Price>
</cac:InvoiceLine>
The amount due is 0.00 because the card was already charged, so the payment means is code 1 rather than a credit transfer with an IBAN. The same data as CII, for ZUGFeRD, passes the EN 16931 rules too.
VAT categories
Every line and every VAT breakdown needs a category code: S, AE (reverse charge), Z, E and others, each with its own rules. Stripe's taxability_reason is a hint, not a category code.
For example, not_collecting has a tax amount of 0 but only means Stripe Tax has no registration for that location; it doesn't tell you which VAT treatment applies. Map only the cases that are unambiguous, and stop on the others.
The mapping and the rules are in VAT IDs, reverse charge and Stripe tax IDs in e-invoices.
Choosing the syntax and the CIUS
EN 16931 is one data model with two XML syntaxes, UBL 2.1 and UN/CEFACT CII. A CIUS adds rules and a specification identifier (BT-24) on top. Which one you write depends on the buyer:
| Format | Syntax | Specification identifier (BT-24) |
|---|---|---|
| XRechnung 3.0 (Germany) | UBL or CII | urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0 |
| ZUGFeRD / Factur-X, EN 16931 profile | CII, inside a PDF/A-3 | urn:cen.eu:en16931:2017 |
| Peppol BIS Billing 3.0 | UBL | urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0 |
If you build your own mapper, build one internal EN 16931 model and write each syntax from it, rather than mapping Stripe to XML separately for each one.
UBL also has a separate CreditNote document, so credit notes need their own writer path.
Background: XRechnung vs ZUGFeRD, ZUGFeRD profiles (MINIMUM and BASIC WL don't count as e-invoices in Germany).
ZUGFeRD is more than XML. The CII has to be embedded in a PDF/A-3 as factur-x.xml, with the right associated-file relationship and XMP metadata, and most PDF libraries don't do that out of the box. See ZUGFeRD and PDF/A-3: embedding the XML correctly.
Validate every file, and keep the rules current
A file that looks right isn't necessarily valid. Run every output through the official rules before it leaves your system, and treat a failure as a bug: don't send the file.
- XRechnung. KoSIT publishes the validator (Java) and the XRechnung validator configuration, which bundles the XML schemas, the EN 16931 rules and the XRechnung Schematron. The validator has a daemon mode for services. Alternatively, run the configuration's compiled XSLT in-process with an XSLT 2.0 processor such as Saxon. How to validate an XRechnung shows the commands.
- Peppol BIS Billing 3.0. OpenPeppol publishes the rules as Schematron files with each BIS release: the EN 16931 rules plus the PEPPOL-* rules. Your access point runs the same checks and won't deliver a file that fails. See How to validate a Peppol BIS 3.0 invoice.
- ZUGFeRD. Validate the embedded CII against the EN 16931 rules, and the PDF/A part with veraPDF or Mustang.
The rules change, so validation is an ongoing job rather than something you set up once:
- OpenPeppol publishes a BIS release each May and November, each mandatory about three months later (release notes). Release 3.0.21 has been mandatory since 17 August 2026.
- KoSIT ships bugfix configurations for XRechnung 3.0 (the current one is from 31 August 2026), and XRechnung 4.0 is in preparation: a preliminary version was published in September 2026, with the final version expected in spring 2027 (XRechnung versions and bundles).
Pin the rule versions in your build, record which versions checked each file, and put the release dates in a calendar. Keep a set of fictional Stripe invoices as test fixtures (reverse charge, discounts, tax-inclusive prices, credit notes) and run them through the validators on every change. For a quick manual check, our free validator runs the same official rules on a file you upload, without storing it. When an XRechnung fails, Common XRechnung validation errors lists the usual causes. For Peppol, see Common Peppol BIS validation errors.
Delivery and archiving
Delivery. In Germany, email is fine for B2B: no special network is required, and an email inbox is enough for the buyer to receive (see Germany's e-invoicing mandate). Public-sector buyers use their own portals. Belgium's mandate runs over Peppol, which means a contract with a certified access point, Peppol participant IDs for you and your buyers, and handling the access point's responses (see Belgium's Peppol mandate for Stripe users). Stripe also emails its own PDF for invoices sent for manual payment, unless you switch that off. That PDF alone isn't an e-invoice, so decide whether customers get both.
Archiving. Keep every file exactly as you issued it. For Germany, § 14b UStG requires you to keep a copy of each invoice you issue for eight years, and for an e-invoice that means the XML in its original form; the GoBD, the German rules for electronic records, also apply (§ 14b UStG). Ask your tax advisor how this fits your bookkeeping. Store the validation report next to each file, so that you can later show which rules it passed.
Checklist
- A webhook endpoint for
invoice.finalizedandcredit_note.created(plusaccount.application.deauthorizedwith Connect), with signature check on the raw body, a timestamp tolerance, and a quick 2xx. - An event store with a unique event ID, an output keyed on the invoice or credit note ID, and a worker with backoff for 429 and 5xx responses.
- Fresh fetches with a pinned
Stripe-Version, the expands above, all line pages, the tax rates, andStripe-Accountfor connected accounts. Alivemodecheck. - Seller configuration for what Stripe doesn't store: address, contact, VAT ID, IBAN, and where the buyer reference comes from.
- A mapper with decimal arithmetic, currency exponents, time zones, net prices, line-level discounts and credits, and explicit VAT categories. A reason, readable by a human, for every case it refuses.
- A totals check against Stripe's
total_taxes,totalandamount_remainingbefore anything is issued. - Writers for UBL Invoice and CreditNote, CII, and a PDF/A-3 with the embedded XML if you send ZUGFeRD.
- Validation of every file with KoSIT's XRechnung configuration and the Peppol schematrons, pinned versions, and a calendar for the May and November Peppol releases and for XRechnung 4.0.
- Delivery by email or a Peppol access point, with retries and a fallback.
- An archive of the original files and their validation reports, and a list of failed documents that someone actually reads.
Related guides
- Mapping a Stripe invoice to EN 16931, field by field: every field, and the gaps.
- VAT IDs, reverse charge and Stripe tax IDs in e-invoices: BT-31, BT-48 and the VAT categories.
- Stripe credit notes as e-invoices: type code 381 and the reference to the invoice.
- What is a Leitweg-ID: the buyer reference German public authorities need.
- Does Stripe support e-invoicing?: what Stripe does itself.
- What is EN 16931?: the data model behind the BT and BR codes.
Where evoicely fits
If you'd rather not build and maintain this, evoicely is the pipeline above as a service. You connect your Stripe account with Stripe Connect and enter your business details once. Each finalized invoice and each credit note is then converted to XRechnung and ZUGFeRD (EN 16931), checked with the official rules, and rejected with a reason if it can't be converted faithfully or doesn't match Stripe's totals. Belgian sellers can also send over Peppol BIS Billing 3.0. If you switch it on, evoicely emails the e-invoice to your customer. Every file and its validation report stays available to download. Get started, free for 10 e-invoices a month.
This is general information, not legal or tax advice. Check what applies to your business with your tax advisor.