KSeF API 2.0 step by step: sending an invoice from your own system

From the KSeF token to the KSeF number and the UPO: authentication, an online session, RSA-OAEP and AES-256 encryption and sending an FA(3) invoice. Python code run against the Ministry of Finance test environment.

What you will do

By the end of this guide your system sends a structured invoice to Poland's National e-Invoicing System (KSeF) on its own and stores its KSeF number and the official receipt (UPO). All through API 2.0, with no manual login to the taxpayer app.

Issuing invoices in KSeF has been mandatory since 1 February 2026 for companies whose 2024 sales exceeded PLN 200 million, and since 1 April 2026 for other taxpayers; the smallest companies, which may issue invoices outside KSeF until the end of 2026, join on 1 January 2027. We work on the test environment, so nothing you send here has any tax effect.

Level
advanced
Code
Python
Steps
8 steps
  1. Stage 1 KSeF token A secret with permission to issue invoices.
  2. Stage 2 Access token Challenge, encrypted token, redeemed token.
  3. Stage 3 Online session An AES-256 key sealed with the Ministry key.
  4. Stage 4 FA(3) invoice Encrypted XML with two SHA-256 hashes.
  5. Result KSeF number and UPO Proof that the invoice is in the system.

What you need

  • A KSeF token for the TEST environment

    A token is generated with POST /tokens after a one-time XAdES signature login. On TEST a self-signed certificate and a random tax ID (NIP) are enough. The token's permissions are fixed when it is created, so grant InvoiceWrite right away.

  • Python 3 with requests and cryptography

    Two libraries: requests for HTTP and cryptography for RSA-OAEP, AES and reading X.509 certificates. Nothing else is needed.

  • An FA(3) invoice file

    XML that matches the FA(3) schema, with the header kodSystemowy="FA (3)" and wersjaSchemy="1-0E". Use made-up data on TEST: the Ministry's documentation forbids real invoices and real company data there.

  • A safe place for the token

    A KSeF token authenticates just like a qualified signature. Keep it in a secret manager or an environment variable, never in the repository.

The three KSeF API 2.0 environments

EnvironmentAPI addressWhat for
TESThttps://api-test.ksef.mf.gov.pl/v2Integration and release candidates; self-signed certificates allowed, data shared between integrators.
DEMOhttps://api-demo.ksef.mf.gov.pl/v2Final validation in a production-like configuration.
PRODhttps://api.ksef.mf.gov.pl/v2Invoices with full legal effect.

Step by step

Each step with commands to copy. The list on the left shows where you are.

01

Fetch the Ministry public keys

The Ministry publishes two certificates: one for encrypting the KSeF token (KsefTokenEncryption), the other for encrypting the session key (SymmetricKeyEncryption). The endpoint is public and needs no login. The certificate arrives as Base64-encoded DER.

Encryption is always RSA-OAEP with SHA-256 and MGF1 with SHA-256. With any other hash the server cannot decrypt the data.

ksef.py
import base64import requestsfrom cryptography import x509from cryptography.hazmat.primitives import hashesfrom cryptography.hazmat.primitives.asymmetric import paddingAPI = "https://api-test.ksef.mf.gov.pl/v2"def mf_key(usage: str): certs = requests.get(f"{API}/security/public-key-certificates", timeout=30).json() cert = next(c for c in certs if usage in c["usage"]) der = base64.b64decode(cert["certificate"]) return x509.load_der_x509_certificate(der).public_key()def rsa_oaep(key, data: bytes) -> str: sealed = key.encrypt(data, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) return base64.b64encode(sealed).decode()
02

Get a challenge

POST /auth/challenge returns a one-time challenge and a timestamp in milliseconds. The challenge is valid for 10 minutes. To encrypt the token you need the timestampMs field, not timestamp.

