---
title: "Connect your ERP to Flowie"
description: "Send e-invoices straight from D365, SAP S/4HANA, NetSuite or any ERP: point its invoice event at POST /v1/documents/send, pick a payload shape (JSON, UBL/CII, file, native event), add a webhook receiver and make retries safe."
canonical: "https://docs.get-flowie.com/guides/erp-integration"
source: "https://docs.get-flowie.com/guides/erp-integration.html"
---

# Connect your ERP to Flowie

Guides

# Connect your ERP to Flowie

Point your ERP's "invoice posted" event at one endpoint, `POST /v1/documents/send`, and every invoice, credit note or order it produces leaves as a compliant e-invoice.

For
    Mid-market · Large group — Sellers (and Buyers sending purchase orders)

Time
    ≈ 45 min in sandbox

You need
    A sandbox key ([get one](<../sandbox/keys.html>)) and an ERP that can call a URL

Updated
    30 Nov 2026

Which path for your size

  * **Small business** — no code needed. Bill in Stripe? Use the [Stripe app](<stripe.html>). Another accounting tool? Check the [integrations catalogue](<integrations.html>) first.
  * **Mid-market** — one ERP, one webhook. Map the ERP's invoice event to `/v1/documents/send`, directly or through the small receiver in [step 2](<#receiver>).
  * **Large group** — one glue layer per ERP (the same receiver, one mapping per system), and either one API key per entity or a single platform key acting for every entity. See [Multi-entity groups](<multi-entity.html>).



## How it works

There is no separate "inbound" route. The endpoint that sends an invoice is the one your ERP calls: same key, same idempotency, same lifecycle and webhooks. Whatever you push goes through validation, routing and the lifecycle like any other document.
[code] 
    ┌────────────────┐  invoice posted,   ┌─────────────────────┐   HTTPS POST          ┌──────────────────┐
    │   Your ERP     │  order confirmed…  │  Glue (optional):   │  /v1/documents/send   │  Flowie Exchange │
    │                │ ──────────────────▶│  receiver, Logic    │ ─────────────────────▶│                  │
    └────────────────┘                    │  App, Lambda…       │  Bearer + Idem-Key    └──────────────────┘
                                          └─────────────────────┘
[/code]

The glue is optional: if your ERP can POST JSON to a URL with an `Authorization` header, call Flowie directly. Add the glue when you need to map fields, fetch the rendered PDF, or turn a non-2xx answer into an ERP retry.

## Pick a payload shape

Pick the row that matches what your ERP can produce. All five go to the same endpoint.

