Flowie
Guides

Flusso degli ordini: preventivo → ordine d'acquisto → conferma d'ordine → fattura

Preventivi, ordini d'acquisto, conferme d'ordine e fatture passano tutti dallo stesso POST /v1/documents/send e dallo stesso ciclo di vita, concatenati da un solo campo: orderReference.

Per chi
Mid-market · Grande gruppo — Acquirenti e venditori che lavorano con ordini
Tempo
≈ 30 min in sandbox
Serve
Due chiavi sandbox, una per parte (ottienila)
Aggiornato
30 nov 2026
Questa guida fa per te?
  • Piccola impresa — se fatturi senza ordini d'acquisto, no. Inizia da Inviare una fattura. Se un cliente ti dà un numero d'ordine, mettilo in orderReference sulla fattura, e basta.
  • Mid-market — invia gli ordini dal tuo ERP come le fatture (Collegare il tuo ERP) e usa questa guida per concatenarli.
  • Grande gruppo — lo stesso flusso per entità; ogni entità invia con la propria chiave o tramite una chiave piattaforma (Gruppi multi-entità).

I tipi di documenti d'ordine

Da uno all'altro cambiano solo type e il riferimento. Ogni tipo accetta le stesse forme di payload (JSON, XML, file).

typeChi lo inviaCosa dice
quoteVenditore → acquirenteUn'offerta: righe, prezzi, validità.
purchase-orderAcquirente → venditoreL'acquirente si impegna ad acquistare.
sales-orderVenditore → acquirenteLa conferma d'ordine del venditore.
goods-receiptAcquirenteCiò che è stato effettivamente ricevuto.
invoice · credit-note · debit-noteVenditore → acquirenteLa fattura e le sue rettifiche.

Come si concatenano i documenti

Ogni documento punta al precedente con document.orderReference. È l'unico campo di riferimento d'ordine dell'API (BT-13, reso come cac:OrderReference):

quote           QUO-2026-0042   seller → buyer
  │
purchase-order  PO-2026-9988    buyer → seller   orderReference: "QUO-2026-0042"
  │  seller sets the PO to approved (= order confirmed)
sales-order     SO-2026-0107    seller → buyer   orderReference: "PO-2026-9988"
  │
invoice         INV-2026-0311   seller → buyer   orderReference: "PO-2026-9988"
  │  buyer: received → approved → paid

Poiché ogni documento successivo all'ordine d'acquisto ne riporta il numero, elenchi tutto ciò che è stato fatturato su un ordine con una sola chiamata (passo 4).

1 · Inviare il preventivo (venditore)

Il venditore invia il preventivo come una fattura, con "type": "quote". In questa guida il venditore è la società di test sandbox vat:BE0000000001 e l'acquirente vat:FR12345678901.

curl -X POST https://back.flowie.ink/exchange/v1/documents/send \
  -H "Authorization: Bearer $FLOWIE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "quote",
    "format": "json",
    "from": "vat:BE0000000001",
    "to": "vat:FR12345678901",
    "document": {
      "number": "QUO-2026-0042",
      "issueDate": "2026-11-30",
      "currency": "EUR",
      "lines": [
        { "description": "Consulting", "quantity": 10, "unitPrice": 150.00, "vatRate": 20 }
      ]
    }
  }'
// Node 18+ (built-in fetch). Run: FLOWIE_API_KEY=flw_test_... node quote.mjs
const res = await fetch("https://back.flowie.ink/exchange/v1/documents/send", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.FLOWIE_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    type: "quote",
    format: "json",
    from: "vat:BE0000000001",
    to: "vat:FR12345678901",
    document: {
      number: "QUO-2026-0042",
      issueDate: "2026-11-30",
      currency: "EUR",
      lines: [{ description: "Consulting", quantity: 10, unitPrice: 150.0, vatRate: 20 }],
    },
  }),
});
const body = await res.json();
if (!res.ok) {
  console.error(res.status, JSON.stringify(body, null, 2));
  process.exit(1);
}
console.log(JSON.stringify(body, null, 2));
import os, json, requests

