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.1 (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.4.0.tar.gz (65.7 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.4.0-py3-none-any.whl (49.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: ksef_client-0.4.0.tar.gz
  • Upload date:
  • Size: 65.7 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.4.0.tar.gz
Algorithm Hash digest
SHA256 c4f62810183aa2d9c6cae8fabc54c021835e35d4b627a5fc8ebc3c58c79b9be2
MD5 47377bbba72daf897ba9e5d3b784ece6
BLAKE2b-256 e5a94601e0e6eb8c9a097b75539c13dcc20890f9a866ccfd5bdaae2ac35acd39

See more details on using hashes here.

Provenance

The following attestation bundles were made for ksef_client-0.4.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.4.0-py3-none-any.whl.

File metadata

  • Download URL: ksef_client-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 49.7 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.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bf04267c7711e19fc309fc28e313a8c1a6e7f3082c39d57fa922ff56662c7e33
MD5 1361b38ea19d81a63b4db0a7baa12570
BLAKE2b-256 39947fc9f60f0408018698c22d91193882b5aea801d7df56b0a18ab53734cf49

See more details on using hashes here.

Provenance

The following attestation bundles were made for ksef_client-0.4.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