PHP code example of labapawel / ksef-api

1. Go to this page and download the library: Download labapawel/ksef-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

labapawel / ksef-api example snippets


use Labapawel\KsefApi\Models\KsefEnvironment;

// Pobierz środowisko po identyfikatorze
$demo = KsefEnvironment::findByEnvironment('demo');

// Pobierz tylko aktywne środowiska
$active = KsefEnvironment::active()->get();

// Dostęp do danych
echo $demo->api_url;  // https://api-demo.ksef.mf.gov.pl/v2

$this->call(KsefEnvironmentSeeder::class);

KsefEnvironment::create([
    'environment' => 'staging',
    'api_url' => 'https://api-staging.ksef.mf.gov.pl/v2',
    'description' => 'Środowisko staging',
    'is_active' => true,
]);

use Labapawel\KsefApi\Models\Credential;
use Labapawel\KsefApi\Models\KsefEnvironment;

// Pobierz środowisko
$demo = KsefEnvironment::findByEnvironment('demo');

// Utwórz poświadczenia dla tego środowiska
Credential::create([
    'ksef_environment_id' => $demo->id,  // Foreign key do środowiska
    'nip' => '1234567890',
    'certificate_encrypted' => $certificatePem,
    'private_key_encrypted' => $privateKeyPem,
    'certificate_password_encrypted' => $certificatePassword,
]);

// Lub szybciej — korzystając ze scope
$cred = Credential::forEnvironmentAndNip('demo', '1234567890')->first();
echo $cred->environment->api_url;  // https://api-demo.ksef.mf.gov.pl/v2

use Labapawel\KsefApi\Services\AuthenticationService;

$auth = new AuthenticationService();

// Zaloguj się (pobiera certyfikat z bazy)
$response = $auth->login(
    nip: '1234567890',
    environment: 'demo' // opcjonalnie, domyślnie z konfigu
);

// Sprawdź czy poświadczenia są ważne
if ($auth->hasValidCredentials('1234567890')) {
    $token = $auth->getAccessToken('1234567890');
    // Użyj token do żądań API
}

// Wyloguj się (usuń poświadczenia)
$auth->logout('1234567890');

use Labapawel\KsefApi\Clients\KsefAuthClient;
use Labapawel\KsefApi\DTO\Credentials;

$client = new KsefAuthClient();

$credentials = new Credentials(
    nip: '1234567890',
    ksefToken: '',
    certificatePath: '/path/to/cert.pem',
    privateKeyPath: '/path/to/key.pem',
    certificatePassword: 'hasło123',
);

$authResponse = $client->authenticate($credentials, '1234567890', 'demo');

// $authResponse zawiera:
// - challengeToken (tymczasowy)
// - accessToken (JWT)
// - refreshToken (JWT)
// - tokenExpiresAt (Carbon)
// - challengeTokenReceivedAt (Carbon)

use Labapawel\KsefApi\Models\Credential;

// Pobierz poświadczenia
$credential = Credential::forEnvironmentAndNip('demo', '1234567890')->first();

// Dostęp do tokenów (automatyczne deszyfrowanie)
$challengeToken = $credential->ksef_token_encrypted;
$accessToken = $credential->access_token_encrypted;
$refreshToken = $credential->refresh_token_encrypted;

// Sprawdź ważność access tokena
if ($credential->isTokenValid()) {
    // Access token nie wygasł
}

if ($credential->isTokenExpired()) {
    // Access token wygasł, wymagane odświeżenie
}

// Sprawdź ważność challenge tokena
if ($credential->isChallengeTokenValid()) {
    // Challenge token jest jeszcze ważny
}

if ($credential->isChallengeTokenExpired()) {
    // Challenge token wygasł, wymagany nowy
}

// Lifecycle timestamps
$challengeReceivedAt = $credential->challenge_token_received_at;
$challengeExpiresAt = $credential->challenge_token_expires_at;
$accessExpiresAt = $credential->token_expires_at;

use Labapawel\KsefApi\Models\KsefEnvironment;

// Pobierz środowisko
$demo = KsefEnvironment::findByEnvironment('demo');
$prod = KsefEnvironment::findActiveByEnvironment('prod');

// Dostępne scopes
KsefEnvironment::active()->get();                    // tylko aktywne
KsefEnvironment::byEnvironment('demo')->first();     // po ID

// Dostęp do danych
echo $demo->api_url;        // https://api-demo.ksef.mf.gov.pl/v2

// Relacja do poświadczeń
$credentials = $demo->credentials()->get();  // wszystkie kredencje dla demo

use Labapawel\KsefApi\Models\Credential;

// Szukaj poświadczeń (nowe podejście — przez string environment)
$credential = Credential::forEnvironmentAndNip('demo', '1234567890')
    ->withCertificate()
    ->orderByDesc('updated_at')
    ->first();

