Skip to main content

Client SDK for KSeF API v2

Project description

KSeF Client (Python)

CI PyPI - License PyPI - Version

ksef-client-python jest repozytorium biblioteki (SDK) publikowanej na PyPI jako ksef-client (import: ksef_client).

SDK zostało zaprojektowane w oparciu o oficjalne biblioteki referencyjne KSeF dla ekosystemów Java oraz C#/.NET, z naciskiem na zachowanie spójności pojęć oraz przepływów (workflow).

🔄 Kompatybilność API KSeF

Aktualna kompatybilność: KSeF API v2.1.2 (api-changelog.md).

✅ Funkcjonalności

  • Klienci API (KsefClient, AsyncKsefClient) mapujący wywołania na endpointy KSeF.
  • Uwierzytelnianie tokenem KSeF oraz podpisem XAdES (w tym XadesKeyPair dla PKCS#12 lub zestawu PEM+hasło).
  • Sesje wysyłkowe: online (pojedyncze faktury) oraz batch (ZIP, party, pre-signed URL).
  • Eksport i pobieranie paczek faktur (pre-signed URL) wraz z odszyfrowaniem i rozpakowaniem.
  • Narzędzia kryptograficzne i pomocnicze (AES/ZIP/Base64Url, linki weryfikacyjne, QR).

📦 Instalacja

Wymagania: Python >= 3.10.

Instalacja z PyPI:

pip install ksef-client

Opcjonalne dodatki (extras):

pip install "ksef-client[xml,qr]"
  • xml – podpis XAdES (lxml, xmlsec)
  • qr – generowanie PNG z kodami QR (qrcode, pillow)

📚 Dokumentacja

Dokumentacja SDK znajduje się w katalogu docs/:

🚀 Quick start

Minimalny przebieg integracji obejmuje:

  • uzyskanie access_token (token KSeF albo XAdES),
  • wykonanie wywołania API, np. wyszukiwania metadanych faktur.
from ksef_client import KsefClient, KsefClientOptions, KsefEnvironment
from ksef_client.services.workflows import AuthCoordinator

with KsefClient(KsefClientOptions(base_url=KsefEnvironment.DEMO.value)) as client:
    token_cert_pem = ...  # usage: KsefTokenEncryption (client.security.get_public_key_certificates)
    access_token = AuthCoordinator(client.auth).authenticate_with_ksef_token(
        token=KSEF_TOKEN,
        public_certificate=token_cert_pem,
        context_identifier_type="nip",
        context_identifier_value="5265877635",
    ).tokens.access_token.token

    metadata = client.invoices.query_invoice_metadata(
        {...}, access_token=access_token, page_offset=0, page_size=10, sort_order="Desc"
    )

🔐 Najważniejsze snippety

Fragmenty pokazują kluczowe wywołania. Pełne, uruchamialne przykłady znajdują się w docs/examples/.

Autoryzacja tokenem KSeF

token_cert_pem = ...  # usage: KsefTokenEncryption
tokens = AuthCoordinator(client.auth).authenticate_with_ksef_token(
    token=KSEF_TOKEN,
    public_certificate=token_cert_pem,
    context_identifier_type="nip",
    context_identifier_value="5265877635",
).tokens

Autoryzacja certyfikatem (XAdES)

Wymaga dodatku xml: pip install "ksef-client[xml]".

from ksef_client.services import XadesKeyPair

key_pair = XadesKeyPair.from_pkcs12_file(pkcs12_path="cert.p12", pkcs12_password="***")
tokens = AuthCoordinator(client.auth).authenticate_with_xades_key_pair(
    key_pair=key_pair,
    context_identifier_type="nip",
    context_identifier_value="5265877635",
    subject_identifier_type="certificateSubject",
    enforce_xades_compliance=False,  # ustaw True, aby dodać X-KSeF-Feature: enforce-xades-compliance
).tokens

Listowanie faktur (metadane)

metadata = client.invoices.query_invoice_metadata(
    {...}, access_token=access_token, page_offset=0, page_size=10, sort_order="Desc"
)

Wysyłka faktury (sesja online, FA(3) XML)

Wywołanie zakłada, że dostępne są session_reference_number oraz encryption_data (utworzone przy otwarciu sesji online).

from ksef_client.services.workflows import OnlineSessionWorkflow

send_result = OnlineSessionWorkflow(client.sessions).send_invoice(
    session_reference_number=session_reference_number,
    invoice_xml=invoice_xml_fa3_bytes,
    encryption_data=encryption_data,
    access_token=access_token,
)

Wysyłka wsadowa (batch, ZIP z wieloma XML)

Wywołanie zakłada dostępność zip_bytes (ZIP z wieloma plikami XML faktur) oraz certyfikatu KSeF do szyfrowania klucza symetrycznego (SymmetricKeyEncryption).

from ksef_client.services.workflows import BatchSessionWorkflow

session_reference_number = BatchSessionWorkflow(client.sessions, client.http_client).open_upload_and_close(
    form_code={"systemCode": "FA (3)", "schemaVersion": "1-0E", "value": "FA"},
    zip_bytes=zip_bytes,
    public_certificate=symmetric_cert_pem,  # usage: SymmetricKeyEncryption
    access_token=access_token,
    parallelism=4,
)

🧪 Testy

Python E2E TEST token Python E2E TEST cert Python E2E DEMO token Python E2E DEMO cert

Testy uruchamiane są przez pytest.

Instalacja zależności testowych:

pip install -r requirements-dev.txt

Uruchomienie testów:

pytest

Uruchomienie testów z kontrolą pokrycia:

pytest --cov=ksef_client --cov-report=term-missing --cov-fail-under=100

Testy E2E (marker e2e) są wyłączone w standardowym przebiegu i wymagają osobnej konfiguracji środowiska oraz danych dostępowych.

Scenariusz E2E obejmuje:

  • logowanie tokenem KSeF,
  • logowanie certyfikatem (XAdES),
  • wystawienie faktury,
  • pobranie UPO,
  • listowanie faktur,
  • pobranie ostatniej faktury.

Plik testów E2E:

  • tests/test_e2e_token_flows.py

Dostępne testy:

  • test_e2e_test_environment_full_flow_token
  • test_e2e_test_environment_full_flow_xades
  • test_e2e_demo_environment_full_flow_token
  • test_e2e_demo_environment_full_flow_xades

Lokalne uruchomienie (token, TEST):

KSEF_E2E=1 \
KSEF_TEST_TOKEN=... \
KSEF_TEST_CONTEXT_TYPE=nip \
KSEF_TEST_CONTEXT_VALUE=... \
pytest tests/test_e2e_token_flows.py::test_e2e_test_environment_full_flow_token

Lokalne uruchomienie (XAdES, TEST):

KSEF_E2E=1 \
KSEF_TEST_CONTEXT_TYPE=nip \
KSEF_TEST_CONTEXT_VALUE=... \
KSEF_TEST_XADES_CERT_CRT="$(cat cert.crt)" \
KSEF_TEST_XADES_PRIVATE_KEY_PEM="$(cat key.pem)" \
KSEF_TEST_XADES_PRIVATE_KEY_PASSWORD=... \
pytest tests/test_e2e_token_flows.py::test_e2e_test_environment_full_flow_xades

🤝 Kontrybucja

Wkład w rozwój projektu przyjmowany jest w formie pull requestów oraz zgłoszeń w Issues. Zalecany przebieg prac:

  • opis problemu lub propozycji zmiany (Issue),
  • implementacja w osobnej gałęzi,
  • dołączenie testów dla zmian zachowania,
  • utrzymanie jakości: pytest oraz pytest --cov=ksef_client --cov-fail-under=100,
  • krótki opis zmian i uzasadnienie w PR.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ksef_client-0.5.0.tar.gz (67.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ksef_client-0.5.0-py3-none-any.whl (50.4 kB view details)

Uploaded Python 3

File details

Details for the file ksef_client-0.5.0.tar.gz.

File metadata

  • Download URL: ksef_client-0.5.0.tar.gz
  • Upload date:
  • Size: 67.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ksef_client-0.5.0.tar.gz
Algorithm Hash digest
SHA256 7a25e003649b97da15d8480b7863a676c1cfbd8be463ec066a1b43daf591422d
MD5 e6d792b7770ef8df343ab5851b080619
BLAKE2b-256 0a8f783ef852533bc790fb09a8e4435ba58fc95b8bcc1858f29eb758f67d8370

See more details on using hashes here.

Provenance

The following attestation bundles were made for ksef_client-0.5.0.tar.gz:

Publisher: publish-pypi.yml on smekcio/ksef-client-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ksef_client-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: ksef_client-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 50.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ksef_client-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0939a9d0d72150e063f106db65ecf884ce5a1ee25e0304138728a4fa360ee335
MD5 efe54f75bd39b4e87bf8a2a9cbd0b917
BLAKE2b-256 075fd6006781d02d4415d5df944acd21b29fa252e8811cc6bc8d453f42360c50

See more details on using hashes here.

Provenance

The following attestation bundles were made for ksef_client-0.5.0-py3-none-any.whl:

Publisher: publish-pypi.yml on smekcio/ksef-client-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page