PHPackages                             mostafax/knet - 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. mostafax/knet

Abandoned → [mostafax/payment-engine](/?search=mostafax%2Fpayment-engine)Library[Payment Processing](/categories/payments)

mostafax/knet
=============

Enterprise Payment Orchestration, Reconciliation, Recovery and Monitoring Platform for Laravel — Multi-gateway (KNET, MyFatoorah, Tap, PayTabs, Stripe, PayPal, Fawry), Transaction Ledger, Webhook Reliability, Auto-Recovery, Backfill Engine

2.1.0(3w ago)014MITPHPPHP ^8.2CI passing

Since Jan 9Pushed 3w ago1 watchersCompare

[ Source](https://github.com/mostafax2/payment-engine)[ Packagist](https://packagist.org/packages/mostafax/knet)[ Docs](https://github.com/mostafax2/payment-engine)[ RSS](/packages/mostafax-knet/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (4)Dependencies (18)Versions (7)Used By (0)

mostafax/payment-engine
=======================

[](#mostafaxpayment-engine)

> **Enterprise Payment Orchestration, Reconciliation, Recovery &amp; Monitoring Platform for Laravel**

[![Latest Version](https://camo.githubusercontent.com/8cf67af7ab72a8a8376b6e75b688fea6576b840ba40b497dbb56aaa32fd9eb09/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d322e312e302d627269676874677265656e2e737667)](https://github.com/mostafax2/payment-engine/releases)[![PHP Version](https://camo.githubusercontent.com/0f16581d1180dbfd4c0e13166ec1267d4ad2f2fab8281ea6d6b284cf5c65d921/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d626c75652e737667)](https://www.php.net)[![Laravel Version](https://camo.githubusercontent.com/36ab9eb40d419c375ec1c19e6d5fd0d5ae0aeb01372cc6b164966c412feecdad/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302532422d7265642e737667)](https://laravel.com)[![License](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](https://choosealicense.com/licenses/mit/)

---

Overview
--------

[](#overview)

`mostafax/payment-engine` transforms any Laravel application into a full payment orchestration platform. It provides a unified driver interface across **7 payment gateways**, an immutable transaction ledger, a webhook reliability layer with Dead Letter Queue, automated reconciliation, stale-transaction recovery, and historical backfill — all event-driven and multi-tenant ready.

**Author:** [Mostafa Elbayyar](https://github.com/mostafax2)
**Documentation:**
**Support:**

---

Supported Gateways
------------------

[](#supported-gateways)

GatewayRegionStatusKNETKuwait/Gulf✅ Full SupportMyFatoorahGulf &amp; MENA✅ Full SupportTap PaymentsMENA✅ Full SupportPayTabsMENA/Global✅ Full SupportStripeGlobal✅ Full SupportPayPalGlobal✅ Full SupportFawryEgypt / MENA✅ Full Support---

Key Features
------------

[](#key-features)

- **Multi-Gateway Driver Architecture** — Strategy Pattern. Add new gateways by implementing `PaymentDriverInterface`.
- **Immutable Transaction Ledger** — ULID-keyed `pe_transactions` + append-only `pe_transaction_events` audit trail.
- **Webhook Reliability Layer** — Raw payload persistence, SHA-256 idempotency, exponential backoff (1m→5m→15m→1h→24h), Dead Letter Queue.
- **Reconciliation Engine** — Automated comparison of gateway vs internal records with mismatch detection (amount tolerance: ±0.01).
- **Auto-Recovery Engine** — Scans stale pending transactions and self-heals via gateway inquiry.
- **Historical Backfill Engine** — Full or gap-only sync from gateway for any date range.
- **6 Domain Events** — Decoupled lifecycle: `PaymentInitiated`, `PaymentCaptured`, `PaymentFailed`, `PaymentRefunded`, `PaymentRecovered`, `PaymentReconciled`.
- **Multi-Tenant Support** — `tenant_id` scoping via configurable resolver callable.
- **3 Artisan Commands** — `payment:sync`, `payment:reconcile`, `payment:recover`.
- **REST API** — 10 Sanctum-protected endpoints.

---

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

[](#requirements)

- PHP 8.2+
- Laravel 10, 11, or 13
- MySQL 8+ or MariaDB 10.3+
- Redis (recommended for queue workers)

---

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

[](#installation)

### Option A — One Command (Recommended)

[](#option-a--one-command-recommended)

```
composer require mostafax/payment-engine
php artisan payment:install
```

`payment:install` automatically:

- Publishes `config/payment-engine.php`
- Runs the 6 database migrations
- Patches CSRF exclusions in `VerifyCsrfToken.php` (Laravel 10) or `bootstrap/app.php` (Laravel 11+)
- Appends `.env` stubs for gateway credentials

### Option B — Manual

[](#option-b--manual)

```
composer require mostafax/payment-engine
php artisan vendor:publish --tag=payment-engine-config
php artisan migrate
```

### Configure `.env`

[](#configure-env)

```
# Default gateway
PAYMENT_GATEWAY=knet

# KNET credentials
KNET_TRANSPORT_ID=your_transport_id
KNET_TRANSPORT_PASSWORD=your_password
KNET_RESOURCE_KEY=your_resource_key
KNET_SUCCESS_URL=https://yourapp.com/payment/knet/success
KNET_ERROR_URL=https://yourapp.com/payment/knet/error
KNET_SANDBOX=true

# Stripe (optional)
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...

# PayPal (optional)
PAYPAL_CLIENT_ID=...
PAYPAL_CLIENT_SECRET=...

# Queue names
PAYMENT_QUEUE=payments
PAYMENT_WEBHOOK_QUEUE=payment-webhooks
PAYMENT_RECONCILE_QUEUE=payment-reconcile
PAYMENT_RECOVERY_QUEUE=payment-recovery
```

### 4. Exclude Callbacks from CSRF

[](#4-exclude-callbacks-from-csrf)

```
// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
    'payment/*/success',
    'payment/*/error',
    'api/payment/webhook/*',
];
```

### 5. Start Queue Workers

[](#5-start-queue-workers)

```
php artisan queue:work --queue=payment-webhooks
php artisan queue:work --queue=payment-reconcile
php artisan queue:work --queue=payment-recovery
```

---

Basic Usage
-----------

[](#basic-usage)

### Initiate a Payment

[](#initiate-a-payment)

```
use Mostafax\PaymentEngine\Facades\PaymentEngine;
use Mostafax\PaymentEngine\DTOs\InitiatePaymentDTO;
use Illuminate\Support\Str;

$dto = InitiatePaymentDTO::fromArray([
    'gateway'     => 'knet',
    'track_id'    => (string) Str::ulid(),
    'amount'      => 25.500,
    'currency'    => 'KWD',
    'success_url' => route('payment.return'),
    'error_url'   => route('payment.cancel'),
    'metadata'    => ['order_id' => $order->id],
]);

$result = PaymentEngine::initiate($dto);

return redirect($result['redirect_url']);
```

### Listen to Events

[](#listen-to-events)

```
// In EventServiceProvider::boot()
use Mostafax\PaymentEngine\Events\PaymentCaptured;

Event::listen(PaymentCaptured::class, function (PaymentCaptured $event) {
    Order::find($event->transaction->metadata['order_id'])?->markAsPaid();
});
```

### Live Gateway Inquiry

[](#live-gateway-inquiry)

```
$response = PaymentEngine::inquire(
    trackId: $trackId,
    gateway: 'knet',
    amount:  25.500,
);
// $response → GatewayResponseDTO
```

---

Reconciliation
--------------

[](#reconciliation)

```
# Sync date range
php artisan payment:reconcile knet --from=2026-06-01 --to=2026-06-10

# Async (background job)
php artisan payment:reconcile knet --async

# Recover stale pending transactions (>30 min)
php artisan payment:recover --minutes=30 --max=1000
```

---

Historical Backfill
-------------------

[](#historical-backfill)

```
# Full sync for a date range
php artisan payment:sync knet --from=2026-01-01 --to=2026-01-31

# Gap-fill only (safe to re-run, skips existing)
php artisan payment:sync knet --missing
```

---

API Endpoints
-------------

[](#api-endpoints)

All endpoints require `Authorization: Bearer {token}` (Laravel Sanctum) except webhook receivers.

MethodEndpointDescription`POST``/api/payment/initiate`Initiate payment, get redirect URL`GET``/api/payment/transactions`Paginated list (filter by gateway/status/date)`GET``/api/payment/transactions/{ulid}`Transaction + full audit trail`POST``/api/payment/inquire/{trackId}`Live gateway status check`POST``/api/payment/reconcile`Trigger reconciliation`GET``/api/payment/reconciliation/reports`Paginated reports`GET``/api/payment/reconciliation/reports/{ulid}`Report with mismatch items`POST``/api/payment/webhook/{gateway}`Receive push webhooks (no auth, sig verified)`ANY``/payment/{gateway}/success`KNET/PayTabs success callback`ANY``/payment/{gateway}/error`KNET/PayTabs error callback---

Database Tables
---------------

[](#database-tables)

TablePurpose`pe_transactions`Central payment ledger (ULID, multi-tenant, status lifecycle)`pe_transaction_events`Append-only audit trail for every status change`pe_webhook_payloads`Raw payload persistence + retry state`pe_webhook_attempts`Per-attempt log with exception trace`pe_reconciliation_reports`Reconciliation run summaries`pe_reconciliation_items`Individual mismatch records per reportTable names are configurable via `config('payment-engine.tables.*')`.

---

Custom Gateway Driver
---------------------

[](#custom-gateway-driver)

Implement `PaymentDriverInterface` to add any gateway:

```
use Mostafax\PaymentEngine\Contracts\PaymentDriverInterface;
use Mostafax\PaymentEngine\DTOs\InitiatePaymentDTO;
use Mostafax\PaymentEngine\DTOs\GatewayResponseDTO;

final class MyGatewayDriver implements PaymentDriverInterface
{
    public function initiate(InitiatePaymentDTO $dto): array { ... }
    public function handleCallback(array $payload): GatewayResponseDTO { ... }
    public function inquire(string $trackId, ?float $amount = null): GatewayResponseDTO { ... }
    public function fetchTransactions(string $from, string $to, int $page = 1, int $perPage = 500): array { ... }
    public function getGatewayName(): string { return 'my-gateway'; }
    public function getSupportedCurrencies(): array { return ['KWD', 'USD']; }
}
```

Register it in your `ServiceProvider`:

```
config(['payment-engine.gateways.my-gateway' => [
    'driver' => MyGatewayDriver::class,
    'api_key' => env('MY_GATEWAY_KEY'),
    'sandbox' => env('MY_GATEWAY_SANDBOX', true),
]]);
```

---

Upgrade from 1.x (KNET-only)
----------------------------

[](#upgrade-from-1x-knet-only)

1. Update `composer.json`: `"mostafax/payment-engine": "^2.0"`
2. Publish and run new migrations: `php artisan vendor:publish --tag=payment-engine-migrations && php artisan migrate`
3. Publish new config: `php artisan vendor:publish --tag=payment-engine-config`
4. Replace `.env` keys with new `KNET_*` prefixed names (see [Installation](#installation) above)
5. Replace old CSRF exclusion `knet/*` with `payment/*/success`, `payment/*/error`
6. Update namespace: `Mostafax\Knet\*` → `Mostafax\PaymentEngine\*`

---

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for full release history.

---

License
-------

[](#license)

MIT — see [LICENSE](LICENSE) for details.

---

Author
------

[](#author)

**Mostafa Elbayyar**
Senior Software Engineer &amp; Laravel Package Author
GitHub: [@mostafax2](https://github.com/mostafax2)
Email:

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance95

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

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 ~177 days

Recently: every ~221 days

Total

6

Last Release

24d ago

Major Versions

1.0.3 → 2.0.02026-06-11

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/146624906?v=4)[Mostafa Elbayyar](/maintainers/mostafax2)[@mostafax2](https://github.com/mostafax2)

---

Top Contributors

[![mostafax2](https://avatars.githubusercontent.com/u/146624906?v=4)](https://github.com/mostafax2 "mostafax2 (28 commits)")

---

Tags

laravelstripepaymentpaypalwebhookenterprisefawrypayment gatewaymulti-tenantfintechmyfatoorahtapEgyptknetpayment-orchestrationreconciliationtransaction-ledger

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mostafax-knet/health.svg)

```
[![Health](https://phpackages.com/badges/mostafax-knet/health.svg)](https://phpackages.com/packages/mostafax-knet)
```

###  Alternatives

[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M131](/packages/roots-acorn)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k15.1M132](/packages/laravel-pulse)[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.6k29.9M148](/packages/laravel-cashier)[flarum/core

Delightfully simple forum software.

201.4M2.3k](/packages/flarum-core)[flat3/lodata

OData v4.01 Producer for Laravel

99351.7k](/packages/flat3-lodata)

PHPackages © 2026

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