PHPackages                             rayhan-bapari/bkash-payment - 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. rayhan-bapari/bkash-payment

ActiveLibrary[Payment Processing](/categories/payments)

rayhan-bapari/bkash-payment
===========================

A production-ready Laravel package for bKash Tokenized Checkout Payment Gateway — with token caching, webhook/IPN support, refund, search, and more. Supports Laravel 9–12 and PHP 8.1–8.5.

v1.0.0(3mo ago)05MITPHPPHP ^8.1

Since Mar 9Pushed 3mo agoCompare

[ Source](https://github.com/rayhan-bapari/bkash-payment)[ Packagist](https://packagist.org/packages/rayhan-bapari/bkash-payment)[ Docs](https://github.com/rayhan-bapari/bkash-payment)[ RSS](/packages/rayhan-bapari-bkash-payment/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (1)Dependencies (8)Versions (2)Used By (0)

bKash Payment for Laravel
=========================

[](#bkash-payment-for-laravel)

[![Packagist Version](https://camo.githubusercontent.com/c312185d349aefe90017e35d63de4af6181167d01b5e1fe57e56fab2ac327ecc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f72617968616e2d6261706172692f626b6173682d7061796d656e742e737667)](https://packagist.org/packages/rayhan-bapari/bkash-payment)[![PHP Version](https://camo.githubusercontent.com/d4f43df4fd4f9579c57917e84ecebf579c1ce460880b791696ae8f5f7d739ca5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e31253230254532253830253933253230382e352d626c75652e737667)](https://php.net)[![Laravel](https://camo.githubusercontent.com/15bab99ebfaae48be42fab2f19f544ec2d4269c25ab1d819303be66cac1f734f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d3925323025453225383025393325323031322d7265642e737667)](https://laravel.com)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](LICENSE)

A production-ready Laravel package for **bKash Tokenized Checkout** payment gateway integration.

**Features:**

- ✅ Create, execute, query, and verify payments
- ✅ Refund &amp; refund status
- ✅ Transaction search by TrxID
- ✅ Database token caching (ID token + refresh token)
- ✅ IPN / Webhook support (Amazon SNS format with subscription confirmation)
- ✅ Optional HMAC-SHA256 webhook signature verification
- ✅ AWS SNS signature verification (RSA + SHA1)
- ✅ Full webhook payload logging to database
- ✅ Laravel Facade &amp; dependency injection support
- ✅ Laravel 9 / 10 / 11 / 12 · PHP 8.1 / 8.2 / 8.3 / 8.4 / 8.5

---

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

[](#requirements)

DependencyVersionPHP^8.1Laravel^9.0 | ^10.0 | ^11.0 | ^12.0ext-curl\*ext-json\*ext-openssl\*---

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

[](#installation)

```
composer require rayhan-bapari/bkash-payment
```

### Publish config &amp; migrations

[](#publish-config--migrations)

```
php artisan vendor:publish --tag=bkash-config
php artisan vendor:publish --tag=bkash-migrations
php artisan migrate
```

---

Configuration
-------------

[](#configuration)

Add the following variables to your `.env` file:

```
# --- Environment ---
BKASH_SANDBOX=true          # true = sandbox, false = production

# --- Merchant credentials (provided by bKash during onboarding) ---
BKASH_USERNAME=your_username
BKASH_PASSWORD=your_password
BKASH_APP_KEY=your_app_key
BKASH_APP_SECRET=your_app_secret

# --- Payment defaults ---
BKASH_CALLBACK_URL=https://yourdomain.com/bkash/callback

# --- Webhook / IPN ---
BKASH_WEBHOOK_ENABLED=true
BKASH_WEBHOOK_PATH=bkash/webhook
BKASH_WEBHOOK_SECRET=          # optional extra HMAC layer
BKASH_WEBHOOK_VERIFY_SSL=true
BKASH_WEBHOOK_LOG_PAYLOADS=true
```

---

Usage
-----

[](#usage)

### Via Facade

[](#via-facade)

```
use RayhanBapari\BkashPayment\Facades\BkashPayment;
```

### Via Dependency Injection

[](#via-dependency-injection)

```
use RayhanBapari\BkashPayment\Contracts\BkashPaymentInterface;

public function __construct(protected BkashPaymentInterface $bkash) {}
```

---

### 1. Create Payment

[](#1-create-payment)

```
$response = BkashPayment::createPayment([
    'amount'                => '100.00',
    'merchantInvoiceNumber' => 'INV-' . time(),
    'callbackURL'           => route('bkash.callback'),   // or omit to use config default
    'payerReference'        => '01712345678',             // optional
]);

// Redirect user to bKash checkout
if (isset($response['bkashURL'])) {
    return redirect($response['bkashURL']);
}
```

**Response:**

```
{
  "statusCode": "0000",
  "statusMessage": "Successful",
  "paymentID": "TR0011abc123",
  "bkashURL": "https://sandbox.payment.bkash.com/?paymentId=...",
  "callbackURL": "https://yourdomain.com/bkash/callback",
  "amount": "100.00",
  "currency": "BDT",
  "intent": "sale",
  "merchantInvoiceNumber": "INV-1718449546"
}
```

---

### 2. Handle Callback (Execute &amp; Verify)

[](#2-handle-callback-execute--verify)

After the user completes payment on the bKash page, bKash redirects back to your `callbackURL` with `paymentID` and `status` query parameters.

```
// routes/web.php
Route::get('/bkash/callback', [BkashController::class, 'callback'])->name('bkash.callback');
```

```
// BkashController.php
public function callback(Request $request): RedirectResponse
{
    $paymentID = $request->query('paymentID');
    $status    = $request->query('status');

    if ($status === 'cancel') {
        return redirect()->route('checkout')->with('error', 'Payment cancelled.');
    }

    if ($status === 'failure') {
        return redirect()->route('checkout')->with('error', 'Payment failed.');
    }

    // status === 'success' — verify the payment
    $result = BkashPayment::verifyPayment($paymentID);

    if ($result['success']) {
        // Payment confirmed — store the TrxID in your orders table
        // $result['trxID'], $result['amount']
        return redirect()->route('order.success')->with('trxID', $result['trxID']);
    }

    return redirect()->route('checkout')->with('error', $result['message']);
}
```

---

### 3. Execute Payment (manual)

[](#3-execute-payment-manual)

```
$response = BkashPayment::executePayment('TR0011abc123');
```

---

### 4. Query Payment Status

[](#4-query-payment-status)

```
$response = BkashPayment::queryPayment('TR0011abc123');
```

---

### 5. Search Transaction by TrxID

[](#5-search-transaction-by-trxid)

```
$response = BkashPayment::searchTransaction('BK0011XYZ');
```

---

### 6. Refund

[](#6-refund)

```
$response = BkashPayment::refund([
    'paymentID' => 'TR0011abc123',
    'trxID'     => 'BK0011XYZ',
    'amount'    => '50.00',
    'reason'    => 'Customer requested refund',
    'sku'       => 'ITEM-001',               // optional
]);
```

**Refund response:**

```
{
  "statusCode": "0000",
  "statusMessage": "Successful",
  "originalTrxID": "BK0011XYZ",
  "refundTrxID": "BK0099REF",
  "transactionStatus": "Completed",
  "amount": "50.00",
  "currency": "BDT"
}
```

---

### 7. Refund Status

[](#7-refund-status)

```
$response = BkashPayment::refundStatus('TR0011abc123', 'BK0011XYZ');
```

---

Webhook / IPN
-------------

[](#webhook--ipn)

bKash delivers payment event notifications as **Amazon SNS HTTP messages** to your endpoint.

### How it works

[](#how-it-works)

1. You share your webhook URL with the bKash technical team during onboarding.
2. bKash sends a `SubscriptionConfirmation` — the package automatically visits the `SubscribeURL` to activate the subscription.
3. After confirmation, bKash POSTs `Notification` messages for each completed transaction.

### Default webhook URL

[](#default-webhook-url)

```
POST https://yourdomain.com/bkash/webhook

```

Override via `BKASH_WEBHOOK_PATH` in `.env`.

### Listening to webhook events in your app

[](#listening-to-webhook-events-in-your-app)

The package fires a Laravel event `bkash.webhook.notification` for every notification. Register a listener in your `EventServiceProvider`:

```
// app/Providers/EventServiceProvider.php
protected $listen = [
    'bkash.webhook.notification' => [
        App\Listeners\HandleBkashWebhook::class,
    ],
];
```

```
// app/Listeners/HandleBkashWebhook.php
namespace App\Listeners;

class HandleBkashWebhook
{
    public function handle(array $payload): void
    {
        $trxID  = $payload['trxID'];
        $status = $payload['transactionStatus'];  // "Completed"
        $amount = $payload['amount'];
        $invoice= $payload['merchantInvoiceNumber'];

        // Update your order/transaction record here
    }
}
```

### Notification payload fields

[](#notification-payload-fields)

FieldDescription`trxID`bKash transaction ID`transactionStatus``Completed` | `Initiated` | etc.`amount`Actual deducted amount`saleAmount`Original sale amount (before coupon)`currency``BDT``dateTime`Transaction datetime (`YYYYMMDDHHmmss`)`debitMSISDN`Customer's bKash wallet number`merchantInvoiceNumber`Your invoice number`transactionReference`Payer reference value`couponAmount`Coupon discount (if any)### CSRF Exclusion

[](#csrf-exclusion)

Add the webhook path to your CSRF exclusions if using `web` middleware:

```
// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
    'bkash/webhook',
];
```

### Optional: Extra HMAC verification

[](#optional-extra-hmac-verification)

Set `BKASH_WEBHOOK_SECRET` in `.env` if your setup sends an `X-Bkash-Signature` header alongside requests for an extra validation layer.

---

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

[](#database-tables)

TablePurpose`bkash_tokens`Caches ID &amp; refresh tokens per environment`bkash_webhook_logs`Stores raw + parsed IPN payloads---

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

[](#error-handling)

The package throws typed exceptions:

ExceptionWhen`BkashAuthException`Token grant or refresh fails`BkashPaymentException`Empty/invalid response from bKash API`BkashWebhookException`Invalid/untrusted webhook payload```
use RayhanBapari\BkashPayment\Exceptions\BkashAuthException;
use RayhanBapari\BkashPayment\Exceptions\BkashPaymentException;

try {
    $result = BkashPayment::createPayment([...]);
} catch (BkashAuthException $e) {
    // Credentials or token issue
} catch (BkashPaymentException $e) {
    // API communication issue
}
```

---

Sandbox Testing
---------------

[](#sandbox-testing)

Set `BKASH_SANDBOX=true` and use your sandbox credentials. The package routes all requests to:

```
https://tokenized.sandbox.bka.sh/v1.2.0-beta

```

---

License
-------

[](#license)

MIT © [Rayhan Bapari](https://github.com/rayhan-bapari)

bkash-payment
=============

[](#bkash-payment)

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance79

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

Unknown

Total

1

Last Release

109d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/126815340?v=4)[Md Rayhan Bapari](/maintainers/rayhan-bapari)[@rayhan-bapari](https://github.com/rayhan-bapari)

---

Top Contributors

[![rayhan-bapari](https://avatars.githubusercontent.com/u/126815340?v=4)](https://github.com/rayhan-bapari "rayhan-bapari (1 commits)")

---

Tags

laravelpaymentgatewaywebhookcheckoutipnbkashbangladeshtokenizedmobile-financial-service

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/rayhan-bapari-bkash-payment/health.svg)

```
[![Health](https://phpackages.com/badges/rayhan-bapari-bkash-payment/health.svg)](https://phpackages.com/packages/rayhan-bapari-bkash-payment)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[laravel/cashier

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

2.5k28.4M137](/packages/laravel-cashier)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9742.3M121](/packages/roots-acorn)[api-platform/laravel

API Platform support for Laravel

59156.3k11](/packages/api-platform-laravel)[sebdesign/laravel-viva-payments

A Laravel package for integrating the Viva Payments gateway

4849.3k](/packages/sebdesign-laravel-viva-payments)

PHPackages © 2026

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