ksef.py
challenge = requests.post(f"{API}/auth/challenge", timeout=30).json()# {"challenge": "20261006-CR-...", "timestamp": "2026-10-06T12:33:47+00:00",# "timestampMs": 1791290027137, "clientIp": "..."}
03

Encrypt the token and start authentication

You encrypt the text token|timestampMs with the KsefTokenEncryption key and send it with the challenge and the context identifier. The context is the company you act for: type Nip and its NIP.

The server answers 202 with the operation reference number and an authentication token. That is not API access yet: with this token you only check the status and redeem the real one.

ksef.py
import osKSEF_TOKEN = os.environ["KSEF_TOKEN"]NIP = os.environ["KSEF_NIP"]plain = f"{KSEF_TOKEN}|{challenge['timestampMs']}".encode()init = requests.post(f"{API}/auth/ksef-token", json={ "challenge": challenge["challenge"], "contextIdentifier": {"type": "Nip", "value": NIP}, "encryptedToken": rsa_oaep(mf_key("KsefTokenEncryption"), plain),}, timeout=30)init.raise_for_status() # 202 Acceptedoperation = init.json()auth = {"Authorization": f"Bearer {operation['authenticationToken']['token']}"}
04

Wait for the result and redeem the access token

GET /auth/{referenceNumber} returns status 100 (in progress), 200 (success) or an error code. After 200 you call POST /auth/token/redeem and receive an accessToken and a refreshToken.

Redeeming works only once. When the accessToken expires you do not start over: you call POST /auth/token/refresh with the refreshToken.

ksef.py
import timewhile True: status = requests.get(f"{API}/auth/{operation['referenceNumber']}", headers=auth, timeout=30).json()["status"] if status["code"] == 200: break if status["code"] != 100: raise RuntimeError(status) # 415, 425, 450... time.sleep(1)tokens = requests.post(f"{API}/auth/token/redeem", headers=auth, timeout=30).json()access = {"Authorization": f"Bearer {tokens['accessToken']['token']}"}refresh_token = tokens["refreshToken"]["token"]
05

Open an online session

You draw a 32-byte AES key and a 16-byte IV. You encrypt the key with the SymmetricKeyEncryption key and send the IV in plain Base64. The form code for an FA(3) invoice is systemCode "FA (3)", schemaVersion "1-0E", value "FA".

The server answers 201 with the session number and its expiry. In one session you send as many invoices as you like under the same key.

ksef.py
key, iv = os.urandom(32), os.urandom(16) # AES-256 key and IV for this sessionopened = requests.post(f"{API}/sessions/online", headers=access, json={ "formCode": {"systemCode": "FA (3)", "schemaVersion": "1-0E", "value": "FA"}, "encryption": { "encryptedSymmetricKey": rsa_oaep(mf_key("SymmetricKeyEncryption"), key), "initializationVector": base64.b64encode(iv).decode(), },}, timeout=30)opened.raise_for_status() # 201 Createdsession_ref = opened.json()["referenceNumber"]
06

Encrypt and send the invoice

You encrypt the invoice XML with AES-256-CBC and PKCS#7 padding. The request carries the SHA-256 hash and size of the plain file and the hash and size of the encrypted one, all hashes in Base64.

The IV does not go into the invoice content: you gave it when opening the session.

ksef.py
import hashlibfrom cryptography.hazmat.primitives import padding as sym_paddingfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modesdef aes_cbc(data: bytes) -> bytes: padder = sym_padding.PKCS7(128).padder() padded = padder.update(data) + padder.finalize() encryptor = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor() return encryptor.update(padded) + encryptor.finalize()def sha256_b64(data: bytes) -> str: return base64.b64encode(hashlib.sha256(data).digest()).decode()xml = open("invoice.xml", "rb").read()encrypted = aes_cbc(xml)sent = requests.post(f"{API}/sessions/online/{session_ref}/invoices", headers=access, json={ "invoiceHash": sha256_b64(xml), "invoiceSize": len(xml), "encryptedInvoiceHash": sha256_b64(encrypted), "encryptedInvoiceSize": len(encrypted), "encryptedInvoiceContent": base64.b64encode(encrypted).decode(),}, timeout=60)sent.raise_for_status() # 202 Acceptedinvoice_ref = sent.json()["referenceNumber"]
07