// Lub przez ID środowiska (szybciej)
$envId = KsefEnvironment::findByEnvironment('demo')->id;
$credential = Credential::forEnvironmentIdAndNip($envId, '1234567890')
    ->withCertificate()
    ->orderByDesc('updated_at')
    ->first();

// Dostępne scopes
Credential::environment('demo')->get();                          // legacy
Credential::nip('1234567890')->get();
Credential::forEnvironmentAndNip('demo', '1234567890')->get();   // ze string environment
Credential::forEnvironmentIdAndNip($envId, '1234567890')->get(); // z foreign key (szybciej)
Credential::forEnvironmentId($envId)->get();                     // wszystkie kredencje dla środowiska
Credential::withCertificate()->get();                            // z kompletnym certyfikatem
Credential::validToken()->get();                                 // z ważnym access tokenem
Credential::validChallengeToken()->get();                        // z ważnym challenge tokenem

// Relacja do środowiska
echo $credential->environment->api_url;

// Sprawdzenie ważności access tokena
if ($credential->isTokenValid()) {
    // access token jest jeszcze ważny
}

if ($credential->isTokenExpired()) {
    // access token wygasł, wymagane odświeżenie
}

// Sprawdzenie ważności challenge tokena
if ($credential->isChallengeTokenValid()) {
    // challenge token jest jeszcze ważny
}

if ($credential->isChallengeTokenExpired()) {
    // challenge token wygasł, wymagany nowy
}

use Labapawel\KsefApi\Models\Invoice;

// Szukaj faktur
$invoices = Invoice::sale()->accepted()->get();
$outgoing = Invoice::direction('sale')->sellerNip('7986711699')->get();
$income = Invoice::purchase()->pending()->get();

// Dostępne scopes
Invoice::direction('sale')->get();                 // sale | purchase
Invoice::sale()->get();                            // alias dla sale direction
Invoice::purchase()->get();                        // alias dla purchase direction
Invoice::status('accepted')->get();                // pending|processing|accepted|rejected
Invoice::pending()->get();                         // oczekujące
Invoice::processing()->get();                      // w trakcie przetwarzania
Invoice::accepted()->get();                        // zaakceptowane
Invoice::rejected()->get();                        // odrzucone
Invoice::sellerNip('7986711699')->get();          // po NIP sprzedawcy
Invoice::buyerNip('5471740555')->get();           // po NIP nabywcy
Invoice::ksefNumber('20260303-EE-3FAFFEF000')->get(); // po numerze KSeF

// Metody sprawdzające status
if ($invoice->isAccepted()) {
    // Faktura została zaakceptowana
}

if ($invoice->isRejected()) {
    // Faktura została odrzucona
}

if ($invoice->isPending()) {
    // Faktura czeka na przetwarzanie
}

if ($invoice->isProcessed()) {
    // Faktura została przetworzona przez KSeF
}

// Zapis — dane są automatycznie szyfrowane
$credential = Credential::create([
    'environment' => 'demo',
    'nip' => '1234567890',
    'access_token_encrypted' => 'secret_token_value', // będzie zaszyfrowany
]);

// Odczyt — dane są automatycznie deszyfrowane
echo $credential->access_token_encrypted; // wyświetli zdeszyfowany token

use Labapawel\KsefApi\Models\Credential;

// Zapisz poświadczenia dla danego środowiska i NIP
Credential::create([
    'environment' => 'demo',
    'nip' => '7986711699',
    'access_token_encrypted' => $token,
    'refresh_token_encrypted' => $refreshToken,
    'certificate_encrypted' => $certPem,
    'private_key_encrypted' => $privateKeyPem,
    'certificate_password_encrypted' => $certPassword,
    'token_expires_at' => now()->addHours(24),
    'meta' => ['issuer' => 'mf.gov.pl'],
]);

// Pobierz późno poświadczenia
$cred = Credential::forEnvironmentAndNip('demo', '7986711699')->firstOrFail();

// Sprawdź czy token nie wygasł
if ($cred->isTokenExpired()) {
    // Odśwież token tutaj
}

use Labapawel\KsefApi\Models\Invoice;

Invoice::create([
    'direction' => 'sale',                           // sale lub purchase
    'invoice_number' => 'TEST/2026/03/03/001',
    'invoice_date' => '2026-03-03',
    'seller_nip' => '7986711699',
    'seller_name' => 'Moja Firma Sp. z o.o.',
    'buyer_nip' => '5471740555',
    'buyer_name' => 'Odbiorca Sp. z o.o.',
    'xml_encrypted' => $xmlContent,                  // będzie zaszyfrowany
    'xml_hash' => hash('sha256', $xmlContent),
    'status' => 'pending',
    'meta' => [
        'gross_amount' => 1234.56,
        'tax_amount' => 286.66,
        'net_amount' => 947.90,
        'line_items_count' => 2,
    ],
]);

