Search by

nedarta / omnipay-klix

nedarta

Klix payment gateway for Omnipay: redirect checkout, status lookup, refunds and signed webhooks.

Package info

github.com/nedarta/omnipay-klix

pkg:composer/nedarta/omnipay-klix

Statistics

Installs: 8

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 2

v0.3.0 2026-11-28 10:54 UTC

This package is auto-updated.

Last update: 2026-11-28 10:54:54 UTC


README

Latest Version PHP Version License

Omnipay v3 gateway for Klix (by Citadele) hosted checkout.

Supports the redirect purchase flow, status lookup, refunds, capture/release of authorized payments, cancellation, and signed webhook / callback verification. Transport goes through Omnipay's HTTP client; the official klix/klix-sdk-php is available as an optional adapter.

Requirements

  • PHP 8.0 or newer
  • ext-openssl (webhook signature verification)
  • An Omnipay v3 application
  • Optional: klix/klix-sdk-php if you want the SDK transport

Installation

composer require nedarta/omnipay-klix

The SDK is not installed with the package. Add it only if you want KlixSdkClient:

composer require klix/klix-sdk-php

HTTP client and SDK integration

Transport uses Omnipay's own $httpClient, so a PSR-18 client or a mock passed to Omnipay::create() or the Gateway constructor is honoured:

  • Client\HttpClient implements KlixClientInterface over Omnipay\Common\Http\ClientInterface. It sends JSON directly and returns the decoded body, so payloads stay plain arrays and no SDK model can lose fields.
  • Every transport maps errors through Client\ErrorFactory, so the exception shape is identical whichever client you use.

The official SDK is an optional adapter. Install it and pass a KlixSdkClient to reuse the SDK's Guzzle client (timeouts, proxies, handlers):

use Omnipay\Klix\Client\KlixSdkClient;

$gateway->setKlixClient(new KlixSdkClient(
    brandId: $brandId,
    apiKey: $apiKey,
    options: ['timeout' => 15, 'connect_timeout' => 5, 'proxy' => 'http://proxy:3128'],
));

KlixSdkClient reaches into two SDK internals (KlixApi as parent and its protected $client); a compatibility test fails loudly if an SDK upgrade changes either. Nothing else in the package depends on the SDK.

Any custom Omnipay\Klix\Client\KlixClientInterface implementation works too; tests use setKlixClient() with an in-memory double.

Docker

A minimal PHP 8.0 image with git, unzip and Composer is included:

docker build -t omnipay-klix:php80 .
docker run --rm -v "$PWD":/app -w /app omnipay-klix:php80 \
  bash -c 'composer update --prefer-lowest --prefer-stable --no-interaction \
           && vendor/bin/phpunit --testsuite Klix'

On PowerShell use -v "${PWD}:/app". vendor/ and composer.lock are excluded from the build context; dependencies resolve inside the container, so nothing generated there is committed.

Gateway parameters