Collect the KSeF number

You check the invoice status with GET /sessions/{ref}/invoices/{invoiceRef}. Codes 100 and 150 mean processing, 200 is success with the ksefNumber field. Code 440 is a duplicate: the same file was accepted before, and its number is in extensions.originalKsefNumber.

Treat a duplicate as success. That is how you recover a send that timed out after KSeF had already taken it.

ksef.py
while True: invoice = requests.get(f"{API}/sessions/{session_ref}/invoices/{invoice_ref}", headers=access, timeout=30).json() code = invoice["status"]["code"] if code == 200: print("KSeF number:", invoice["ksefNumber"]) break if code == 440: # duplicate: the same file was accepted before print("Already accepted:", invoice["status"]["extensions"]["originalKsefNumber"]) break if code not in (100, 150): raise RuntimeError(invoice["status"]) # 430, 435, 450... time.sleep(2)
08

Close the session and download the UPO

POST /sessions/online/{ref}/close closes the session (204). The collective UPO appears in GET /sessions/{ref} under upo.pages with download addresses. A single invoice also has its own upoDownloadUrl in its status.

ksef.py
requests.post(f"{API}/sessions/online/{session_ref}/close", headers=access, timeout=30).raise_for_status() # 204while True: session = requests.get(f"{API}/sessions/{session_ref}", headers=access, timeout=30).json() pages = (session.get("upo") or {}).get("pages") or [] if pages: for page in pages: upo = requests.get(page["downloadUrl"], timeout=60) open(f"upo-{page['referenceNumber']}.xml", "wb").write(upo.content) break time.sleep(5)

How to check it works

We ran steps 1 to 4 on TEST with a deliberately fake token. The server accepted the request (202) and the operation status came back with code 450, "Invalid token encoding". That confirms the address, the challenge and the request format: with a real token you get 200 at this point.

Environment
Ministry of Finance TEST environment
Result
Request accepted (202) and the deliberately fake token rejected with code 450

What you should see

  • The authentication status comes back as 200 and redeem returns an accessToken and a refreshToken.
  • Opening the session returns 201 and a session number.
  • The invoice status moves through 100 or 150 to 200 and carries a ksefNumber.
  • After closing the session, upo.pages holds the address of the collective UPO.
python ksef.py (TEST)
Command
python ksef.py
Output
challenge 20261006-CR-2B26197000-FA464AB39C-AE timestampMs 1791290044823init 202 referenceNumber 20261006-AU-2B262EC000-FA4D7212F7-50status 450 Uwierzytelnianie zakończone niepowodzeniem z powodu błędnego tokenu details: Nieprawidłowe kodowanie tokenu.
  1. 2-3
    The challenge and its timestamp

    POST /auth/challenge returns a one-time challenge and timestampMs. That field, not timestamp, goes into the token encryption.

  2. 4-5
    Request accepted

    The server answered 202 with the operation reference number: the encrypted token, the challenge and the context are in the right format.

  3. 6-9
    The fake token rejected

    Code 450 is the expected result for a deliberately fake token. The Polish message in the output reads "Authentication failed because of an invalid token. Invalid token encoding." With a real token you get 200 at this point.

How Flaem sends it

How it looks in our project

At Flaem the same flow runs in Rust. The key decision is not about encryption: issuing an invoice never waits for KSeF. The document is written together with a queue entry, and a separate process does the sending.

One invoice reaches KSeF once. Three layers guard that: the queue's primary key on the document id, a row lock when the worker claims it, and KSeF's own deduplication by file hash, status 440, which the worker records as success.

