KSeF API for Poland — E‑Invoicing Compliance Playbook

Overview — What KSeF Is and Why It Matters

  • KSeF is Poland’s National e‑Invoicing System for structured B2B invoices. It assigns a unique KSeF ID to each accepted invoice and provides lifecycle statuses and auditability for tax compliance.
  • Businesses integrate via KSeF APIs to submit, receive, and query invoices, handle corrections, and maintain compliant archives. Vendors and SaaS platforms often embed KSeF as part of their billing or ERP flows.
  • Scope continues to evolve — always validate current go‑live phases, exemptions, and contingency procedures against official Ministry of Finance communications before committing timelines.

Legal and Compliance Scope — Entities, Transactions, Evidence

  • KSeF focuses on structured e‑invoices for domestic B2B transactions; specific rules may apply to cross‑border scenarios, self‑billing, and special VAT treatments.
  • Acceptance in KSeF yields a KSeF ID and official processing acknowledgment — this acts as the authoritative evidence that the invoice exists in the system.
  • Your compliance posture should cover authenticity and integrity of data, timely delivery, correction/cancellation workflows, and retention with audit trails.

Data Models — KSeF Logical Structure vs JPK_FA

  • KSeF uses a dedicated “FA” logical XML model for invoice content and metadata; it is optimized for transactional exchange, statuses, and reference to prior documents.
  • JPK_FA (SAF‑T for invoices) is an aggregate reporting/extract format used for audit/reporting, not for operational exchange. Its tags and normalization differ from KSeF’s FA structure.
  • Practical implication — do not “dump” JPK_FA into KSeF. Instead, map ERP fields to the KSeF FA schema and treat JPK_FA as a separate reporting pipeline.

JPK_FA XML Mapping — Field‑By‑Field Considerations

  • Parties — map Seller/Buyer NIP, legal name, addresses; ensure normalization (street, building, premise, postal code, country). JPK_FA naming and address blocks may differ.
  • Identification — ensure invoice number sequences comply with your policy; reference prior KSeF ID for corrections (faktura korygująca) and linked documents.
  • Tax lines — map each VAT rate category (e.g., 23, 8, 5, 0, “ZW”, “NP”) with base, tax, and totals; ensure precise rounding rules as per KSeF expectations.
  • Lines — items with quantity, unit price, discounts/charges; align unit codes and decimal precision to KSeF constraints (JPK_FA sometimes allows different scales).
  • References — purchase order, delivery note, contract numbers; transport/delivery dates for supply; payment terms and methods.
  • Totals — taxable base per rate, VAT per rate, grand totals; verify that numeric tolerances pass KSeF validation to avoid rejects.
  • Metadata — supply dates of issue/supply, currency, exchange rates; include annotations required by special regimes where applicable.

Tip: Build a canonical invoice model in your system, then implement dedicated mappers: ERP → Canonical → KSeF FA, and separately ERP → JPK_FA for audits.

Security and Identity — Authorizations and Tokens

  • Authorization is role‑based at the taxpayer entity level. Onboard authorized representatives and generate API tokens for server‑to‑server integrations under your organization.
  • Maintain least‑privilege scopes, rotate tokens regularly, and segregate credentials per environment (sandbox, pre‑prod, prod).
  • If you support multi‑tenant SaaS, isolate token stores and enforce per‑tenant rate limits and audit logs.

Transport and Packaging — Submission Patterns

  • Submissions are asynchronous: you send a structured invoice package, KSeF validates and processes, then you retrieve status and the assigned KSeF ID if accepted.
  • Use idempotent submission with stable correlation IDs to avoid duplicates; implement retries with exponential backoff and jitter for transient errors or throttling.
  • Compress large payloads, sign where required by your policy, and always capture the raw request/response for evidence and troubleshooting.

Processing and Statuses — From Draft to Accepted

  • Typical states include received, validating, accepted, or rejected with error codes and diagnostics. Rejections cite schema/business‑rule violations to fix and resubmit.
  • Upon acceptance, the system returns or exposes the official KSeF ID and processing timestamp — store both in your ERP to ensure perfect reconciliation.
  • For buyers, implement retrieval/subscription to inbound invoices; for suppliers, subscribe to status callbacks or poll efficiently to keep UIs and ledgers in sync.

Corrections and Cancellations — Reference Integrity

  • Polish practice uses correction invoices to amend prior invoices. Always reference the original invoice number and, where required, the original KSeF ID.
  • Support partial and full corrections, tax base adjustments, and text annotations explaining the reason. Keep a linked list in your database to show the entire correction chain.
  • If a cancellation flow exists for specific edge cases, implement the required reference and evidence emission to satisfy audits.

