Search by

serkannyildirim / lidio-php-sdk

serkannyildirim

Unofficial PHP SDK for the Lidio payment API (hosted payment page, payment status, notifications).

Package info

github.com/serkannyildirim/lidio-php-sdk

pkg:composer/serkannyildirim/lidio-php-sdk

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.0 2026-11-27 18:43 UTC

This package is auto-updated.

Last update: 2026-11-27 18:53:28 UTC


README

Tests PHP License: MIT

Türkçe | English

Unofficial PHP SDK for the Lidio payment API. It covers the hosted payment page flow: start a payment, send the customer to Lidio's 3D Secure payment page (full page or popup), confirm the result, and verify payment notifications.

This is a community project and is not affiliated with or endorsed by Lidio. Always test in Lidio's test environment before going live.

Features

  • StartHostedPaymentProcess with a fluent, validated request builder (correct JSON types, documented field paths for every payment instrument)
  • GetHostedPaymentStatus with helpers: isPaid(), isPending(), isFailed(), isFraudCheckPending(), matchesOrder()
  • Payment notification parsing with ParametersHash signature verification
  • TLS verification always on, typed exceptions, no runtime dependencies (only ext-curl and ext-json)
  • Pluggable HTTP transport for proxies, logging, or tests
  • Working example shop: cart, popup (iframe) and full-page payment, return page, notification endpoint

Requirements

  • PHP 7.4 or newer (tested on 7.4, 8.0 – 8.4)
  • ext-curl, ext-json
  • Lidio merchant code and API key (ask Lidio). The API password is needed to verify notifications.

Installation

composer require serkannyildirim/lidio-php-sdk

Quick start

1. Create the client

use Lidio\Config;
use Lidio\LidioClient;

$lidio = new LidioClient(Config::test(
    getenv('LIDIO_MERCHANT_CODE'),
    getenv('LIDIO_API_KEY'),       // without or with the "MxS2S " prefix
    getenv('LIDIO_API_PASSWORD')   // optional; required for notifications
));
// Live: Config::production(...)

Keep credentials out of your code and your repository (environment variables, a secrets manager, ...).

2. Start a payment

Save the order (id, amount, currency) before starting the payment, so you can verify the result later.

use Lidio\HostedPayment\{Address, BasketItem, CardOptions, Customer, HostedPaymentRequest, ThreeDSecureMode};
use Lidio\Support\OrderId;

$orderId = OrderId::generate('SHOP');   // unique, 20 chars, accepted by every bank
$amount  = 299.80;
// $db->saveOrder($orderId, $amount, 'TRY', 'pending');