See the project
A company panel with the KSeF invoice queue and the run of one send
the KSeF integration we build for companies: the invoice queue and the sending run of this guide, from the challenge to the UPO
client.rs
pub async fn open_session(&self, access: &str) -> Result<Session, ClientError> { let key = self.public_key("SymmetricKeyEncryption").await?; let mut symmetric = [0u8; 32]; let mut iv = [0u8; 16]; rand_core::OsRng.fill_bytes(&mut symmetric); rand_core::OsRng.fill_bytes(&mut iv); let wrapped = encrypt_rsa(&key.key, &symmetric)?; let opened: Opened = self .post_json("/sessions/online", Some(access), Some(serde_json::json!({ "formCode": { "systemCode": "FA (3)", "schemaVersion": "1-0E", "value": "FA" }, "encryption": { "encryptedSymmetricKey": BASE64.encode(&wrapped), "initializationVector": BASE64.encode(iv), "publicKeyId": key.id, }, }))) .await?; Ok(Session { reference_number: opened.reference_number, symmetric, iv })}

Common errors

Symptom, cause and fix, with the number of the step where the error shows up.

StepSymptomCauseFix
03 Status 450, "invalid token time" or "invalid challenge" The token was encrypted with timestamp instead of timestampMs, or the challenge is older than 10 minutes. Fetch a new challenge right before encrypting and use timestampMs.
04 Status 415, no permissions assigned The token lacks the InvoiceWrite permission. Generate a new token with InvoiceWrite. An existing token's permissions cannot be changed.
06 Invoice status 435, file decryption error A different key or IV than when the session was opened, no PKCS#7 padding, or the IV glued to the content. Encrypt with the key and IV of the same session and send the ciphertext alone.
07 Invoice status 430 or 450 The XML fails the FA(3) schema or its semantics, for example a wrong field or element order. Validate the file locally against the FA(3) XSD before sending; elements are an xsd:sequence, so order matters.
04 A second redeem fails An authentication token can be redeemed for an access token only once. Keep the refreshToken and renew access with /auth/token/refresh.

Frequently asked questions

The questions that come up with this setup.

Since when is KSeF mandatory?
Since 1 February 2026 for companies whose 2024 sales including tax exceeded PLN 200 million, and since 1 April 2026 for the rest. From 1 January 2027 it also covers the smallest companies, whose invoiced sales do not exceed PLN 10,000 a month and which may still issue invoices outside KSeF until the end of 2026.
A KSeF token or a certificate?
Both are full authentication methods. A token is simpler to integrate because it needs no XAdES signature on every login, but generating it requires one signature-based login.
Can I test with real company data?
No. The Ministry's documentation explicitly forbids real invoices and data on TEST and DEMO. On TEST data is not isolated, because many integrators can act in the context of the same tax ID (NIP).
What if KSeF is down when the invoice is issued?
Issuing an invoice should not depend on KSeF being up. We store the invoice and send it from a background queue. The rules for late sending and the fallback modes are covered by the Ministry's separate documentation on offline mode.
How much does a KSeF API integration cost?
We quote a KSeF integration as part of our API integration service, from PLN 999 (about EUR 220). The final amount depends on the system the invoices come from and on the number of edge cases.
How long does it take to connect your own system to KSeF?
Usually 2-3 days for the API integration itself: authentication, session, encryption, sending and collecting the UPO. Adapting the invoicing system the invoices come from takes longer.
Do you need a qualified signature for the KSeF API?
Not for day-to-day sending: a KSeF token is enough. To generate it you authenticate once with an XAdES signature; on TEST a self-signed certificate is enough.

Sources

The documentation and specifications we compared the commands with.

Other guides

  • Przelewy24 REST APIRegistering a transaction, the SHA-384 sign, the notification and verifying the payment in PHP.

Glossary terms

Tell us what you want to build.

A free quote comes back within an hour during working hours. You talk to the person who writes the code.