PHP code example of naprawksef / sdk

1. Go to this page and download the library: Download naprawksef/sdk 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/ */

    

naprawksef / sdk example snippets




use NaprawKsef\Sdk\NaprawKsef;
use NaprawKsef\Sdk\Exceptions\RateLimitException;
use NaprawKsef\Sdk\Exceptions\ValidationException;

.2',         // optional, attached to User-Agent
]);

// 1. Who am I?
$me = $client->me->retrieve();
echo $me['organization']['name'], PHP_EOL;

// 2. Validate a KSeF XML
$xml = file_get_contents('invoice.xml');
try {
    $result = $client->validate->run($xml, filename: 'invoice.xml');
    if (!$result['valid']) {
        foreach ($result['issues'] as $issue) {
            printf("[%s] %s → %s\n", $issue['severity'], $issue['code'], $issue['message']);
        }
    }
} catch (RateLimitException $e) {
    printf("Throttled. Wait %d seconds.\n", $e->retryAfterSeconds() ?? 60);
} catch (ValidationException $e) {
    printf("Bad input: %s (%s)\n", $e->getMessage(), $e->code);
}

// 3. Analyse for FA(3) correction scenarios
$analysis = $client->correction->analyze($xml);
print_r($analysis['suggestions']); // top 5 scenarios with confidence

$client->validate->run(
    xml: $xml,
    idempotencyKey: "invoice-{$invoice->id}-v3",
);

use NaprawKsef\Sdk\Exceptions\{
    NaprawKsefException,
    AuthException,
    ForbiddenException,
    NotFoundException,
    ValidationException,
    RateLimitException,
    IdempotencyConflictException,
    ServerException,
    NetworkException,
};



use NaprawKsef\Sdk\Webhooks\SignatureVerifier;

= $_SERVER['HTTP_X_NK_SIGNATURE'] ?? null;

$result = SignatureVerifier::verify(
    secret: $_ENV['NAPRAW_KSEF_WEBHOOK_SECRET'],
    rawBody: $rawBody,
    header: $header,
);

if (!$result['ok']) {
    http_response_code(401);
    exit('Invalid signature: ' . $result['reason']);
}

$event = json_decode($rawBody, true);
// handle $event['type'] (e.g. "validation.completed")

http_response_code(200);
echo 'ok';

public function __invoke(Request $request)
{
    $result = SignatureVerifier::verify(
        secret: config('services.naprawksef.webhook_secret'),
        rawBody: $request->getContent(),
        header: $request->header('X-NK-Signature'),
    );

    abort_if(!$result['ok'], 401, 'Invalid signature: ' . $result['reason']);

    $event = $request->json()->all();
    // …

    return response('ok');
}

$client = new NaprawKsef([
    'api_key' => $apiKey,
    'max_retries' => 0, // disable retries
    'timeout_ms' => 60_000, // longer per-request timeout
]);