Validation — Preventing KSeF Rejects

  • Schema validation — validate against the current KSeF FA XSD before submission; maintain a versioned validator to handle spec updates.
  • Business rules — pre‑check tax logic, rate applicability, exemption codes, date consistency, and totals/rounding.
  • Address quality — standardize and validate address fields; normalize country codes, postal formats, and diacritics to reduce rejects.

Observability — Monitoring, Alerts, and Auditability

  • Metrics — submission throughput, acceptance ratio, time‑to‑acceptance, and top rejection reasons.
  • Alerts — notify on spikes of rejects, SLA breaches, or API outages; implement dead‑letter queues with replay tooling.
  • Evidence — store normalized JSON/XML, raw source payloads, responses, timestamps, hashes, and the KSeF ID; produce regulator‑ready exports on demand.

Archiving and Retention — Integrity and Proof

  • Retain invoices and all acknowledgments for statutory periods with integrity controls (hashes, timestamps, write‑once storage where feasible).
  • Maintain a verifiable audit trail tying each ledger entry to a KSeF ID and its acceptance evidence.
  • Periodically test restorability and traceability — simulate audits to ensure your evidence bundle is complete.

Multi‑Company and Multi‑Channel — Enterprise Patterns

  • Multi‑entity (multi NIP) — partition tokens, sequences, and archives per legal entity; enforce per‑entity configuration and routing.
  • Hybrid channels — if you exchange via KSeF and other networks (e.g., PEPPOL for foreign buyers), converge into one canonical model with channel‑specific adapters.
  • Tenant isolation — for SaaS, isolate storage and keys per tenant; expose per‑tenant dashboards and download APIs for evidence packs.

KSeF API Integration — Step‑by‑Step

1) Readiness and scoping — inventory legal entities, volumes, peak windows, and inbound vs outbound needs. 2) Authorization setup — onboard representatives, create API tokens, define roles and least‑privilege scopes. 3) Canonical model — define a neutral invoice schema covering parties, lines, tax, totals, references, and metadata. 4) Mapping — implement ERP → Canonical → KSeF FA mappers; separately build ERP → JPK_FA for audits. 5) Validation — XSD validation for KSeF FA, business‑rule checks, tax calculators, and rounding verification. 6) Connectivity — implement endpoints, idempotent submissions, retries/backoff, and correlation IDs; wire sandbox first. 7) Status orchestration — callbacks/polling, state machine, and reconciliation that writes KSeF IDs into ERP. 8) Evidence and archiving — store payloads, responses, timestamps, and logs; enable on‑demand export for audits. 9) Monitoring — dashboards, alerts, DLQs, and playbooks for incident response. 10) Go‑live — performance tests, failover rehearsal, runbook, and hyper‑care with daily stability reports.

Testing Matrix — What Good Looks Like

  • Positive flows — standard invoices across all VAT rates, with and without exemptions; multi‑currency with exchange rates.
  • Negative flows — schema violations, rounding mismatches, invalid NIP, date inconsistencies, missing references.
  • Lifecycle — corrections, cancellations, and buyer refusals; inbound receipt handling.
  • Non‑functional — bursts and throttling, idempotency checks, recovery from partial outages, and data integrity under load.

Pricing and Product Strategy — For SaaS Vendors

  • Pricing model — base subscription per legal entity (NIP) plus tiered volume per accepted invoice; add premium for advanced monitoring, analytics, and regulatory update SLAs.
  • Bundles — “KSeF Core” (submission + status + archiving), “KSeF Plus” (inbound inbox + approvals), and “Compliance Updates” (schema/business‑rule tracking).
  • Roadmap — connectors to popular ERPs, low‑code mapping UI, evidence export APIs, and alert webhooks; publish time‑to‑acceptance and acceptance‑rate KPIs.

Common Pitfalls — And How to Avoid Them

  • Treating JPK_FA as a submission format — it is not; build a dedicated KSeF FA mapper and validation pipeline.
  • Weak idempotency — duplicates arise during retries; always use stable correlation IDs and dedupe logic.
  • Ignoring rounding rules — tiny discrepancies cause rejects; align tax and total calculators with KSeF expectations.
  • Sparse observability — without DLQs and alerts, transient errors escalate into compliance incidents.
  • Single‑tenant assumptions — for SaaS, lack of tenant isolation and per‑entity archives creates audit and security risks.

Summary — What to Remember

  • KSeF is a transactional e‑invoicing platform — treat it separately from JPK_FA reporting and build a robust FA mapper.
  • Invest in validation, idempotent transport, status orchestration, and evidence‑grade archiving for compliance and auditability.
  • For ksef api integration and poland einvoicing ksef compliance, center your design on a canonical model, strict validators, and strong observability; for jpk fa xml mapping, implement a dedicated reporting mapper independent from KSeF flows.