PHPackages                             numanrki/bank-alfalah - 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. numanrki/bank-alfalah

ActiveLibrary[Payment Processing](/categories/payments)

numanrki/bank-alfalah
=====================

Bank Alfalah (Alfa) Payment Gateway SDK for PHP &amp; Laravel. Supports Credit/Debit Card, Alfa Wallet, JazzCash, Raast QR, BNPL, Bank Account, and Card on Delivery.

v1.0.0(3mo ago)00MITPHP &gt;=8.0

Since Apr 6Compare

[ Source](https://github.com/numanrki/bank-alfalah-payment-gateway)[ Packagist](https://packagist.org/packages/numanrki/bank-alfalah)[ Docs](https://github.com/numanrki/bank-alfalah-payment-gateway)[ RSS](/packages/numanrki-bank-alfalah/feed)WikiDiscussions Synced 3w ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

Bank Alfalah Payment Gateway — PHP &amp; Laravel SDK
====================================================

[](#bank-alfalah-payment-gateway--php--laravel-sdk)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1e1ebde798e4d2c480d4a994f0020a61c0cd1ee7b89ea6671d228f616382d694/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e756d616e726b692f62616e6b2d616c66616c61682e737667)](https://packagist.org/packages/numanrki/bank-alfalah)[![Total Downloads](https://camo.githubusercontent.com/de85a1f48142e91b16d756871f20fd1d8ebed1bb14f87330aca0245500953be8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e756d616e726b692f62616e6b2d616c66616c61682e737667)](https://packagist.org/packages/numanrki/bank-alfalah)[![License: MIT](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/854124dd57cfd3aad3184fca9760bf1f33a5ec1e5d080cfbe8aa4e3337ba46e6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e302d3838393242462e737667)](https://php.net)

A modern, framework-agnostic PHP SDK for [Bank Alfalah](https://www.bankalfalah.com/) payment gateway with first-class **Laravel** support.

Supports **all 7 payment methods**: Credit/Debit Card, Alfa Wallet, Bank Alfalah Account, Alfa Islamic BNPL, Card on Delivery, JazzCash Wallet, and Raast QR.

---

Features
--------

[](#features)

- **Framework-agnostic** — works with Laravel, Symfony, CodeIgniter, Yii, or plain PHP
- **All 7 payment types** supported out of the box
- **SSO redirect flow** — handshake → redirect → IPN verification
- **Zero dependencies** — only requires `ext-openssl`, `ext-json`, `ext-curl`
- **Laravel auto-discovery** — service provider, facade, and config publishing
- **Typed responses** — `HandshakeResponse`, `IpnResponse` with enum-based status
- **Modern PHP 8.0+** — enums, named arguments, strict types
- **IPN retry** — built-in retry mechanism for payment verification
- **AES-128-CBC encryption** — exact Bank Alfalah specification

---

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

[](#installation)

```
composer require numanrki/bank-alfalah
```

### Requirements

[](#requirements)

- PHP &gt;= 8.0
- OpenSSL extension
- JSON extension
- cURL extension

---

Quick Start (Plain PHP)
-----------------------

[](#quick-start-plain-php)

```
use Numanrki\BankAlfalah\BankAlfalah;
use Numanrki\BankAlfalah\Transaction;
use Numanrki\BankAlfalah\Enums\PaymentType;

// 1. Create gateway instance
$gateway = BankAlfalah::make([
    'merchant_id'       => 'YOUR_MERCHANT_ID',
    'store_id'          => 'YOUR_STORE_ID',
    'merchant_hash'     => 'YOUR_MERCHANT_HASH',
    'merchant_username' => 'YOUR_USERNAME',
    'merchant_password' => 'YOUR_PASSWORD',
    'key1'              => 'YOUR_KEY_1',
    'key2'              => 'YOUR_KEY_2',
    'sandbox'           => true, // false for production
]);

// 2. Create a transaction
$transaction = Transaction::create('ORDER-001', 1500.00)
    ->currency('PKR')
    ->paymentType(PaymentType::CreditDebitCard)
    ->returnUrl('https://yoursite.com/payment/callback')
    ->email('customer@example.com')
    ->phone('03001234567');

// 3. Perform handshake
$handshake = $gateway->handshake($transaction);

// 4. Redirect customer to Bank Alfalah
echo $gateway->buildRedirectPage($handshake, $transaction);
exit;
```

### Verify Payment (on callback URL)

[](#verify-payment-on-callback-url)

```
// After customer returns from Bank Alfalah portal
$response = $gateway->checkStatus('ORDER-001');

if ($response->isPaid()) {
    // Payment successful — update your order
    echo "Payment confirmed!";
} elseif ($response->isFailed()) {
    // Payment failed
    echo "Payment failed.";
} else {
    // Pending — check again later (use cron/scheduled job)
    echo "Payment pending, will verify shortly.";
}
```

### Verify with Retry (recommended for callback URL)

[](#verify-with-retry-recommended-for-callback-url)

```
// Retries 5 times with 3-second intervals
$response = $gateway->checkStatusWithRetry('ORDER-001', maxRetries: 5, delaySeconds: 3);

if ($response->isPaid()) {
    // Confirmed
}
```

---

Laravel Setup
-------------

[](#laravel-setup)

### 1. Publish config file

[](#1-publish-config-file)

```
php artisan vendor:publish --tag=bankalfalah-config
```

This creates `config/bankalfalah.php`.

### 2. Add to `.env`

[](#2-add-to-env)

```
BANK_ALFALAH_MERCHANT_ID=your_merchant_id
BANK_ALFALAH_STORE_ID=your_store_id
BANK_ALFALAH_MERCHANT_HASH=your_merchant_hash
BANK_ALFALAH_MERCHANT_USERNAME=your_username
BANK_ALFALAH_MERCHANT_PASSWORD=your_password
BANK_ALFALAH_KEY1=your_key_1
BANK_ALFALAH_KEY2=your_key_2
BANK_ALFALAH_SANDBOX=true
```

### 3. Use in Controller

[](#3-use-in-controller)

```
use Numanrki\BankAlfalah\BankAlfalah;
use Numanrki\BankAlfalah\Transaction;
use Numanrki\BankAlfalah\Enums\PaymentType;

class PaymentController extends Controller
{
    public function pay(BankAlfalah $gateway)
    {
        $transaction = Transaction::create('INV-' . time(), 2500.00)
            ->currency('PKR')
            ->paymentType(PaymentType::CreditDebitCard)
            ->returnUrl(route('payment.callback'))
            ->email('customer@example.com');

        $handshake = $gateway->handshake($transaction);

        return response($gateway->buildRedirectPage($handshake, $transaction));
    }

    public function callback(BankAlfalah $gateway, Request $request)
    {
        $response = $gateway->checkStatusWithRetry('INV-123456789');

        if ($response->isPaid()) {
            return redirect('/thank-you');
        }

        return redirect('/payment-failed');
    }
}
```

### Using the Facade

[](#using-the-facade)

```
use Numanrki\BankAlfalah\Laravel\Facades\BankAlfalah;
use Numanrki\BankAlfalah\Transaction;
use Numanrki\BankAlfalah\Enums\PaymentType;

$transaction = Transaction::create('ORD-100', 5000)
    ->currency('PKR')
    ->paymentType(PaymentType::AlfaWallet)
    ->returnUrl(route('payment.callback'));

$handshake = BankAlfalah::handshake($transaction);
return response(BankAlfalah::buildRedirectPage($handshake, $transaction));
```

---

Payment Types
-------------

[](#payment-types)

EnumValueMethod`PaymentType::CreditDebitCard``3`Visa / Mastercard`PaymentType::AlfaWallet``1`Alfa Wallet`PaymentType::BankAccount``2`Bank Alfalah Account`PaymentType::BNPL``5`Alfa Islamic BNPL`PaymentType::CardOnDelivery``6`Card on Delivery`PaymentType::JazzCash``11`JazzCash Wallet`PaymentType::RaastQR``12`Raast QRGet all types as an array:

```
$allTypes = PaymentType::all();
// ['1' => 'Alfa Wallet', '2' => 'Bank Alfalah Account', '3' => 'Credit/Debit Card', ...]
```

---

Payment Flow
------------

[](#payment-flow)

```
┌──────────────┐     1. Handshake      ┌───────────────────┐
│  Your Server │ ───────────────────▶  │  Bank Alfalah API │
│              │ ◀──────────────────── │  /HS/HS/HS        │
│              │     AuthToken          └───────────────────┘
│              │
│              │     2. SSO Redirect    ┌───────────────────┐
│              │ ──── (HTML Form) ────▶ │  Bank Alfalah     │
│              │                        │  Payment Portal   │
│              │                        │  /SSO/SSO/SSO     │
│              │                        └───────────────────┘
│              │                               │
│              │     3. Customer returns        │
│              │ ◀─────────────────────────────┘
│              │
│              │     4. IPN Check        ┌───────────────────┐
│              │ ───────────────────▶   │  Bank Alfalah IPN │
│              │ ◀──────────────────── │  /HS/api/IPN/...  │
└──────────────┘     Paid / Failed      └───────────────────┘

```

### API Endpoints

[](#api-endpoints)

EndpointSandboxProductionHandshake`https://sandbox.bankalfalah.com/HS/HS/HS``https://payments.bankalfalah.com/HS/HS/HS`SSO`https://sandbox.bankalfalah.com/SSO/SSO/SSO``https://payments.bankalfalah.com/SSO/SSO/SSO`IPN`https://sandbox.bankalfalah.com/HS/api/IPN/OrderStatus/{MerchantId}/{StoreId}/{OrderRef}``https://payments.bankalfalah.com/HS/api/IPN/OrderStatus/{MerchantId}/{StoreId}/{OrderRef}`---

IPN Webhook / Cron Job
----------------------

[](#ipn-webhook--cron-job)

Bank Alfalah sends the customer back to your `returnUrl`, but the payment may still be processing. Use a cron job or scheduled task to verify pending payments:

### Laravel Scheduled Command

[](#laravel-scheduled-command)

```
// app/Console/Commands/VerifyPendingPayments.php
use Numanrki\BankAlfalah\BankAlfalah;

class VerifyPendingPayments extends Command
{
    protected $signature = 'payments:verify';

    public function handle(BankAlfalah $gateway)
    {
        $pendingOrders = Order::where('status', 'pending')->get();

        foreach ($pendingOrders as $order) {
            $response = $gateway->checkStatus($order->transaction_ref);

            if ($response->isPaid()) {
                $order->update(['status' => 'paid']);
            } elseif ($response->isFailed()) {
                $order->update(['status' => 'failed']);
            }
        }
    }
}
```

```
// app/Console/Kernel.php
$schedule->command('payments:verify')->everyFiveMinutes();
```

### Plain PHP Cron

[](#plain-php-cron)

```
// cron.php — run via crontab: */5 * * * * php /path/to/cron.php
require 'vendor/autoload.php';

$gateway = \Numanrki\BankAlfalah\BankAlfalah::make([/* your config */]);

$pendingOrders = get_pending_orders(); // your function

foreach ($pendingOrders as $order) {
    $response = $gateway->checkStatus($order['transaction_ref']);
    if ($response->isPaid()) {
        mark_as_paid($order['id']);
    }
}
```

---

Error Handling
--------------

[](#error-handling)

```
use Numanrki\BankAlfalah\Exceptions\InvalidConfigException;
use Numanrki\BankAlfalah\Exceptions\HandshakeException;
use Numanrki\BankAlfalah\Exceptions\PaymentException;

try {
    $handshake = $gateway->handshake($transaction);
} catch (InvalidConfigException $e) {
    // Missing merchant credentials
    echo "Configuration error: " . $e->getMessage();
} catch (HandshakeException $e) {
    // Bank Alfalah rejected the handshake
    echo "Gateway error: " . $e->getMessage();
} catch (PaymentException $e) {
    // General payment/connection error
    echo "Error: " . $e->getMessage();
}
```

---

IPN Response Properties
-----------------------

[](#ipn-response-properties)

```
$response = $gateway->checkStatus($transactionRef);

$response->isPaid();           // true if TransactionStatus === 'Paid'
$response->isFailed();         // true if TransactionStatus === 'Failed'
$response->isSessionEnded();   // true if TransactionStatus === 'SessionEnded'
$response->isDecided();        // true if paid OR failed (not pending)
$response->getStatus();        // TransactionStatus enum or null
$response->getTransactionRef();// Transaction reference number
$response->getRawData();       // Full response array from Bank Alfalah
```

---

Configuration Reference
-----------------------

[](#configuration-reference)

KeyDescriptionRequired`merchant_id`Unique merchant identifier from Bank AlfalahYes`store_id`Store/location identifierYes`merchant_hash`Authentication hash from Bank AlfalahYes`merchant_username`API usernameYes`merchant_password`API passwordYes`key1`AES-128-CBC encryption keyYes`key2`AES-128-CBC initialization vector (IV)Yes`sandbox``true` for sandbox, `false` for productionNo (default: `false`)---

Migrating from Other Packages
-----------------------------

[](#migrating-from-other-packages)

### From `naeemz/alfapay` or `zfhassaan/alfa`

[](#from-naeemzalfapay-or-zfhassaanalfa)

This package provides a cleaner, more complete implementation:

1. Replace `composer require` with `numanrki/bank-alfalah`
2. Update env variables from `ALFAPAY_*` to `BANK_ALFALAH_*`
3. Use the `Transaction` builder instead of setter chains
4. SSO redirect is built-in (no manual form building needed)
5. IPN verification with retry is built-in
6. All 7 payment types work out of the box

---

Credits
-------

[](#credits)

- [Numan (@numanrki)](https://github.com/numanrki)
- Built on top of the Bank Alfalah payment gateway specification

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance79

Regular maintenance activity

Popularity0

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

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

Unknown

Total

1

Last Release

109d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/43486441?v=4)[Numan Rasheed](/maintainers/numanrki)[@numanrki](https://github.com/numanrki)

---

Tags

phplaravelpaymentecommercepayment gatewaycredit-cardbnplpakistanjazzcashalfabank-alfalahraastalfa-walletalfalah

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/numanrki-bank-alfalah/health.svg)

```
[![Health](https://phpackages.com/badges/numanrki-bank-alfalah/health.svg)](https://phpackages.com/packages/numanrki-bank-alfalah)
```

PHPackages © 2026

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