resp = requests.post(
    "https://back.flowie.ink/exchange/v1/documents/send",
    headers={
        "Authorization": f"Bearer {os.environ['FLOWIE_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "type": "quote",
        "format": "json",
        "from": "vat:BE0000000001",
        "to": "vat:FR12345678901",
        "document": {
            "number": "QUO-2026-0042",
            "issueDate": "2026-11-30",
            "currency": "EUR",
            "lines": [{"description": "Consulting", "quantity": 10, "unitPrice": 150.00, "vatRate": 20}],
        },
    },
    timeout=30,
)
if resp.status_code >= 400:
    raise SystemExit(f"{resp.status_code}: {resp.text}")
print(json.dumps(resp.json(), indent=2))

Risposta attesa — 201 Created:

{
  "id": "doc_sbx_…",
  "status": "sent",
  "type": "quote",
  "number": "QUO-2026-0042",
  "deliveryStatus": "delivered",
  "sentAt": "2026-11-30T09:12:44Z"
}

status: "sent" significa che Flowie ha accettato il documento. deliveryStatus è il suo stato sulla rete: pending in produzione finché il lato destinatario non conferma, poi delivered o failed; la sandbox risponde subito delivered.

2 · Inviare l'ordine d'acquisto (acquirente)

L'acquirente, con la propria chiave, accetta il preventivo inviando un ordine d'acquisto il cui orderReference è il numero del preventivo.

curl -X POST https://back.flowie.ink/exchange/v1/documents/send \
  -H "Authorization: Bearer $FLOWIE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "purchase-order",
    "format": "json",
    "from": "vat:FR12345678901",
    "to": "vat:BE0000000001",
    "document": {
      "number": "PO-2026-9988",
      "issueDate": "2026-11-30",
      "currency": "EUR",
      "orderReference": "QUO-2026-0042",
      "lines": [
        { "description": "Consulting", "quantity": 10, "unitPrice": 150.00, "vatRate": 20 }
      ]
    }
  }'

Il venditore riceve un webhook document.received con data.type uguale a PURCHASE_ORDER (vedi webhook).

3 · Confermare (o rifiutare) l'ordine (venditore)

Gli ordini usano gli stessi stati del ciclo di vita delle fatture. Non esiste uno stato «confermato» o «evaso» a parte: il venditore conferma un ordine d'acquisto portandolo ad approved, e lo rifiuta con rejected più un reasonCode. L'evasione si vede nei documenti successivi della catena — la conferma d'ordine, il ricevimento merci e la fattura che riportano il numero dell'ordine.

curl -X POST https://back.flowie.ink/exchange/v1/documents/{documentId}/lifecycle \
  -H "Authorization: Bearer $FLOWIE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "approved",
    "note": "Order confirmed, delivery week 50"
  }'

Risposta attesa — 200:

{
  "documentId": "doc_…",
  "previousStatus": "received",
  "currentStatus": "approved",
  "updatedAt": "2026-11-30T09:20:03Z",
  "compliance": {},
  "allowedTransitions": ["partially_paid", "paid", "disputed"]
}

Per rifiutare invece: {"status": "rejected", "reasonCode": "PRI", "reason": "Unit price differs from quote QUO-2026-0042"}. rejected è definitivo. La macchina a stati completa e i codici motivo sono nel riferimento del ciclo di vita.

Poi il venditore invia la sua sales-order (e, dopo la consegna, la invoice) esattamente come al passo 1, con "orderReference": "PO-2026-9988":

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": "vat:FR12345678901",
    "document": {
      "number": "INV-2026-0311",
      "issueDate": "2026-11-30",
      "dueDate": "2026-12-30",
      "currency": "EUR",
      "orderReference": "PO-2026-9988",
      "lines": [
        { "description": "Consulting", "quantity": 10, "unitPrice": 150.00, "vatRate": 20 }
      ]
    }
  }'

4 · Abbinare le fatture all'ordine

Ciascuna parte elenca tutte le fatture emesse su un ordine d'acquisto partendo dal suo numero — il valore che le fatture riportano in orderReference. La chiamata risponde a «cosa è già stato fatturato su questo ordine?» ed è il punto di partenza del tuo abbinamento ordine ↔ fattura. Un ordine senza fatture restituisce una lista vuota, non un 404.

curl https://back.flowie.ink/exchange/v1/purchase-orders/PO-2026-9988/invoices \
  -H "Authorization: Bearer $FLOWIE_API_KEY"