// Wszystkie zatwierdzone faktury sprzedane w marcu 2026
$invoices = Invoice::sale()
    ->accepted()
    ->whereMonth('invoice_date', 3)
    ->whereYear('invoice_date', 2026)
    ->get();

// Faktury niezgodnie oczekujące na przetwarzanie od danego sprzedawcy
$pending = Invoice::pending()
    ->sellerNip('7986711699')
    ->orderBy('created_at', 'desc')
    ->get();

use Labapawel\KsefApi\Tests\Fixtures\DataFactory;

// Utwórz jedno poświadczenie
$credential = DataFactory::createCredential();

// Utwórz kilka poświadczeń dla środowiska demo
$credentials = DataFactory::createCredentials(5, 'demo');

// Utwórz jedną fakturę
$invoice = DataFactory::createInvoice();

// Utwórz zaakceptowaną fakturę
$acceptedInvoice = DataFactory::createInvoice(['status' => 'accepted']);

// Utwórz fakturę dla konkretnego sprzedawcy
$sellerInvoice = DataFactory::createInvoice([
    'seller_nip' => '7986711699',
    'seller_name' => 'Acme Corp',
]);

use Labapawel\KsefApi\Models\KsefEnvironment;
use Labapawel\KsefApi\Models\Credential;

// Pobierz środowisko
$env = KsefEnvironment::findByEnvironment('demo');

// Wczytaj certyfikat z pliku
$cert = file_get_contents('/path/to/cert.pem');
$key = file_get_contents('/path/to/key.pem');

// Utwórz nowe poświadczenia
Credential::create([
    'ksef_environment_id' => $env->id,
    'nip' => '1234567890',
    'certificate_encrypted' => $cert,
    'private_key_encrypted' => $key,
    'certificate_password_encrypted' => 'hasło_do_certyfikatu',
]);

// src/Clients/KsefAuthClient.php - zmodyfikuj constructor
$this->httpClient = new Client([
    'timeout' => $timeout,
    'verify' => true, // Włącz weryfikację
    'cert' => ['/path/to/ca-bundle.crt'], // Ścieżka do CA bundle
]);

// Zamiast create() — użyj firstOrCreate()
Credential::firstOrCreate(
    [
        'ksef_environment_id' => $env->id,
        'nip' => '1234567890',
    ],
    [
        'certificate_encrypted' => $cert,
        'private_key_encrypted' => $key,
        'certificate_password_encrypted' => $password,
    ]
);

$cred = Credential::with('ksefEnvironment')->find($id);
echo $cred->environment->api_url; // Pobranie URL z KsefEnvironment

Credential::all()->each(function($cred) {
    $env = KsefEnvironment::byEnvironment($cred->environment)->first();
    if($env) {
        $cred->update(['ksef_environment_id' => $env->id]);
    }
});
bash
php artisan vendor:publish --tag=ksef-config
bash
# Publikacja migracji
php artisan vendor:publish --tag=ksef-migrations
php artisan migrate

# Publikacja seeders (opcjonalnie)
php artisan vendor:publish --tag=ksef-seeders
bash
php artisan db:seed --class="Labapawel\KsefApi\Database\Seeders\KsefEnvironmentSeeder"
bash
php artisan db:seed --class="KsefEnvironmentSeeder"
bash
php artisan key:generate
bash
php artisan db:seed --class=Labapawel\\KsefApi\\Database\\Seeders\\KsefEnvironmentSeeder
bash
composer install
composer dump-autoload

┌─────────────────────────────────────────────────────────┐
│ Warstwa aplikacji (Laravel Controller/Service)          │
└──────────────────────┬──────────────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────────────┐
│ Services (High-level API)                               │
│ - AuthenticationService.php                             │
└──────────────────────┬──────────────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────────────┐
│ Repositories (Business Logic)                           │
│ - CredentialRepository.php                              │
│ - InvoiceRepository.php                                 │
└──────────────────────┬──────────────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────────────┐
│ Models (Eloquent ORM)                                    │
│ - KsefEnvironment.php / Credential.php / Invoice.php   │
└──────────────────────┬──────────────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────────────┐
│ Clients (HTTP Communication)                            │
│ - KsefAuthClient.php (Authentication)                   │
│ - KsefInvoiceClient.php (Invoice Operations)            │
└──────────────────────┬──────────────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────────────┐
│ KSeF REST API                                            │
│ https://api-demo.ksef.mf.gov.pl/v2                      │
└─────────────────────────────────────────────────────────┘