Parameter Required Description
brandId yes Klix Brand ID
apiKey yes Klix secret key, sent as Authorization: Bearer …
publicKey for notifications PEM used to verify success_callback (and webhook) signatures
webhookPublicKey for webhooks PEM of the webhook pointed at this endpoint; accepted alongside publicKey
testMode no Stored for Omnipay convention. It does not change the endpoint: test vs live is decided by the credentials.
endpoint no Overrides the API base URL (default https://portal.klix.app/api/v1/)
use Omnipay\Omnipay;

$gateway = Omnipay::create('Klix');
$gateway->setBrandId(getenv('KLIX_BRAND_ID'));
$gateway->setApiKey(getenv('KLIX_API_KEY'));
$gateway->setPublicKey(file_get_contents('/path/to/klix-public-key.pem'));

Purchase (redirect)

$response = $gateway->purchase([
    'amount'       => '12.34',            // major units; converted to cents
    'currency'     => 'EUR',
    'description'  => 'Order #1001',
    'transactionId'=> 'ORDER-1001',       // becomes the Klix reference
    'clientEmail'  => 'buyer@example.com',// required by Klix
    'returnUrl'    => 'https://shop.test/klix/return',
    'cancelUrl'    => 'https://shop.test/cart',
    'notifyUrl'    => 'https://shop.test/klix/notify', // Klix success_callback
    'failureUrl'   => 'https://shop.test/klix/failure', // optional; falls back to cancelUrl, then returnUrl
    'pendingUrl'   => 'https://shop.test/klix/pending', // optional; defaults to returnUrl
    // 'pendingRedirectDelay' => 5,        // 0-180 seconds on Klix's waiting screen
    'language'     => 'lv',               // en, et, lt, lv
    // 'paymentMethod' => 'klix',         // restricts the checkout to one method
    // 'skipCapture'   => true,           // authorize only (hold), then capture/release
])->send();

if ($response->isRedirect()) {
    $response->redirect();                // or: header('Location: ' . $response->getRedirectUrl())
}

if (!$response->isSuccessful()) {
    // $response is an ErrorResponse here
    error_log($response->getMessage());
}

Items are optional. When you pass Omnipay items, each item becomes a Klix product and price is converted from major to minor units:

'items' => [
    ['name' => 'T-shirt', 'quantity' => 2, 'price' => '9.50'],
],

The items total must equal amount; a mismatch throws InvalidRequestException rather than letting Klix charge a different total than your application expects.

The Klix purchase id (used as transactionReference) is available via $response->getTransactionReference(). Persist it and use it on return: the redirect URLs are fixed at creation, and Klix has no lookup by reference.

Amounts

Klix stores every amount as an integer in the smallest indivisible currency unit (cents for EUR, none for JPY, thousandths for KWD). amount is passed through Omnipay's getAmountInteger(), so the total is never re-converted.

Item prices are Omnipay major-unit decimals, converted with exact decimal parsing. A line total is computed with integer arithmetic only: whole quantities are multiplied directly, and the sub-unit fraction is split into base-1000 digits before dividing, so no float is involved and the intermediate products stay inside 32-bit integers (a price/quantity pair that would overflow throws InvalidRequestException rather than wrapping). Lines are then summed as integers. Fractional quantities are supported; quantities must be greater than zero and decimal (scientific notation is rejected). The resulting item total must equal amount, otherwise InvalidRequestException is thrown. Half-up per line is the gateway's rule; Klix computes purchase.total server-side, and fractional-quantity rounding has not been observed against the sandbox.

Complete the purchase

Klix redirects the customer back and (optionally) POSTs a signed callback. Confirm the status before fulfilling an order, and re-fetch the purchase rather than trusting the callback snapshot for anything financial:

$response = $gateway->completePurchase([
    'transactionReference' => $purchaseId, // the id you stored after purchase()
])->send();

if ($response->isSuccessful()) {
    // status === 'paid'
} elseif ($response->isPending()) {
    // created, hold, pending_execute, … — wait for the notification or poll again
} elseif ($response->isCancelled()) {
    // cancelled or expired
} elseif ($response->isFailed()) {
    // status === 'error' (declined); see getMessage() / getPaymentErrorCode()
} else {
    // refunded, released, chargeback, … — inspect getStatus()
}

fetchTransaction() performs the same lookup and returns the raw status through getStatus(), getAmountInteger() and getCurrency(). Both responses also expose getTransactionId(), the merchant reference Klix echoes back, so the order can be cross-checked after the return.

Status mapping

Klix status Omnipay
paid isSuccessful()
hold, preauthorized isPending() and isAuthorized() (funds reserved, not captured)
created, sent, viewed, overdue, pending_* isPending()
cancelled, expired isCancelled()
error isFailed()
released, refunded, chargeback none of the above

A hold is a successful authorization, not a payment: isSuccessful() stays false and isAuthorized() is the accessor to branch on before capture() or release().

Webhooks and success callbacks

Klix signs the raw request body with RSA PKCS#1 v1.5 / SHA-256 and sends the base64 signature in X-Signature.

  • success_callback payloads are signed with the company key from GET /api/v1/public_key/.
  • Webhook payloads are signed with the per-webhook publicKey of that webhook.

Set the company key as publicKey and the webhook's own key as webhookPublicKey; a delivery is accepted when it verifies with either, so one gateway instance handles both mechanisms without swapping keys. If you use only one mechanism, that key alone is enough. Literal \n sequences in a key copied from JSON or a config file are normalized before verification.

If you register several webhooks with different keys against the same handler, the deliveries are indistinguishable; give each endpoint its own gateway instance and key.

$notification = $gateway->acceptNotification(); // verifies immediately

switch ($notification->getTransactionStatus()) {
    case $notification::STATUS_COMPLETED: // money received: purchase.paid, purchase.captured
    case $notification::STATUS_PENDING:   // not final: created, hold, pending_execute, reversals
    case $notification::STATUS_FAILED:    // payment failure, cancelled, expired
}

$notification->getTransactionReference();
$notification->getEventType();  // e.g. purchase.paid

STATUS_COMPLETED means money was received, nothing else. Refund and chargeback events (payment.refunded, payment.charged_back, payment.chargeback_reversed) are reported as STATUS_PENDING so a handler that fulfils on STATUS_COMPLETED can never fulfil on a reversal; branch on getEventType() for them. They are not STATUS_FAILED either, because the original payment did not fail. isRefund(), isChargeback() and isChargebackReversed() answer the event question directly, and isSuccessful() stays false for all three.

Answer the callback with HTTP 200 once processed. Klix retries up to 8 times over 36 hours and may deliver duplicates, so handling must be idempotent. The payload is a snapshot: re-fetch the purchase with fetchTransaction() before fulfilling an order.

On Klix's shared public test brand, webhooks are brand-wide (observed, not documented): a handler can receive purchase.* events for purchases it did not create. Ignore unknown references and keep handling idempotent.

The signature and payload shapes (purchase.paid, payment.refunded, duplicate deliveries, unknown events, missing related_to) are covered by tests using real RSA signatures. Real sandbox deliveries have also been verified: purchase.paid arrived as both a success_callback and a webhook, and payment.refunded as a webhook, each with the expected key. See docs/e2e.md for the evidence and how to repeat it.

Refund

$response = $gateway->refund([
    'transactionReference' => $purchaseId,
    'amount'               => '5.00',        // omit for a full refund
    'clientName'           => 'Janis Kalnins', // optional; Klix does not require it
])->send();

$response->isSuccessful(); // the refund request was accepted
$response->isPending();    // accepted, but Klix has not finished (pending_refund)
$response->isSettled();    // the refund finished: success / succeeded / paid
$response->getRefundId();

Acceptance and settlement are different questions. Klix returns a Payment with status: "success" when the refund completed, status: "pending" (or a Purchase in pending_refund) while the acquirer is still working, and an error otherwise. isSuccessful() answers "was the request accepted"; use isSettled() when money must actually have moved (for example before marking a refund as done in your ledger). A Payment without a status is accepted but not considered settled.

Klix only refunds paid purchases; check refund_availability / refundable_amount on the fetched purchase when in doubt. Even a partial refund moves the purchase to status = refunded, so a later fetchTransaction() no longer reports it as paid.

Capture, release and void

// Capture funds held after purchase(['skipCapture' => true])
$gateway->capture(['transactionReference' => $id, 'amount' => '10.00'])->send();

// Release a hold without taking the money
$gateway->release(['transactionReference' => $id])->send();

// Cancel a purchase that has not been paid
$gateway->void(['transactionReference' => $id])->send();

void() maps to Klix cancel/. It is not the same as release(): cancelling prevents a payment, releasing frees an authorization hold.

Omnipay has no supportsRelease() capability method (unlike supportsCapture() and supportsVoid()), so release() is available without a supports* flag. Every other operation is advertised through the matching supports*() method.

Errors

Invalid caller input (missing amount, returnUrl, clientEmail, …) throws Omnipay\Common\Exception\InvalidRequestException before any HTTP call.

Anything Klix refuses is returned as an Omnipay\Klix\Message\ErrorResponse:

$response->isSuccessful();   // false
$response->getMessage();     // first Klix message
$response->getCode();        // e.g. authentication_failed, min_length
$response->getStatusCode();  // HTTP status
$response->getFieldErrors(); // ['purchase.products' => [['message' => …, 'code' => …]]]

The API key is never included in error messages or exceptions. Transport failures keep the HTTP status, Klix code and messages, but the transport exception is not retained: its request would expose the Authorization header through getPrevious(). Exceptions are also built with trace arguments suppressed, so request payloads (customer email, names) do not leak through getTrace().

Testing against Klix

Klix publishes shared test credentials and test cards at https://developers.klix.app/test-environment/. There is no separate test host: the credentials decide. Do not rely on the is_test flag to detect test traffic — Klix's own full-flow test brand returns is_test: false (observed).

The package's own sandbox smoke test is opt-in and reads KLIX_BRAND_ID / KLIX_API_KEY:

vendor/bin/phpunit --testsuite e2e

It creates a purchase and fetches it back from the sandbox, and is skipped without those environment variables. It never touches the live API. The full browser flow that produced the fixtures is documented in docs/e2e.md.

Limitations

  • testMode does not switch URLs (Klix uses one host).
  • The customer email is required by Klix; provide clientEmail or a card with an email.
  • pending_execute is not reproducible on the published test brands, so pendingRedirect handling is unit-tested only.
  • Raw signed callback fixtures are not committed: the body embeds the caller IP and cannot be redacted without breaking the signature. Generated-signature tests cover the same shapes; see docs/e2e.md.
  • Billing templates, subscriptions and payouts are out of scope.
  • The reference field cannot be used to look a purchase up; always persist the id.

License

MIT. See LICENSE.