PHPackages                             sudiptpa/khalti-sdk-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. sudiptpa/khalti-sdk-php

ActiveLibrary[Payment Processing](/categories/payments)

sudiptpa/khalti-sdk-php
=======================

Framework-agnostic Khalti PHP SDK for ePayment create/status verification and production-safe backend fulfillment.

v1.1.0(4mo ago)0787MITPHPPHP &gt;=8.2 &lt;9.0

Since Feb 22Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/sudiptpa/khalti-sdk-php)[ Packagist](https://packagist.org/packages/sudiptpa/khalti-sdk-php)[ GitHub Sponsors](https://github.com/sudiptpa)[ RSS](/packages/sudiptpa-khalti-sdk-php/feed)WikiDiscussions master Synced today

READMEChangelog (2)Dependencies (2)Versions (3)Used By (0)

Khalti PHP SDK
==============

[](#khalti-php-sdk)

Framework-agnostic Khalti SDK for modern ePayment integrations in PHP.

[![Tests](https://github.com/sudiptpa/khalti-sdk-php/actions/workflows/ci.yml/badge.svg)](https://github.com/sudiptpa/khalti-sdk-php/actions/workflows/ci.yml)[![Latest Version](https://camo.githubusercontent.com/929ba8af91e3138eb2c6a3fbad50e45c9cc223093dc91dbcdbfa1fe5cc441106/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73756469707470612f6b68616c74692d73646b2d7068702e737667)](https://packagist.org/packages/sudiptpa/khalti-sdk-php)[![Total Downloads](https://camo.githubusercontent.com/dd14dfd7ab8c145e25894a6d8d36ac66c057b922b160dc52472f23dbc09f7e3b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73756469707470612f6b68616c74692d73646b2d7068702e737667)](https://packagist.org/packages/sudiptpa/khalti-sdk-php)[![License](https://camo.githubusercontent.com/4c1b42709071be9d04229b3657e5cd5496e061c2a37ad25b4361a60bb43fd635/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73756469707470612f6b68616c74692d73646b2d7068702e737667)](LICENSE)

---

[![Sponsor](https://camo.githubusercontent.com/d57b8ff0c3e08877e313deccbfe103a9cbcc5121e4d381986c7f56fb19a08b71/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53706f6e736f722d47697448756225323053706f6e736f72732d6561346161613f6c6f676f3d67697468756273706f6e736f7273266c6f676f436f6c6f723d7768697465)](https://github.com/sponsors/sudiptpa)

If this package has been useful to you, GitHub Sponsors is a simple way to support ongoing maintenance, improvements, and future releases.

Highlights
----------

[](#highlights)

- Modern resource API: `payments()`, `verification()`, `legacyPayments()`, `transactions()`
- ePayment KPG-2 create/status flow with strict backend verification
- First-class payload models (`CustomerInfo`, `AmountBreakdownItem`, `ProductDetail`)
- Typed models and value objects (`MoneyPaisa`, `OrderVerificationResult`)
- Polling helper: `waitForCompletion()`
- Idempotency-friendly verification model for safe order fulfillment
- Retry policy for transient failures (`429`, `5xx`, transport)
- Framework agnostic core with pluggable `TransportInterface`

Requirements
------------

[](#requirements)

- PHP `8.2+``ext-curl` is optional. It is only required when using the built-in `CurlTransport`.

Installation
------------

[](#installation)

```
composer require sudiptpa/khalti-sdk-php
```

Basic Usage (default CurlTransport)
-----------------------------------

[](#basic-usage-default-curltransport)

```
use Khalti\Config\ClientConfig;
use Khalti\Khalti;

$khalti = Khalti::client(new ClientConfig(
    secretKey: $_ENV['KHALTI_SECRET_KEY'],
));
```

If `ext-curl` is not installed, default transport throws a clear exception telling you to install `ext-curl` or pass your own transport.

Transport Examples
------------------

[](#transport-examples)

### 1) Custom Transport (framework-agnostic)

[](#1-custom-transport-framework-agnostic)

```
use Khalti\Exception\TransportException;
use Khalti\Http\HttpRequest;
use Khalti\Http\HttpResponse;
use Khalti\Transport\TransportInterface;

final class MyTransport implements TransportInterface
{
    public function send(HttpRequest $request, int $timeoutSeconds): HttpResponse
    {
        // Send request with your preferred HTTP client.
        throw new TransportException('Implement transport send logic.');
    }
}

$khalti = Khalti::client(
    new ClientConfig(secretKey: $_ENV['KHALTI_SECRET_KEY']),
    new MyTransport(),
);
```

### 2) PSR-18 / Guzzle adapter example

[](#2-psr-18--guzzle-adapter-example)

```
use GuzzleHttp\Client;
use Http\Adapter\Guzzle7\Client as GuzzleAdapter;
use Khalti\Config\ClientConfig;
use Khalti\Exception\TransportException;
use Khalti\Http\HttpRequest;
use Khalti\Http\HttpResponse;
use Khalti\Khalti;
use Khalti\Transport\TransportInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Throwable;

final class Psr18Transport implements TransportInterface
{
    public function __construct(
        private readonly \Psr\Http\Client\ClientInterface $client,
        private readonly RequestFactoryInterface $requestFactory,
        private readonly StreamFactoryInterface $streamFactory,
    ) {
    }

    public function send(HttpRequest $request, int $timeoutSeconds): HttpResponse
    {
        try {
            $psrRequest = $this->requestFactory
                ->createRequest($request->method, $request->url);

            foreach ($request->headers as $name => $value) {
                $psrRequest = $psrRequest->withHeader($name, $value);
            }

            if ($request->body !== '') {
                $psrRequest = $psrRequest->withBody($this->streamFactory->createStream($request->body));
            }

            $psrResponse = $this->client->sendRequest($psrRequest);
        } catch (Throwable $e) {
            throw new TransportException('PSR-18 transport failed.', 0, $e);
        }

        $headers = [];
        foreach ($psrResponse->getHeaders() as $name => $values) {
            $headers[strtolower($name)] = implode(', ', $values);
        }

        return new HttpResponse(
            $psrResponse->getStatusCode(),
            (string) $psrResponse->getBody(),
            $headers
        );
    }
}

$psr18 = new GuzzleAdapter(new Client());

$khalti = Khalti::client(
    new ClientConfig(secretKey: $_ENV['KHALTI_SECRET_KEY']),
    new Psr18Transport($psr18, $requestFactory, $streamFactory),
);
```

Note: This PSR-18 example requires user-land packages (for example `guzzlehttp/guzzle`, `php-http/guzzle7-adapter`, and PSR-17 factories). They are optional and not required by this SDK.

### 3) Built-in CurlTransport

[](#3-built-in-curltransport)

```
use Khalti\Transport\CurlTransport;

$khalti = Khalti::client(
    new ClientConfig(secretKey: $_ENV['KHALTI_SECRET_KEY']),
    new CurlTransport(),
);
```

### 4) Custom Laravel Transport

[](#4-custom-laravel-transport)

```
use Illuminate\Support\Facades\Http;
use Khalti\Exception\TransportException;
use Khalti\Http\HttpRequest;
use Khalti\Http\HttpResponse;
use Khalti\Transport\TransportInterface;
use Throwable;

final class LaravelTransport implements TransportInterface
{
    public function send(HttpRequest $request, int $timeoutSeconds): HttpResponse
    {
        try {
            $response = Http::timeout($timeoutSeconds)
                ->withHeaders($request->headers)
                ->send($request->method, $request->url, ['body' => $request->body]);
        } catch (Throwable $e) {
            throw new TransportException('Laravel HTTP transport failed.', 0, $e);
        }

        $headers = [];
        foreach ($response->headers() as $name => $values) {
            $headers[strtolower($name)] = implode(', ', $values);
        }

        return new HttpResponse($response->status(), $response->body(), $headers);
    }
}
```

ePayment Flow
-------------

[](#epayment-flow)

```
use Khalti\Model\AmountBreakdownItem;
use Khalti\Model\CustomerInfo;
use Khalti\Model\EpaymentInitiateRequest;
use Khalti\Model\ProductDetail;

$request = EpaymentInitiateRequest::make(
    returnUrl: 'https://example.com/payments/khalti/return',
    websiteUrl: 'https://example.com',
    amount: 1000,
    purchaseOrderId: 'ORD-1001',
    purchaseOrderName: 'Pro Subscription',
)
    ->setCustomerInfo(new CustomerInfo(
        name: 'Sujip Thapa',
        email: 'sudiptpa@gmail.com',
        phone: '9800000000',
    ))
    ->addAmountBreakdownItem(new AmountBreakdownItem('Subtotal', 900))
    ->addAmountBreakdownItem(new AmountBreakdownItem('Tax', 100))
    ->addProductDetail(new ProductDetail(
        identity: 'SKU-1001',
        name: 'Pro Subscription',
        totalPrice: 1000,
        quantity: 1,
        unitPrice: 1000,
    ));

$session = $khalti->payments()->initiate($request); // alias: create($request)
$status = $khalti->payments()->lookup($session->pidx); // alias: status($session->pidx)
```

Important: Khalti ePayment Has No Checkout Webhook
--------------------------------------------------

[](#important-khalti-epayment-has-no-checkout-webhook)

Khalti ePayment does **not** provide a dedicated payment webhook for this checkout flow.

You must manually verify payment on your backend before order fulfillment.

Never trust return query params alone.

Return Verification (Backend)
-----------------------------

[](#return-verification-backend)

```
use Khalti\ValueObject\MoneyPaisa;
use Khalti\Verification\VerificationContext;

$payload = $khalti->verification()->parseReturnQuery($_GET);

$result = $khalti->verification()->verify(
    payload: $payload,
    context: new VerificationContext(
        orderId: 'ORD-1001',
        pidx: $payload->pidx,
        expectedAmount: MoneyPaisa::of(1000),
        receivedAtUnix: time(),
    )
);

if (! $result->fulfillable) {
    // pending/failed/refunded/duplicate
    return;
}

// fulfill once
```

Idempotency (Processed-once Pattern)
------------------------------------

[](#idempotency-processed-once-pattern)

Use `IdempotencyStoreInterface` in your app:

```
$idempotencyStore = new App\Payments\Khalti\RedisIdempotencyStore($redis);

$result = $khalti->verification()->verify(
    payload: $payload,
    context: new VerificationContext(
        orderId: $orderId,
        pidx: $payload->pidx,
        expectedAmount: MoneyPaisa::of($expectedAmount),
    ),
    idempotencyStore: $idempotencyStore,
);
```

If the same payment return is received again, status becomes `duplicate` and fulfillment is blocked.

Polling Helper
--------------

[](#polling-helper)

```
$status = $khalti->payments()->waitForCompletion(
    pidx: $session->pidx,
    timeoutSeconds: 30,
    intervalSeconds: 2,
);
```

Retry Policy
------------

[](#retry-policy)

```
$config = new ClientConfig(
    secretKey: $_ENV['KHALTI_SECRET_KEY'],
    maxRetries: 2,
    retryBackoffMs: 200,
    retryMaxBackoffMs: 1200,
    retryHttpStatusCodes: [429, 500, 502, 503, 504],
);
```

Transaction APIs
----------------

[](#transaction-apis)

```
$list = $khalti->transactions()->all(page: 1, pageSize: 20);
$detail = $khalti->transactions()->find('txn_idx');

foreach ($list->records as $row) {
    echo $row->idx . ' => ' . $row->state . PHP_EOL;
}
```

Legacy APIs
-----------

[](#legacy-apis)

```
$verify = $khalti->legacyPayments()->verify($token, 1000);
$status = $khalti->legacyPayments()->status($token, 1000);
```

Optional Extension Points
-------------------------

[](#optional-extension-points)

- `RequestNormalizerInterface`
- `ResponseNormalizerInterface`
- `IdempotencyStoreInterface`
- `MismatchCounterInterface`
- `ClockInterface`

These are optional and do not add runtime dependencies.

Troubleshooting
---------------

[](#troubleshooting)

### Common auth errors

[](#common-auth-errors)

- `AuthenticationException` (401/403): wrong secret key or wrong environment key.
- Check sandbox vs production key mismatch.

### Amount mismatch causes

[](#amount-mismatch-causes)

- Stored order amount in paisa differs from Khalti lookup amount.
- Tax/fee math done at UI but not stored in backend order snapshot.
- Verifying wrong order against wrong `pidx`.

### Return verification checklist

[](#return-verification-checklist)

- Parse query with `parseReturnQuery()`.
- Verify with `VerificationContext` (`orderId`, `pidx`, `expectedAmount`).
- Enforce idempotency before fulfillment.
- Fulfill only when `OrderVerificationResult::isPaid()` and `fulfillable === true`.

Testing &amp; Quality
---------------------

[](#testing--quality)

```
composer test
composer stan
composer lint
```

Architecture
------------

[](#architecture)

See `ARCHITECTURE.md`.

License
-------

[](#license)

MIT

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance79

Regular maintenance activity

Popularity19

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

132d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7222620?v=4)[Sujip Thapa](/maintainers/sudiptpa)[@sudiptpa](https://github.com/sudiptpa)

---

Top Contributors

[![sudiptpa](https://avatars.githubusercontent.com/u/7222620?v=4)](https://github.com/sudiptpa "sudiptpa (14 commits)")

---

Tags

khaltikhalti-integrationkhalti-payment-gatewaykhalti-sdkphppaymentgatewayepaymentkhalti

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sudiptpa-khalti-sdk-php/health.svg)

```
[![Health](https://phpackages.com/badges/sudiptpa-khalti-sdk-php/health.svg)](https://phpackages.com/packages/sudiptpa-khalti-sdk-php)
```

###  Alternatives

[omalizadeh/laravel-multi-payment

A driver-based laravel package for online payments via multiple gateways

491.2k](/packages/omalizadeh-laravel-multi-payment)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