$request = HostedPaymentRequest::create($orderId, $amount, 'TRY')
    ->setCustomer(
        Customer::create()
            ->setId('customer-42')
            ->setEmail('jane@example.com')
            ->setName('Jane Doe')
            ->setPhone('5551112233')          // or +905551112233
    )
    ->addBasketItem(BasketItem::create('Ceramic mug', 149.90, 2)->setItemType(BasketItem::TYPE_PHYSICAL))
    ->setInvoiceAddress(Address::create()->setContactName('Jane Doe')->setCity('Istanbul')->setCountry('Turkey'))
    ->setCardOptions(
        CardOptions::create()
            ->useInstallment()
            ->setNewCardThreeDSecureMode(ThreeDSecureMode::MANDATORY)
    )
    ->setDesign(HostedPaymentRequest::VIEW_COMPACT, 4)
    ->setReturnUrl('https://shop.example/payment/return')
    ->setNotificationUrl('https://shop.example/payment/notification')
    ->setClient($_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'] ?? null);

$response = $lidio->startHostedPayment($request);

if ($response->isSuccess()) {
    header('Location: ' . $response->getRedirectUrl()); // open within 5 minutes
    exit;
}

echo 'Payment could not be started: ' . $response->getResult(); // e.g. InvalidPhone

Without addPaymentInstrument() the request offers only NewCard. Other instruments:

use Lidio\HostedPayment\PaymentInstrument;

$request
    ->addPaymentInstrument(PaymentInstrument::NEW_CARD)
    ->addPaymentInstrument(PaymentInstrument::STORED_CARD)
    ->addPaymentInstrument(PaymentInstrument::BKM_EXPRESS, ['paymentSecurity' => 'NoneThreeD']);

Fields without a dedicated setter can be set with setField('subscriptionConfig', [...]).

3. Confirm the result on the return URL

Lidio redirects the browser to your return URL with OrderId, Result, ... in the query string. These values can be changed by the user; use them only to find the order and ask Lidio for the real status:

use Lidio\HostedPayment\ReturnParameters;

$params = ReturnParameters::fromArray($_GET);
$order  = $db->findOrder($params->getOrderId());

$status = $lidio->getHostedPaymentStatus($order->id, $params->getSystemTransId());

if ($status->isPaid() && $status->matchesOrder($order->id, $order->amount, $order->currency)) {
    // Mark the order as paid ONCE (the notification may arrive first or at the same time).
} elseif ($status->isFraudCheckPending()) {
    // Bank approved, Lidio's fraud check still running. Wait for the notification.
} elseif ($status->isPending()) {
    // Not final yet (3D in progress, UnexpectedState, ...). Check again later.
} elseif ($status->isFailed()) {
    echo $status->getMessage();   // customer friendly Turkish message; getMessage('en') for English
}

matchesOrder() compares the requested amount. The processed amount (getTotalAmountProcessed()) can be higher because it includes installment interest chosen by the customer.

4. Handle notifications

Lidio posts a notification after the payment and again when the fraud check finishes. Verify the signature, then confirm with getHostedPaymentStatus():

use Lidio\Exception\InvalidSignatureException;
use Lidio\Notification\NotificationParser;

try {
    $notification = $lidio->notifications()->parse(
        file_get_contents('php://input'),
        NotificationParser::signatureFromServer($_SERVER)
    );
} catch (InvalidSignatureException $e) {
    http_response_code(403);
    exit;
}

$status = $lidio->getHostedPaymentStatus($notification->getOrderId(), $notification->getSystemTransId());
// ... same checks as on the return URL, idempotent ...

echo 'OK';

Ask Lidio to send notifications as JSON and to use OK as the success match string. Notification URLs must be reachable from the internet (use a tunnel such as ngrok for local development).

Popup (iframe) payment

The payment page can be shown in an iframe (use VIEW_COMPACT). Lidio posts HeightChanged, ErrorOccurred, ... messages to the parent window, and your return page, loaded inside the iframe, can post the final result to the parent. See examples/index.php and examples/return.php.

Notes:

  • Do not use cookies on the return URL in iframe mode; browsers may block third-party cookies.
  • On localhost, Chrome blocks the redirect from Lidio to your local return URL inside an iframe (Local Network Access). Use a public URL (ngrok, a staging server) to test the popup flow end to end; the full-page flow works on localhost.

Error handling

Exception When
Lidio\Exception\ValidationException The request is invalid; nothing was sent. getErrors() lists the problems.
Lidio\Exception\ConnectionException Lidio could not be reached (network, TLS, timeout).
Lidio\Exception\ApiException Lidio answered with something unusable (not JSON, HTTP error without a result).
Lidio\Exception\InvalidSignatureException Notification signature is missing or wrong.

All extend Lidio\Exception\LidioException. Business results such as InvalidPhone, Refused or TransactionNotFound are not exceptions; read them from the response objects.

Validation performed before sending

  • Order id: 1–32 characters of letters, digits, _ or -. OrderId::generate() produces ids that also satisfy the strictest bank rules (letters/digits only, max 20).
  • Amount > 0 with at most 2 decimals; currency from Lidio's list.
  • Customer is required; phone 5xxxxxxxxx or +<country><number>; valid e-mail.
  • Absolute http(s) return/notification URLs; known payment instruments.
  • When basket items are given, their total must equal the total amount (add shipping as a basket item).

Example shop

composer install
export LIDIO_MERCHANT_CODE=... LIDIO_API_KEY=... LIDIO_API_PASSWORD=...
php -S localhost:8000 -t examples

Open http://localhost:8000. See examples/README.md for details and test cards.

Going live checklist

  • Production credentials in environment variables, Config::production(...)
  • Your server's IP address registered at Lidio (otherwise InvalidCredential)
  • Production base URL confirmed with Lidio (the SDK uses https://api.lidio.com from the documentation; override with ['base_url' => ...] if needed)
  • API password configured; notification format JSON and match string OK agreed with Lidio
  • Orders stored in a database; status updates are idempotent
  • Orders under fraud review are not shipped until the final notification
  • A scheduled job re-checks orders that stay pending (in case a notification is lost)

Testing

composer test                     # unit tests
LIDIO_MERCHANT_CODE=... LIDIO_API_KEY=... composer test:integration   # against Lidio's test environment

Documentation

Contributing

Issues and pull requests are welcome. Please add tests for changes and run composer test.

License

MIT