Shape| You have| Request| What Flowie does  
---|---|---|---  
[A · JSON](<#send-json>)| Field-level data (number, dates, lines)| `"format": "json"` \+ `document`| Renders, validates and routes the e-invoice  
[B · UBL / CII XML](<#shape-ubl>)| Peppol BIS 3.0 / EN 16931 XML from the ERP| `"format": "ubl-xml"` or `"cii-xml"` \+ `xml`| Validates, then routes  
[C · File, auto](<#shape-auto>)| A file: Factur-X PDF, UBL, PDF, image…| `"format": "auto"` \+ `file` (base64)| Sniffs the bytes: UBL, CII and Factur-X are read and routed; anything else is stored  
[D · File, raw](<#shape-raw>)| A file to archive, not interpret| `"format": "raw"` \+ `file`| Stores the bytes as-is, never routes  
[E · Native event](<#shape-event>)| An ERP event that is not an invoice| `?type=event` in the URL, ERP payload as the body| Records the event for audit, never routes  
  
## 1 · Send your first document from an ERP mapping

Shape A is the usual mid-market choice: your mapping turns the ERP record into JSON, and Flowie builds the compliant XML. Derive the `Idempotency-Key` from the ERP record, so a webhook retry never creates a second invoice. The same body works for `credit-note`, `debit-note`, `purchase-order`, `sales-order` and `quote`: only `type` and the references change.
[code] 
    curl -X POST https://back.flowie.ink/exchange/v1/documents/send \
      -H "Authorization: Bearer $FLOWIE_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "type": "invoice",
        "format": "json",
        "from": "vat:BE0000000001",
        "to": "0208:TEST_OK",
        "document": {
          "number": "INV-2026-0042",
          "issueDate": "2026-11-30",
          "dueDate": "2026-12-30",
          "currency": "EUR",
          "buyerReference": "BUYER-REF-77",
          "orderReference": "PO-2026-9988",
          "payment": { "means": "credit_transfer", "iban": "BE68539007547034", "reference": "INV-2026-0042" },
          "lines": [
            { "description": "Consulting", "quantity": 10, "unit": "HUR", "unitPrice": 150.00, "vatRate": 21 },
            { "description": "Travel", "quantity": 1, "unit": "C62", "unitPrice": 320.00, "vatRate": 21 }
          ]
        }
      }'
[/code]

Expected response — `201 Created` (a `200` with `Idempotent-Replayed: true` means the same document had already been sent, and nothing new was created):
[code] 
    {
      "id": "doc_sbx_…",
      "status": "sent",
      "type": "invoice",
      "number": "INV-2026-0042",
      "from": { "peppolId": "…" },
      "to": { "peppolId": "0208:TEST_OK" },
      "deliveryStatus": "delivered",
      "sentAt": "2026-11-30T09:12:44Z"
    }
[/code]

Two fields, two questions:

  * **`status`** — what Flowie did with your request. `sent`: accepted and handed to the network. `stored`: a file kept without routing (shapes C/D). `recorded`: an event (shape E).
  * **`deliveryStatus`** — where the document is on the network. Live: `pending` until the recipient's access point confirms, then `delivered` or `failed` (also sent as `document.delivered` / `document.failed` webhooks). `awaiting_registration`: saved, and routed as soon as the sender is connected to Peppol. `stored`: kept without routing. The sandbox answers synchronously with `delivered`.



Totals are optional: omit `totals` and Flowie sums the lines. Every field of `document` is in the [endpoint reference](<../reference/index.html#send-document>).

### Shape B — UBL or CII XML from the ERP

Your ERP already renders Peppol BIS 3.0 / EN 16931 XML. Send the XML as a JSON string; Flowie validates it before routing. A UBL document that fails validation is refused with `422 UBL_VALIDATION_FAILED`. For CII, use `"format": "cii-xml"`.
[code] 
    # jq builds the JSON and escapes the XML for you
    jq -n --rawfile xml INV-2026-0042.xml \
      '{type: "invoice", format: "ubl-xml", from: "vat:BE0000000001", to: "0208:TEST_OK", xml: $xml}' |
    curl -X POST https://back.flowie.ink/exchange/v1/documents/send \
      -H "Authorization: Bearer $FLOWIE_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: erp-invoice-INV-2026-0042" \
      -d @-
[/code]

### Shape C — a file, `format=auto`

The forgiving option when you don't fully control what the ERP emits. Base64-encode the file; Flowie reads its first bytes. UBL XML, CII XML and Factur-X PDF/A-3 (for invoices, credit notes and debit notes) are read into a structured document and routed. Any other PDF, image, ZIP or JSON is stored as-is.
[code] 
    jq -n --arg b64 "$(base64 < INV-2026-0042.pdf | tr -d '\n')" \
      '{type: "invoice", format: "auto", from: "vat:BE0000000001", to: "0208:TEST_OK",
        file: {content: $b64, contentType: "application/pdf", filename: "INV-2026-0042.pdf"}}' |
    curl -X POST https://back.flowie.ink/exchange/v1/documents/send \
      -H "Authorization: Bearer $FLOWIE_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: erp-invoice-INV-2026-0042" \
      -d @-
[/code]

Expected response for a plain PDF (no embedded invoice data) — kept, not routed:
[code] 
    {
      "id": "doc_sbx_…",
      "status": "stored",
      "type": "invoice",
      "deliveryStatus": "stored",
      "fileId": "file_sbx_…",
      "storedFormat": "pdf"
    }
[/code]

### Shape D — a file, `format=raw` (archive only)

Skip the sniffer: the bytes are stored verbatim and never routed. Use it for audit copies or proprietary exports you want to keep next to the e-invoice, and fetch them back later from the document.
[code] 
    curl -X POST https://back.flowie.ink/exchange/v1/documents/send \
      -H "Authorization: Bearer $FLOWIE_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "type": "invoice",
        "format": "raw",
        "from": "vat:BE0000000001",
        "to": "0208:TEST_OK",
        "file": {
          "content": "AQIDBAUG",
          "contentType": "application/octet-stream",
          "filename": "legacy-export.dat"
        }
      }'
[/code]

### Shape E — a native ERP event, verbatim

For ERP events that are not invoices (an order confirmed, a payment journal posted, a workflow completed) and that you want on record. Put `type=event` in the query string and send the ERP's own JSON as the body, byte for byte — no wrapping, no base64. `from` is optional for events (it defaults to your organization). The response carries `deliveryStatus: "recorded"`; events are never routed.
[code] 
    curl -X POST "https://back.flowie.ink/exchange/v1/documents/send?type=event" \
      -H "Authorization: Bearer $FLOWIE_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "eventType": "SalesOrderConfirmed",
        "eventId": "7f3c9a2e-1b4d-4e8a-9c61-2d5f0b8e4a17",
        "salesOrderId": "SO-2026-0107",
        "totalAmount": 6480.00,
        "currency": "EUR"
      }'
[/code]

Optional query parameters: `from`, `contentType` (overrides the stored media type) and `filename` (defaults to the `Idempotency-Key`, else a random name). The raw-body mode is switched on by `type` in the URL; without it, the JSON body of shapes A–D applies. Raw-body mode has no `to`, so use it for events only: an invoice needs shape A, B or C.

### What comes back, per format

Every document type — `invoice`, `credit-note`, `debit-note`, `purchase-order`, `sales-order`, `quote`, `goods-receipt` — accepts every shape A–D. What you get back depends on the format and, for files, on the bytes:

format| Body field| Bytes detected| `deliveryStatus`  
---|---|---|---  
`json`| `document`| —| `pending` → `delivered` / `failed`  
`ubl-xml` · `cii-xml`| `xml`| —| `pending` (after validation)  
`auto`| `file`| UBL or CII XML| `pending`  
`auto`| `file`| Factur-X PDF/A-3 (invoice, credit or debit note)| `pending`; the number is read from the embedded CII  
`auto`| `file`| Other PDF| `stored`, `storedFormat: "pdf"`  
`auto`| `file`| PNG / JPEG / GIF| `stored`, `storedFormat: "png"` · `"jpeg"` · `"gif"`  
`auto`| `file`| ZIP| `stored`, `storedFormat: "zip"`  
`auto`| `file`| JSON or unknown| `stored`, `storedFormat: "json"` · `"binary"`  
`raw`| `file`| never inspected| `stored`  
`?type=event`| request body| —| `recorded`  
  
Wherever the table says `pending`, a sender not yet connected to Peppol gets `awaiting_registration` instead: the document is saved and leaves once the registration is active.

## 2 · Put a webhook receiver between the ERP and Flowie

Most ERPs retry a webhook when it gets a non-2xx answer. A small receiver lets you map fields, keep your API key out of the ERP, and hand Flowie's failures back to the ERP so it retries. Below, a complete FastAPI receiver. Adapt `map_erp_invoice()` to your ERP's event; the rest stays as is.

The example ERP event it expects:
[code] 
    {
      "eventId": "evt-000184",
      "invoice": {
        "number": "INV-2026-0042",
        "issueDate": "2026-11-30",
        "dueDate": "2026-12-30",
        "currency": "EUR",
        "customerPeppolId": "0208:TEST_OK",
        "customerPo": "PO-2026-9988",
        "lines": [
          { "text": "Consulting", "qty": 10, "unitPrice": 150.0, "vatPercent": 21 }
        ]
      }
    }
[/code]
[code] 
    # erp_receiver.py
    # pip install fastapi uvicorn httpx
    # FLOWIE_API_KEY=flw_test_... ERP_SHARED_SECRET=change-me uvicorn erp_receiver:app --port 8080
    import hmac
    import os
    from contextlib import asynccontextmanager
    
    import httpx
    from fastapi import FastAPI, HTTPException, Request
    
    FLOWIE_BASE = os.environ.get("FLOWIE_BASE", "https://back.flowie.ink/exchange")
    FLOWIE_API_KEY = os.environ["FLOWIE_API_KEY"]
    ERP_SHARED_SECRET = os.environ["ERP_SHARED_SECRET"]
    SENDER = os.environ.get("FLOWIE_SENDER", "vat:BE0000000001")  # your company
    
    
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        app.state.flowie = httpx.AsyncClient(
            base_url=FLOWIE_BASE,
            headers={"Authorization": f"Bearer {FLOWIE_API_KEY}"},
            timeout=30.0,
        )
        yield
        await app.state.flowie.aclose()
    
    
    app = FastAPI(lifespan=lifespan)
    
    
    def map_erp_invoice(event: dict) -> dict:
        """Turn one ERP 'invoice posted' event into a Flowie send request."""
        inv = event["invoice"]
        return {
            "type": "invoice",
            "format": "json",
            "from": SENDER,
            "to": inv["customerPeppolId"],
            "document": {
                "number": inv["number"],
                "issueDate": inv["issueDate"],
                "dueDate": inv.get("dueDate"),
                "currency": inv.get("currency", "EUR"),
                "orderReference": inv.get("customerPo"),
                "lines": [
                    {
                        "description": line["text"],
                        "quantity": line["qty"],
                        "unitPrice": line["unitPrice"],
                        "vatRate": line["vatPercent"],
                    }
                    for line in inv["lines"]
                ],
            },
        }
    
    
    @app.post("/erp/invoice-posted")
    async def invoice_posted(request: Request):
        # 1. Only your ERP may call this URL.
        secret = request.headers.get("X-ERP-Secret", "")
        if not hmac.compare_digest(secret, ERP_SHARED_SECRET):
            raise HTTPException(status_code=401, detail="bad shared secret")
    
        # 2. Map. A mapping error will not fix itself: answer 422.
        event = await request.json()
        try:
            payload = map_erp_invoice(event)
            idempotency_key = f"erp-{event['eventId']}"
        except (KeyError, TypeError) as exc:
            raise HTTPException(status_code=422, detail=f"cannot map ERP event: {exc!r}")
    
        # 3. Send. The key makes the ERP's retries safe: no duplicate invoice.
        try:
            resp = await request.app.state.flowie.post(
                "/v1/documents/send",
                json=payload,
                headers={"Idempotency-Key": idempotency_key},
            )
        except httpx.HTTPError as exc:
            raise HTTPException(status_code=503, detail=f"Flowie unreachable: {exc!r}")
    
        # 4. Hand Flowie's answer back to the ERP as a non-2xx, so it retries.
        if resp.status_code in (409, 429) or resp.status_code >= 500:
            raise HTTPException(
                status_code=503,
                detail=resp.text,
                headers={"Retry-After": resp.headers.get("Retry-After", "30")},
            )
        if resp.status_code >= 400:
            # 400/401/403/422: the payload or the key is wrong. Surface it, fix the mapping.
            raise HTTPException(status_code=422, detail=resp.text)
    
        doc = resp.json()
        return {"flowieId": doc["id"], "status": doc["status"], "deliveryStatus": doc["deliveryStatus"]}
[/code]

Try it locally with the event above saved as `event.json`:
[code] 
    curl -X POST http://localhost:8080/erp/invoice-posted \
      -H "Content-Type: application/json" \
      -H "X-ERP-Secret: change-me" \
      -d @event.json
[/code]

Retryable failures (Flowie unreachable, `409 IDEMPOTENCY_IN_PROGRESS`, `429`, `5xx`) come back as `503` with a `Retry-After`; mapping or key problems as `422`. Both are non-2xx, so the ERP keeps the event and you see it in its failed-deliveries log.

## ERP recipes

### Microsoft Dynamics 365

Dynamics 365 Finance & Operations publishes **business events** (sales invoice posted, free text invoice posted, sales order confirmed…) to an endpoint you configure: HTTPS, Power Automate, Azure Service Bus or Event Grid. The event carries the document's keys, not the invoice itself. Two common set-ups:

  * **Power Automate or Logic App** — trigger on the business event, read the invoice header and lines through the D365 data entities (or fetch the rendered Factur-X), then call `/v1/documents/send` with shape A (or C for the file). Use the business event's `EventId` in the `Idempotency-Key`.
  * **HTTPS endpoint to your receiver** — point the business event at the [receiver](<#receiver>) above and do the read-and-map step in `map_erp_invoice()`.



Business events that are not invoices (order confirmed, payment journal posted, workflow completed) can be archived as they are with [shape E](<#shape-event>): the event's JSON becomes the request body, nothing to map.

### SAP S/4HANA

S/4HANA raises business events (for example, a billing document created) that SAP Event Mesh, or SAP Integration Suite, delivers to a webhook. Like D365, the event carries the document key: read the billing document through its OData API, map it, send it with shape A. If your output management already produces UBL or CII, send that with shape B instead. Use the event's message id in the `Idempotency-Key`.

### NetSuite, Sage Intacct, QuickBooks, homegrown

  * **NetSuite** — a User Event Script (`afterSubmit` on the invoice record) calls Flowie with the `N/https` module. Use the record's internal id in the `Idempotency-Key`.
  * **Sage Intacct** — a Smart Event on the invoice object posts to your receiver, which maps and sends.
  * **QuickBooks Online** — webhooks only tell you an invoice changed. Read it through the QuickBooks API, then send.
  * **Homegrown ERP** — any HTTPS POST that reaches `/v1/documents/send` with a valid key and body works.



### Many documents in one call

For nightly runs or back-fills, [`POST /v1/documents/send/batch`](<../reference/index.html#send-batch>) takes a `documents` array. Each item has its own `idempotencyKey` and its own result: one bad item does not fail the batch (the call answers `200` with per-item `results` and a `summary`).
[code] 
    curl -X POST https://back.flowie.ink/exchange/v1/documents/send/batch \
      -H "Authorization: Bearer $FLOWIE_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "documents": [
          { "idempotencyKey": "erp-row-101", "type": "invoice", "format": "json",
            "from": "vat:BE0000000001", "to": "0208:TEST_OK",
            "document": { "number": "INV-2026-0101", "issueDate": "2026-11-30", "currency": "EUR",
              "lines": [{ "description": "Consulting", "quantity": 4, "unitPrice": 150.00, "vatRate": 21 }] } },
          { "idempotencyKey": "erp-row-102", "type": "invoice", "format": "json",
            "from": "vat:BE0000000001", "to": "0208:TEST_OK",
            "document": { "number": "INV-2026-0102", "issueDate": "2026-11-30", "currency": "EUR",
              "lines": [{ "description": "Support", "quantity": 1, "unitPrice": 480.00, "vatRate": 21 }] } }
        ]
      }'
[/code]

## 3 · Idempotency, retries and failures

Always send an `Idempotency-Key` built from the source system: `{system}-{eventId}` or `{system}-{documentNumber}`. A retry with the same key within 24 hours returns the first answer instead of sending twice. Even without the header, an unchanged payload that was already sent is answered with the existing document and `200` \+ `Idempotent-Replayed: true`. See [Reference → Idempotency](<../reference/index.html#idempotency>).

What to do with each answer:

  * **201** — created. Store the `id` next to the ERP record.
  * **200** \+ `Idempotent-Replayed: true` — already sent; treat as success.
  * **400 / 422** — the payload is wrong. Fix the mapping; retrying the same body won't help.
  * **409`IDEMPOTENCY_IN_PROGRESS`** — the same send is still running. Retry the same request after `Retry-After` seconds.
  * **429** — rate-limited. Wait `Retry-After` seconds.
  * **5xx** — retry with backoff and the same key.



Every error body carries a `requestId`. Look it up with [`GET /v1/requests/{requestId}`](<../reference/index.html#request-inspector>) to see the redacted request and response.

## Errors you may hit

Status / code| What it means| Fix  
---|---|---  
`400` `INVALID_REQUEST`| A field failed validation: bad date, unknown `type`, missing `to`, invalid base64…| Read `details[]`; fix the mapping.  
`401` `MISSING_AUTH` / `INVALID_TOKEN`| No key, or a key that isn't valid.| Send `Authorization: Bearer $FLOWIE_API_KEY`; check the key and the environment.  
`403` `COMPANY_FORBIDDEN`| `from` is a company your key can't act for.| Use that entity's key, or a platform key that manages it.  
`409` `IDEMPOTENCY_IN_PROGRESS`| An identical send is still processing.| Retry the same request after `Retry-After`.  
`409` `IDEMPOTENCY_BODY_MISMATCH`| Same key, different body.| Reuse the original body, or use a new key for a new document.  
`422` `RECIPIENT_NOT_FOUND`| The recipient isn't registered on the network.| Check the identifier, or look the company up in the directory.  
`422` `RECIPIENT_CANNOT_RECEIVE`| The recipient doesn't accept this document type.| Ask the customer for another channel, or check its directory record.  
`422` `UBL_VALIDATION_FAILED`| The XML fails Peppol BIS / EN 16931 rules.| Fix the rule named in the error (BR-*), or send shape A and let Flowie render.  
`429` `RATE_LIMITED`| Too many requests per minute.| Wait `Retry-After`; batch, or send fewer calls in parallel.  
`5xx`| Flowie or a dependency is degraded.| Retry with backoff and the same `Idempotency-Key`.  
  
Delivery problems that happen after the `201` arrive as a `document.failed` webhook — see [Errors → Delivery failures](<../reference/errors.html#delivery>).

## Test in sandbox

Point the ERP (or your receiver's `FLOWIE_BASE`) at `https://back.flowie.ink/exchange` with a `flw_test_…` key. The sandbox accepts every shape production does and never touches the live network. Useful recipients: `0208:TEST_OK` (delivers), `0208:TEST_AP_FAIL` (fires `document.failed`), `0208:TEST_NOT_REGISTERED` (`422 RECIPIENT_NOT_FOUND`). The full list is in [Sandbox → test Peppol IDs](<../sandbox/index.html#test-peppol>); what the sandbox simulates is in [sandbox shortcuts](<../sandbox/index.html#sandbox-shortcuts>). When it works, switch `FLOWIE_BASE` to `https://back.p2p-flowie.com/exchange` and use a `flw_live_…` key.

## Next steps

  * [Receive invoices](<receive-invoices.html>) — subscribe to `document.delivered`, `document.failed` and incoming invoices.
  * [Order flow](<order-flow.html>) — quotes, purchase orders and sales orders on the same endpoint.
  * [Multi-entity groups](<multi-entity.html>) — one key per entity, or one platform key for all.
  * [Webhooks reference](<../reference/webhooks.html>) — events, signatures and the retry schedule.
  * [Go-live checklist](<index.html#go-live>) — prove you are production-ready.
