shevelinski/klix-php-sdk

A PHP SDK for the Klix Public REST API

Installs: 2

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Forks: 0

pkg:composer/shevelinski/klix-php-sdk

v1.0.0 2025-09-30 19:40 UTC

This package is auto-updated.

Last update: 2025-12-30 17:47:46 UTC


README

Klix PHP SDK

alt text

alt text

alt text

A comprehensive, fluent PHP SDK for the official Klix Public REST API. This package provides a clean, object-oriented interface for all API resources, handling authentication, HTTP requests, and errors, so you can focus on your application's business logic.

Installation Install the package via Composer:

composer require shevelinski/klix-php-sdk

Quick Start: Create Your First Payment This example shows the most common use case: creating a payment link and redirecting the user to it.

require 'vendor/autoload.php';

use Klix\Api\ApiClient;
use Klix\Api\Exceptions\ApiException;

// 1. Initialize the client with your secret API key
$klixClient = new ApiClient('YOUR_SECRET_API_KEY');

// 2. Prepare the purchase data
$purchaseData = [
    'brand_id' => 'YOUR_BRAND_ID',
    'client' => [
        'email' => 'customer@example.com',
        'full_name' => 'John Doe',
    ],
    'purchase' => [
        'currency' => 'EUR',
        'products' => [
            'name' => 'Awesome T-Shirt',
            'price' => 2500, // 25.00 EUR in minor units (cents)
            'quantity' => 1
       ]
    ],

    // URLs where the user will be sent after payment
    'success_redirect' => 'https://yoursite.com/payment/success',
    'failure_redirect' => 'https://yoursite.com/payment/failure',
];
// 3. Create the purchase and redirect the user
try {
$newPurchase = $klixClient->purchases->create($purchaseData);
//Redirect the user to the Klix checkout page
header('Location: ' . $newPurchase['checkout_url']);
exit();

} catch (ApiException $e) {
// If something goes wrong, log the error and inform the user.
error_log("Klix API Error: " . json_encode($e->getErrorDetails()));
die('Could not create payment. Please try again later.');
}

Core Concepts

  1. Client Initialization All interactions start by creating an ApiClient instance.

     use Klix\Api\ApiClient;
    
     $apiKey = 'YOUR_SECRET_API_KEY';
     $klixClient = new ApiClient($apiKey);
    
  2. Accessing Resources The client provides access to API endpoint groups through properties.

     // Work with purchases
     $klixClient->purchases->get($purchaseId);
    
    // Work with clients
    $klixClient->clients->create($clientData);
    
    // Work with subscriptions and invoices
    $klixClient->billing->createTemplate($templateData);
    
  3. Error Handling The SDK throws a Klix\Api\Exceptions\ApiException when the API returns an error. Always wrap API calls in a try...catch block.

    use Klix\Api\Exceptions\ApiException;
    
    try {
        $purchase = $klixClient->purchases->get('non-existent-id');
    } catch (ApiException $e) {
        echo "An API error occurred!\n";
        echo "HTTP Status Code: " . $e->getCode() . "\n";
    
        // Get structured error details from Klix
        $details = $e->getErrorDetails();
        if ($details) {
            echo "API Details: " . json_encode($details, JSON_PRETTY_PRINT) . "\n";
        }
    }
    

Advanced Usage Examples

  1. Creating a Monthly Subscription

    try {
        // Step 1: Create a client (or find an existing one)
        $customer = $klixClient->clients->create([
            'email' => 'subscriber@example.com',
            'full_name' => 'Jane Subscriber'
        ]);
    
        // Step 2: Create a monthly subscription template
        $templateData = [
            'is_subscription' => true,
            'title' => 'Monthly Pro Plan Subscription',
            'brand_id' => 'YOUR_BRAND_ID',
            'subscription_period' => 1,
            'subscription_period_units' => 'months', // 'days', 'weeks', or 'months'
            'purchase' => [
                'currency' => 'EUR',
                'products' => [['name' => 'Pro Plan', 'price' => 1000, 'quantity' => 1]]
            ]
        ];
        $template = $klixClient->billing->createTemplate($templateData);
    
        // Step 3: Add the client as a subscriber to the template
        $subscription = $klixClient->billing->addSubscriber($template['id'], [
            'client_id' => $customer['id']
        ]);
    
        echo "Client subscribed successfully!\n";
    
        // If the subscription requires immediate payment, redirect the user.
        if (!empty($subscription['purchase'])) {
            header('Location: ' . $subscription['purchase']['checkout_url']);
            exit();
        }
    
    } catch (ApiException $e) {
        echo "Error creating subscription: " . json_encode($e->getErrorDetails()) . "\n";
    }
    
  2. Verifying Incoming Webhook Signatures This is a critical security step. You must verify every incoming request from Klix to ensure it is authentic.

    // Your webhook endpoint (e.g., /api/klix-webhook.php)
    
    // 1. Get the public key. You get this when you create the webhook. Store it securely.
    $publicKey = '-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----';
    
    // 2. Get the request data
    $requestBody = file_get_contents('php://input');
    $signatureHeader = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
    
    if (empty($signatureHeader) || empty($requestBody)) {
        http_response_code(400); // Bad Request
        exit();
    }
    
    // 3. Use the validator to check the signature
    $isVerified = $klixClient->webhookValidator->isValid(
        $publicKey,
        base64_decode($signatureHeader), // The signature is Base64 encoded
        $requestBody
    );
    
    if ($isVerified) {
        // Signature is valid. You can trust the data.
        $event = json_decode($requestBody, true);
    
        // Process the event based on its type
        if ($event['event_type'] === 'purchase.paid') {
            $purchaseId = $event['id'];
            // TODO: Update the order status in your database to "paid".
        }
    
        // Respond with a 200 OK status to acknowledge receipt
        http_response_code(200);
        echo 'OK';
    
    } else {
        // Signature is invalid! The request may be forged.
        // Log this security event and do not process it.
        error_log('Invalid Klix webhook signature received!');
        http_response_code(403); // Forbidden
        exit();
    }
    

API Coverage

The SDK provides full coverage of the Klix API via the following resource properties.

$klixClient->purchases
$klixClient->clients
$klixClient->billing
$klixClient->webhooks
$klixClient->statements
$klixClient->utils (for payment_methods, public_key, etc.)

License The MIT License (MIT). Please see the LICENSE file for more information.