ngenius-laravel maintained by ahmed-m-hussain
N-Genius Payment Gateway for Laravel
An enterprise-grade, developer-friendly Laravel SDK & Package for Network International (N-Genius) Payment Gateway.
Built with first-class multi-region architecture specifically crafted for Saudi Arabia (KSA Mada & NIARABIA Realm), United Arab Emirates (UAE), and Egypt.
✨ Features
- 🇸🇦 Multi-Regional Architecture: Dedicated gateway URLs and Identity realms for Saudi Arabia (KSA), UAE, Egypt, and Jordan.
- 💳 MADA & Apple Pay Out-of-the-Box: Full compatibility with Saudi MADA cards, Visa, Mastercard, and Apple Pay hosted checkout.
- ⚡ Automated OAuth2 Token Caching: Automatic caching and refreshing of access tokens to optimize API latency.
- 🏗️ Fluent DTO Builders: Type-safe
PaymentOrderandPaymentResultdata transfer objects. - 🛡️ Authoritative Server-to-Server Verification: Anti-tampering verification directly against N-Genius Gateway before fulfilling orders.
- 🔔 Laravel Event Dispatching: Dispatches
PaymentCompleted,PaymentFailed, andPaymentCancelledevents. - 🪝 Webhook Processing: Streamlined handling for asynchronous payment notifications.
- 🚀 Laravel 9, 10, 11, and 12 Ready with full PHP 8.1 - 8.4 support.
📦 Installation
Install the package via Composer:
composer require ahmed-m-hussain/ngenius-laravel
Publish the configuration file:
php artisan vendor:publish --tag="ngenius-config"
⚙️ Configuration
Add the following environment variables to your .env file:
# Region: 'ksa' (Saudi Arabia), 'uae', 'egypt', or 'global'
NGENIUS_REGION=ksa
# Environment: 'sandbox' or 'live'
NGENIUS_ENV=sandbox
# Service Account API Key (from N-Genius Portal > Settings > Integrations > Service Accounts)
NGENIUS_API_KEY=your_base64_service_account_api_key
# Outlet Reference UUID (Trading Unit ID)
NGENIUS_OUTLET_ID=your_outlet_uuid_here
# Currency: 'SAR', 'AED', 'EGP', 'USD'
NGENIUS_CURRENCY=SAR
Supported Regions
| Region Code | Description | Identity Realm | Default Currency |
|---|---|---|---|
ksa |
Saudi Arabia Gateway (api-gateway.ksa...) |
NIARABIA |
SAR (Mada support) |
uae |
UAE Gateway (api-gateway...) |
ni |
AED |
egypt |
Egypt Regional Gateway | ni |
EGP |
global |
Global Standard Gateway | ni |
USD |
🚀 Quickstart Guide
1. Create a Hosted Payment Session
Build a PaymentOrder and retrieve the hosted payment URL:
use NGenius\Laravel\Facades\NGenius;
use NGenius\Laravel\DTO\PaymentOrder;
public function checkout(Order $order)
{
$paymentOrder = PaymentOrder::make()
->orderReference($order->order_number)
->amount($order->total_amount, 'SAR')
->customer($order->customer_name, $order->customer_email, $order->customer_phone)
->billingAddress(
address: 'Olaya Street',
city: 'Riyadh',
countryCode: 'SA'
)
->redirectUrl(route('payment.callback', ['order' => $order->order_number]))
->cancelUrl(route('payment.cancel', ['order' => $order->order_number]));
$response = NGenius::createSession($paymentOrder);
// Store gateway reference if needed
$order->update([
'payment_reference' => $response->getOrderReference(),
]);
// Redirect user to the secure hosted payment page
return redirect()->away($response->getPaymentUrl());
}
2. Handle Payment Return Callback
When the user completes or cancels the payment, verify the status directly with the gateway:
use NGenius\Laravel\Facades\NGenius;
public function callback(Request $request, Order $order)
{
// Retrieve reference from query or database
$ref = $request->query('ref') ?: $order->payment_reference;
$result = NGenius::verifyOrder($ref);
if ($result->isSuccessful()) {
$order->update([
'status' => 'completed',
'payment_id' => $result->getPaymentId(),
'paid_at' => now(),
]);
return redirect()->route('orders.show', $order)
->with('success', 'Payment processed successfully via ' . $result->getCardType());
}
return redirect()->route('orders.show', $order)
->with('error', 'Payment was not completed.');
}
3. Handle Webhooks
Handle asynchronous server-to-server gateway notifications:
use NGenius\Laravel\Facades\NGenius;
public function webhook(Request $request)
{
$result = NGenius::handleWebhook($request->all());
if ($result->isSuccessful()) {
$order = Order::where('order_number', $result->getMerchantOrderReference())->first();
if ($order && !$order->isPaid()) {
$order->update([
'status' => 'completed',
'payment_id' => $result->getPaymentId(),
'paid_at' => now(),
]);
}
}
return response()->json(['status' => 'ok']);
}
🔔 Listening to Payment Events
The package automatically dispatches events during verification and webhook handling:
NGenius\Laravel\Events\PaymentCompletedNGenius\Laravel\Events\PaymentFailedNGenius\Laravel\Events\PaymentCancelled
Register listeners in your EventServiceProvider:
use NGenius\Laravel\Events\PaymentCompleted;
use App\Listeners\SendOrderConfirmationEmail;
protected $listen = [
PaymentCompleted::class => [
SendOrderConfirmationEmail::class,
],
];
In your listener:
namespace App\Listeners;
use NGenius\Laravel\Events\PaymentCompleted;
class SendOrderConfirmationEmail
{
public function handle(PaymentCompleted $event)
{
$result = $event->result;
$paymentId = $result->getPaymentId();
$cardType = $result->getCardType(); // 'MADA', 'VISA', etc.
$amount = $result->getAmount();
}
}
🛡️ Available Methods on PaymentResult
| Method | Return Type | Description |
|---|---|---|
$result->isSuccessful() |
bool |
Returns true if state is PURCHASED, CAPTURED, AUTHORISED, or SUCCESS |
$result->isFailed() |
bool |
Returns true if state is FAILED or DECLINED |
$result->isCancelled() |
bool |
Returns true if state is CANCELLED or ABANDONED |
$result->getPaymentId() |
?string |
Bank Transaction ID |
$result->getOrderReference() |
?string |
N-Genius Order UUID |
$result->getMerchantOrderReference() |
?string |
Your system's order number |
$result->getAmount() |
?float |
Transaction amount in major units |
$result->getCurrency() |
?string |
Currency code (e.g. SAR) |
$result->getCardType() |
?string |
Card scheme: MADA, VISA, MASTERCARD |
$result->getAuthCode() |
?string |
Bank approval/authorization code |
$result->getRawData() |
array |
Full raw JSON payload |
🧪 Testing
composer test
🔒 Security
If you discover any security-related issues, please email info@ahmed-hussain.com instead of using the issue tracker.
👥 Credits
📄 License
The MIT License (MIT). Please see License File for more information.