PHPackages                             sabitahmad/laravel-bkash - 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. sabitahmad/laravel-bkash

ActiveLibrary[Payment Processing](/categories/payments)

sabitahmad/laravel-bkash
========================

Unofficial Bkash Package for Laravel providing seamless integration with Bkash payment gateway.

v2.0.0(7mo ago)058[3 PRs](https://github.com/sabitahmadumid/laravel-bkash/pulls)1MITPHPPHP ^8.0CI passing

Since Apr 2Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/sabitahmadumid/laravel-bkash)[ Packagist](https://packagist.org/packages/sabitahmad/laravel-bkash)[ Docs](https://github.com/sabitahmad/laravel-bkash)[ GitHub Sponsors](https://github.com/SabitAhmad)[ RSS](/packages/sabitahmad-laravel-bkash/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (6)Used By (1)

Laravel bKash Payment Gateway Integration
=========================================

[](#laravel-bkash-payment-gateway-integration)

[![Latest Version on Packagist](https://camo.githubusercontent.com/3b17cee2b41e131dfa40e186d7a4833f49343865dc52949aa74972c2a7b42111/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736162697461686d61642f6c61726176656c2d626b6173682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sabitahmad/laravel-bkash)[![Total Downloads](https://camo.githubusercontent.com/e8ec99fd59f1b98c02b49421de6fccae1395f82cef7ee55fc508b3a4b98d0229/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f736162697461686d61642f6c61726176656c2d626b6173682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sabitahmad/laravel-bkash)

A comprehensive solution for integrating bKash payments into Laravel applications.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Response Handling](#paymentresponse-methods)
- [License](#license)

---

Features
--------

[](#features)

- **Complete bKash API v1.2.0 Integration**: Full support for all bKash APIs
- **Tokenized Checkout**: Agreement management for faster payments
- **Regular Checkout**: Traditional payment flow
- **Sandbox &amp; Production Modes**: Easy environment switching
- **Advanced Token Management**: Auto-refresh with retry mechanisms
- **Comprehensive Payment Operations**: Create, Execute, Query, Refund, Search
- **Agreement Management**: Create, Execute, Query, Cancel agreements
- **Enhanced Exception Handling**: Detailed error reporting and handling
- **Transaction Logging**: Database logging with enhanced tracking
- **Network Resilience**: Automatic retries and timeout handling
- **Parameter Validation**: Strict validation with configurable options
- **Helper Utilities**: Common operations and utilities
- **Event-driven Architecture**: Laravel events integration
- **Customizable Configuration**: Flexible configuration options

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

[](#requirements)

- PHP 8.0+
- Laravel 9.x+
- Composer
- bKash Merchant Account

---

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

[](#installation)

You can install the package via composer:

```
composer require sabitahmad/laravel-bkash
```

You can publish and run the migrations with:

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

You can publish the config file with:

```
php artisan vendor:publish --tag="laravel-bkash-config"
```

This is the contents of the published config file:

```
return [
    'sandbox' => env('BKASH_SANDBOX', true),
    'log_transactions' => env('BKASH_LOG_TRANSACTIONS', true),
    'credentials' => [
        'app_key' => env('BKASH_APP_KEY'),
        'app_secret' => env('BKASH_APP_SECRET'),
        'username' => env('BKASH_USERNAME'),
        'password' => env('BKASH_PASSWORD'),
    ],
    'urls' => [
        'sandbox' => [
            'token' => 'https://checkout.sandbox.bka.sh/v1.2.0-beta/checkout/token/grant',
            // ... other endpoints
        ],
        'production' => [
            // Production endpoints
        ]
    ],
    'callback_url' => env('BKASH_CALLBACK_URL', '/bkash/callback'),
    'redirect_url' => env('BKASH_REDIRECT_URL', '/payment/redirect'),
];
```

Optionally, you can publish the views using

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

[](#configuration)

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

```
# Required Configuration
BKASH_SANDBOX=true
BKASH_APP_KEY=your_app_key
BKASH_APP_SECRET=your_app_secret
BKASH_USERNAME=your_username
BKASH_PASSWORD=your_password

# URL Configuration
BKASH_CALLBACK_URL=/bkash/callback
BKASH_REDIRECT_URL=/payment/redirect

# Optional Configuration
BKASH_LOG_TRANSACTIONS=true
BKASH_TIMEOUT=30
BKASH_RETRY_ATTEMPTS=3
BKASH_RETRY_DELAY=1000
BKASH_TOKEN_CACHE_TTL=3300
BKASH_CURRENCY=BDT

# Validation Settings
BKASH_STRICT_VALIDATION=true
BKASH_MAX_AMOUNT=999999.99
BKASH_MIN_AMOUNT=1.00
```

Usage
-----

[](#usage)

### Agreement Management (Tokenized Checkout)

[](#agreement-management-tokenized-checkout)

#### Create Agreement

[](#create-agreement)

```
use SabitAhmad\Bkash\Facades\Bkash;
use SabitAhmad\Bkash\Exceptions\BkashException;

try {
    $agreement = Bkash::createAgreement('CUST-001');

    if ($agreement->isSuccess()) {
        // Redirect user to bKash for agreement
        return redirect()->away($agreement->getAgreementUrl());
    }

    throw new Exception('Agreement creation failed: ' . $agreement->getErrorMessage());
} catch (BkashException $e) {
    // Handle exception
}
```

#### Execute Agreement

[](#execute-agreement)

```
// After user completes agreement on bKash page
$agreement = Bkash::executeAgreement($paymentId);

if ($agreement->isSuccess()) {
    $agreementId = $agreement->getAgreementId();
    // Store agreementId for future payments
}
```

### Payment Operations

[](#payment-operations)

#### Create Payment (Regular)

[](#create-payment-regular)

```
try {
    $payment = Bkash::createPayment(
        payerReference: 'CUST-001',
        amount: 100.50,
        invoiceNumber: 'INV-001'
    );

    if ($payment->isSuccess()) {
        return redirect()->away($payment->getPaymentUrl());
    }

    throw new Exception('Payment creation failed: ' . $payment->getErrorMessage());
} catch (BkashException $e) {
    // Handle exception
}
```

#### Create Payment (Tokenized with Agreement)

[](#create-payment-tokenized-with-agreement)

```
try {
    $payment = Bkash::createPayment(
        payerReference: 'CUST-001',
        amount: 100.50,
        invoiceNumber: 'INV-001',
        callbackURL: '/payment/callback',
        agreementId: 'AGR123456' // Use existing agreement
    );

    if ($payment->isSuccess()) {
        return redirect()->away($payment->getPaymentUrl());
    }
} catch (BkashException $e) {
    // Handle exception
}
```

### `Execute Payment`

[](#execute-payment)

```
$execution = Bkash::executePayment($paymentId);

if ($execution->getTransactionStatus() === 'Completed') {
    // Payment successful
    $trxId = $execution->getTrxId();
}
```

### `Handle Callback`

[](#handle-callback)

```
Route::post('/bkash/callback', function (Request $request) {
    $payment = Bkash::executePayment($request->paymentID);

    if ($payment->isSuccess()) {
        event(new PaymentCompleted($payment));
        return redirect('/success');
    }

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

### Additional Operations

[](#additional-operations)

#### Refund Payment

[](#refund-payment)

```
$refund = Bkash::refundPayment('TRX123456', 100.50, 'Customer requested refund');

if ($refund->isSuccess()) {
    $refundId = $refund->getRefundId();
    echo "Refund successful. Refund ID: {$refundId}";
}
```

#### Query Payment Status

[](#query-payment-status)

```
$query = Bkash::queryPayment('PAY123456');

if ($query->isCompleted()) {
    echo "Payment completed successfully";
    echo "Transaction ID: " . $query->getTrxId();
}
```

#### Search Transaction

[](#search-transaction)

```
$search = Bkash::searchTransaction('TRX123456');

if ($search->isSuccess()) {
    $transactions = $search->getTransactions();
    foreach ($transactions as $transaction) {
        echo "Amount: " . $transaction['amount'];
        echo "Status: " . $transaction['transactionStatus'];
    }
}
```

#### Refund Status Check

[](#refund-status-check)

```
$refundStatus = Bkash::refundStatus('PAY123456', 'REF789012');

if ($refundStatus->isSuccess()) {
    echo "Refund Status: " . $refundStatus->getTransactionStatus();
}
```

#### Agreement Operations

[](#agreement-operations)

```
// Query Agreement
$agreement = Bkash::queryAgreement('AGR123456');

// Cancel Agreement
$cancelResult = Bkash::cancelAgreement('AGR123456');
```

### Using the Helper Class

[](#using-the-helper-class)

```
use SabitAhmad\Bkash\Helpers\BkashHelper;

$helper = new BkashHelper(app(Bkash::class));

// Process complete payment flow
$payment = $helper->processPayment('CUST-001', 100.50, 'INV-001');

// Handle callback
$result = $helper->handleCallback($request->all());

// Get payment status with detailed info
$status = $helper->getPaymentStatus('PAY123456');

// Generate unique references
$payerRef = BkashHelper::generatePayerReference('CUSTOMER');
$invoiceNum = BkashHelper::generateInvoiceNumber('ORDER');
```

Response Methods
----------------

[](#response-methods)

### BaseResponse Methods (Available in All Response Classes)

[](#baseresponse-methods-available-in-all-response-classes)

MethodReturnsDescription`isSuccess()``bool`Whether operation succeeded`hasError()``bool`Whether operation has error`getErrorMessage()``?string`Error message if failed`getStatusCode()``?string`bKash status code`getStatusMessage()``?string`bKash status message`getErrorCode()``?string`bKash error code`getRawData()``array`Complete API response`toArray()``array`Response as array### PaymentResponse Methods

[](#paymentresponse-methods)

MethodReturnsDescription`getPaymentId()``?string`Payment ID`getPaymentUrl()``?string`Redirect URL for payment`getTrxId()``?string`bKash transaction ID`getAmount()``?float`Transaction amount`getCustomerMsisdn()``?string`Customer phone number`getTransactionStatus()``?string`"Completed"/"Failed" etc`getInvoiceNumber()``?string`Merchant invoice number`getPayerReference()``?string`Payer reference`getCurrency()``?string`Transaction currency`getIntent()``?string`Payment intent`getMode()``?string`Payment mode`getPaymentExecuteTime()``?Carbon`Execution timestamp`getCreateTime()``?Carbon`Creation timestamp`getUpdateTime()``?Carbon`Last update timestamp`isCompleted()``bool`Whether payment completed`isCancelled()``bool`Whether payment cancelled`isFailed()``bool`Whether payment failed### AgreementResponse Methods

[](#agreementresponse-methods)

MethodReturnsDescription`getAgreementId()``?string`Agreement ID`getAgreementUrl()``?string`Redirect URL for agreement`getAgreementStatus()``?string`Agreement status`getPayerReference()``?string`Payer reference`getCustomerMsisdn()``?string`Customer phone number`getAgreementExecuteTime()``?Carbon`Agreement execution time### RefundResponse Methods

[](#refundresponse-methods)

MethodReturnsDescription`getRefundId()``?string`Refund transaction ID`getOriginalPaymentId()``?string`Original payment ID`getRefundAmount()``?float`Refunded amount`getTransactionStatus()``?string`Refund status`getRefundTime()``?Carbon`Refund timestamp`getCharge()``?float`Refund charge`getTrxId()``?string`Transaction ID`getPaymentId()``?string`Payment ID`getCurrency()``?string`Currency`getReason()``?string`Refund reason### QueryResponse Methods

[](#queryresponse-methods)

MethodReturnsDescription`getPaymentId()``?string`Payment ID`getTrxId()``?string`Transaction ID`getTransactionStatus()``?string`Current payment status`getAmount()``?float`Transaction amount`getCustomerMsisdn()``?string`Customer phone number`getMerchantInvoiceNumber()``?string`Invoice number`getCurrency()``?string`Transaction currency`getIntent()``?string`Payment intent`getInitiationTime()``?Carbon`Transaction initiation time`getCompletedTime()``?Carbon`Transaction completion time`isCompleted()``bool`Whether transaction completed`isCancelled()``bool`Whether transaction cancelled`isFailed()``bool`Whether transaction failed### SearchResponse Methods

[](#searchresponse-methods)

MethodReturnsDescription`getTransactions()``array`Array of transactions`getTransactionCount()``int`Number of transactions`getFirstTransaction()``?array`First transaction`getTransactionByTrxId()``?array`Find transaction by trx ID`getTransactionByPaymentId()``?array`Find transaction by payment IDController Example
------------------

[](#controller-example)

See `examples/BkashController.php` for a complete implementation example showing:

- Agreement creation and handling
- Payment processing (both regular and tokenized)
- Callback handling
- Refund processing
- Transaction querying and searching
- Error handling

Events
------

[](#events)

The package dispatches the following events:

- `SabitAhmad\Bkash\Events\PaymentCompleted` - When a payment is successfully completed
- `SabitAhmad\Bkash\Events\PaymentFailed` - When a payment fails
- `SabitAhmad\Bkash\Events\AgreementCreated` - When an agreement is successfully created

You can listen to these events in your `EventServiceProvider`:

```
protected $listen = [
    \SabitAhmad\Bkash\Events\PaymentCompleted::class => [
        \App\Listeners\HandlePaymentCompleted::class,
    ],
    \SabitAhmad\Bkash\Events\PaymentFailed::class => [
        \App\Listeners\HandlePaymentFailed::class,
    ],
];
```

Configuration Options
---------------------

[](#configuration-options)

The package supports extensive configuration options:

- **Timeout Settings**: Configure API request timeouts and retry attempts
- **Validation**: Strict parameter validation with configurable limits
- **Caching**: Token caching with configurable TTL
- **Logging**: Enhanced transaction logging with detailed information
- **Error Handling**: Comprehensive error handling with retry mechanisms

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Recent Improvements
-------------------

[](#recent-improvements)

### Version 2.0.0 (Latest)

[](#version-200-latest)

- ✅ **Complete Tokenized Checkout Support** - Agreement management APIs
- ✅ **Enhanced Response Classes** - More methods and better data access
- ✅ **Advanced Error Handling** - Retry mechanisms and detailed exceptions
- ✅ **Network Resilience** - Automatic retries and timeout handling
- ✅ **Search Transaction API** - Find transactions by various criteria
- ✅ **Refund Status API** - Track refund progress
- ✅ **Helper Utilities** - Common operations and utilities
- ✅ **Event System** - Laravel events for payment lifecycle
- ✅ **Enhanced Database Logging** - Better transaction tracking
- ✅ **Improved Configuration** - More flexible settings
- ✅ **Parameter Validation** - Strict validation with configurable options
- ✅ **Code Optimization** - Removed duplicates and improved performance
- ✅ **Updated API URLs** - Latest bKash endpoint configurations
- ✅ **Better Token Management** - Enhanced caching and refresh logic

Credits
-------

[](#credits)

- [Sabit Ahmad](https://github.com/SabitAhmad)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance79

Regular maintenance activity

Popularity12

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 50% 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 ~175 days

Total

2

Last Release

230d ago

Major Versions

v1.0.0 → v2.0.02025-09-24

### Community

Maintainers

![](https://www.gravatar.com/avatar/61b5e04c3c2f57034b9f4ca411ec4f4c4d4d7e63eb9780a0865d101f6cee135c?d=identicon)[sabitahmadumid](/maintainers/sabitahmadumid)

---

Top Contributors

[![sabitahmadumid](https://avatars.githubusercontent.com/u/185702986?v=4)](https://github.com/sabitahmadumid "sabitahmadumid (6 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (3 commits)")

---

Tags

laravellaravel-bkashSabitAhmad

###  Code Quality

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/sabitahmad-laravel-bkash/health.svg)

```
[![Health](https://phpackages.com/badges/sabitahmad-laravel-bkash/health.svg)](https://phpackages.com/packages/sabitahmad-laravel-bkash)
```

###  Alternatives

[vormkracht10/laravel-mails

Laravel Mails can collect everything you might want to track about the mails that has been sent by your Laravel app.

24149.7k](/packages/vormkracht10-laravel-mails)[danestves/laravel-polar

A package to easily integrate your Laravel application with Polar.sh

7812.3k](/packages/danestves-laravel-polar)[musahmusah/laravel-multipayment-gateways

A Laravel Package that makes implementation of multiple payment Gateways endpoints and webhooks seamless

852.2k1](/packages/musahmusah-laravel-multipayment-gateways)[creagia/laravel-redsys

Laravel Redsys Payments Gateway

2013.6k](/packages/creagia-laravel-redsys)

PHPackages © 2026

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