// Node 18+ (built-in fetch)
const res = await fetch(
  "https://back.flowie.ink/exchange/v1/purchase-orders/PO-2026-9988/invoices",
  { headers: { "Authorization": `Bearer ${process.env.FLOWIE_API_KEY}` } },
);
const body = await res.json();
if (!res.ok) {
  console.error(res.status, JSON.stringify(body, null, 2));
  process.exit(1);
}
const billed = body.data.reduce((sum, inv) => sum + inv.amount, 0);
console.log(`${body.data.length} invoice(s), ${billed} billed`);
import os, requests

resp = requests.get(
    "https://back.flowie.ink/exchange/v1/purchase-orders/PO-2026-9988/invoices",
    headers={"Authorization": f"Bearer {os.environ['FLOWIE_API_KEY']}"},
    timeout=30,
)
if resp.status_code >= 400:
    raise SystemExit(f"{resp.status_code}: {resp.text}")
invoices = resp.json()["data"]
print(f"{len(invoices)} invoice(s), {sum(i['amount'] for i in invoices)} billed")

Risposta attesa — 200 (pagina con cursor finché hasMore è true):

{
  "data": [
    {
      "id": "doc_…",
      "type": "INVOICE",
      "number": "INV-2026-0311",
      "issueDate": "2026-11-30",
      "currency": "EUR",
      "amount": 1800.0,
      "status": "received",
      "direction": "incoming"
    }
  ],
  "hasMore": false,
  "cursor": null
}

Per i controlli riga per riga (quantità e prezzi rispetto all'ordine), leggi ogni documento con GET /v1/documents/{documentId}/structured e confronta nel tuo sistema. Se una fattura non corrisponde, l'acquirente può sospenderla con disputed (motivo QTY o PRI) o rifiutarla con rejected.

Webhook per gli ordini

Gli ordini generano gli stessi eventi delle fatture. Due contano di più:

Le iscrizioni sono per evento, non per tipo di documento: filtra su data.type nel tuo handler.

curl -X POST https://back.flowie.ink/exchange/v1/webhooks \
  -H "Authorization: Bearer $FLOWIE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://yourapp.example.com/hooks/orders",
    "events": ["document.received", "lifecycle.updated"]
  }'
ORDER_TYPES = {"QUOTE", "PURCHASE_ORDER", "SALES_ORDER", "GOODS_RECEIPT"}

def handle(event: dict) -> None:
    # Verify X-Flowie-Signature first: see the webhooks reference.
    data = event["data"]
    if event["type"] == "document.received" and data["type"] in ORDER_TYPES:
        print("order document in:", data["type"], data["number"])
    elif event["type"] == "lifecycle.updated":
        if data["currentStatus"] == "approved":
            print("confirmed / approved:", data["documentId"])
        elif data["currentStatus"] == "rejected":
            print("refused:", data["documentId"], data.get("reasonCode"), data.get("reason"))

Payload, verifica della firma e calendario dei nuovi tentativi: Riferimento webhook.

Errori possibili

Stato / codiceCosa significaSoluzione
400 INVALID_REQUESTUn campo non ha superato la validazione, oppure manca to.Leggi details[] e correggi il corpo.
400 invalid_transitionIl cambio di stato non è consentito dallo stato attuale (per esempio, approvare un ordine già rejected).Leggi allowedTransitions da GET /v1/documents/{documentId}/lifecycle.
400 REASON_CODE_REQUIREDrejected o disputed inviato senza reasonCode.Aggiungi un codice motivo e un reason in testo libero.
403 COMPANY_FORBIDDENfrom indica una società per cui la tua chiave non può agire — tipicamente l'ordine dell'acquirente inviato con la chiave del venditore.Invia ogni parte con la propria chiave.
404 DOCUMENT_NOT_FOUNDId documento sconosciuto, o documento di cui la tua organizzazione non è parte.Usa l'id della risposta di invio o del webhook.
422 RECIPIENT_CANNOT_RECEIVELa controparte non accetta questo tipo di documento.Concorda un altro canale per gli ordini con quella controparte.

Test in sandbox

Crea una chiave sandbox per parte (chiavi API) e registra le due società di test con POST /v1/companies: BE0000000001 come venditore, FR12345678901 come acquirente. Poi esegui i passi da 1 a 4, cambiando chiave tra le chiamate del venditore e dell'acquirente. I cambi di ciclo di vita sui tuoi documenti sandbox si comportano come in produzione; per andare avanti nel tempo usa il viaggio nel tempo.

Prossimi passi