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

ActiveLibrary[Payment Processing](/categories/payments)

sslcommerz/laravel
==================

Production-ready Laravel package for SSLCOMMERZ payment gateway integration (API v4)

v1.1.2(3w ago)034MITPHPPHP ^8.1

Since May 18Pushed 3w agoCompare

[ Source](https://github.com/bdmotaleb/sslcommerz)[ Packagist](https://packagist.org/packages/sslcommerz/laravel)[ Docs](https://github.com/sslcommerz/SSLCommerz-Laravel)[ RSS](/packages/sslcommerz-laravel/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (18)Versions (5)Used By (0)

SSLCOMMERZ Laravel Package
==========================

[](#sslcommerz-laravel-package)

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

[](#table-of-contents)

- [Installation](#installation)
- [Configuration](#configuration)
- [Quick Start](#quick-start)
- [Payment Flow](#payment-flow)
- [Usage](#usage)
    - [Initiate Payment](#initiate-payment)
    - [Recurring Payments (Easycheckout)](#recurring-payments-easycheckout)
    - [Validate Transaction](#validate-transaction)
    - [Refund](#refund)
    - [Query Transaction](#query-transaction)
- [Callback Handling](#callback-handling)
    - [Redirect URLs After Payment](#redirect-urls-after-payment)
- [Events](#events)
- [Hash Verification](#hash-verification)
- [Custom Controllers](#custom-controllers)
- [Testing](#testing)
- [API Reference](#api-reference)
- [Security](#security)
- [Troubleshooting](#troubleshooting)

---

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

[](#installation)

```
composer require sslcommerz/laravel
```

### Publish Configuration

[](#publish-configuration)

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

### Publish Routes (Optional)

[](#publish-routes-optional)

```
php artisan vendor:publish --tag=sslcommerz-routes
```

### Publish Everything

[](#publish-everything)

```
php artisan vendor:publish --tag=sslcommerz
```

---

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

[](#configuration)

Add these variables to your `.env` file:

```
SSLCOMMERZ_SANDBOX=true
SSLCOMMERZ_STORE_ID=your_store_id
SSLCOMMERZ_STORE_PASSWORD=your_store_password
```

```
# Your application URL (IMPORTANT: SSLCOMMERZ sends callbacks to this URL)
APP_URL=https://yourdomain.com
```

> **Note:** `SSLCOMMERZ_SALT_KEY` is required for recurring payments (Easycheckout).

Quick Start
-----------

[](#quick-start)

```
use Sslcommerz\Laravel\Facades\SSLCOMMERZ;

public function checkout(Request $request)
{
    $response = SSLCOMMERZ::initiate([
        'tran_id'      => 'ORDER_' . uniqid(),
        'total_amount' => 1500.00,
        'cus_name'     => $request->name,
        'cus_email'    => $request->email,
        // ...
    ]);

    if ($response->isSuccessful()) {
        return $response->redirect(); // Fluent redirect to SSLCOMMERZ
    }

    return back()->with('error', $response->failedReason);
}
```

### Sandbox Test Credentials

[](#sandbox-test-credentials)

Register at  to get your sandbox credentials.

**Test Card Numbers:**

Card TypeNumberExpiryCVVVISA411111111111111112/36111Mastercard511111111111111112/36111Amex37111111111111112/36111**Mobile OTP:** `111111` or `123456`

---

Custom Controllers
------------------

[](#custom-controllers)

You can easily override the default callback behavior.

1. **Publish the Controller Stub:**

    ```
    php artisan vendor:publish --tag=sslcommerz-controller
    ```
2. **Update Configuration:**In your `config/sslcommerz.php`, update the `controller` option to point to your new controller:

    ```
    'routes' => [
        'controller' => \App\Http\Controllers\SslcommerzCallbackController::class,
        // ...
    ],
    ```
3. **Customize Logic:**Edit `app/Http/Controllers/SslcommerzCallbackController.php` to suit your needs.

> **Note:** If you want to customize the URLs, you can also publish the routes: `php artisan vendor:publish --tag=sslcommerz-routes`

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

[](#payment-flow)

```
┌──────────┐     ┌──────────────┐     ┌─────────────┐
│  Customer│────▶│  Your Server │────▶│ SSLCOMMERZ  │
│  Browser │     │  (Laravel)   │     │   API       │
└──────────┘     └──────────────┘     └─────────────┘
     │                  │                     │
     │  1. Checkout     │                     │
     │─────────────────▶│                     │
     │                  │  2. Create Session  │
     │                  │────────────────────▶│
     │                  │  3. GatewayPageURL  │
     │                  │◀────────────────────│
     │  4. Redirect     │                     │
     │◀─────────────────│                     │
     │                  │                     │
     │  5. Pay on SSLCOMMERZ page             │
     │───────────────────────────────────────▶│
     │                  │                     │
     │                  │  6. IPN Notification│
     │                  │◀────────────────────│
     │                  │  7. Validate (API)  │
     │                  │────────────────────▶│
     │                  │  8. VALID           │
     │                  │◀────────────────────│
     │                  │                     │
     │  9. Redirect to success_url            │
     │◀───────────────────────────────────────│
     │                  │                     │

```

---

Usage
-----

[](#usage)

### Initiate Payment

[](#initiate-payment)

```
use Sslcommerz\Laravel\Facades\SSLCOMMERZ;

$response = SSLCOMMERZ::initiate([
    'tran_id'          => 'ORDER_' . uniqid(),
    'total_amount'     => 1000.00,
    'cus_name'         => 'John Doe',
    'cus_email'        => 'john@example.com',
    'cus_phone'        => '01711111111',
    // ...
]);

if ($response['status'] === 'SUCCESS') {
    return $response->redirect();
}
```

#### Specialized Parameters (API v4)

[](#specialized-parameters-api-v4)

CategoryParameters**Airline**`pnr`, `hours_till_departure`, `flight_type`, `journey_from_to`, `third_party_booking`**Travel**`hotel_name`, `length_of_stay`, `check_in_time`, `hotel_city`**Telecom**`product_type`, `topup_number`, `country_topup`**Logistics**`logistic_pickup_id`, `logistic_delivery_type`### Recurring Payments (Easycheckout)

[](#recurring-payments-easycheckout)

SSLCOMMERZ supports recurring payments via a `schedule` parameter.

**1. Configure SALT Key:**Add `SSLCOMMERZ_SALT_KEY` to your `.env` file. This key is provided by the SSLCOMMERZ team.

**2. Initiate Recurring Payment:**

```
use Sslcommerz\Laravel\Facades\SSLCOMMERZ;

$schedule = json_encode([
    'refer'      => 'REF1234', // Plan ID from Merchant Panel
    'acct_no'    => 'CUS_001',  // Customer account reference
    'type'       => 'monthly',
    'dayofmonth' => '24',
]);

$encryptedSchedule = SSLCOMMERZ::getEncryptionService()->encrypt($schedule);

$response = SSLCOMMERZ::initiate([
    // ...
    'schedule'     => $encryptedSchedule,
]);

// If successful, a subscription_id will be returned in the callback/response
if ($response->isSuccessful()) {
    $subscriptionId = $response->subscriptionId;
}
```

**3. Manage Subscriptions:**

```
// Check status
$status = SSLCOMMERZ::getSubscriptionStatus($refer, $subscriptionId);

// Disable temporarily
SSLCOMMERZ::disableSubscription($refer, $subscriptionId);

// Re-enable
SSLCOMMERZ::enableSubscription($refer, $subscriptionId);

// Cancel permanently
SSLCOMMERZ::cancelSubscription($refer, $subscriptionId);
```

### Validate Transaction

[](#validate-transaction)

```
$validation = SSLCOMMERZ::validate($valId);

if ($validation->isSuccessful()) {
    // Payment confirmed - access via array or object
    echo "Amount: " . $validation['amount'];
    echo "Bank Transaction: " . $validation->bankTranId;
}
```

### Refund

[](#refund)

```
// Simply pass an array
$refund = SSLCOMMERZ::refund([
    'bank_tran_id'   => $bankTranId,
    'refund_amount'  => 500.00,
    'refund_remarks' => 'Customer requested refund',
]);

if ($refund->isSuccessful()) {
    echo "Refund Reference: " . $refund['refund_ref_id'];
}
```

### Query Transaction

[](#query-transaction)

```
$result = SSLCOMMERZ::queryTransaction('ORDER_001');

if ($result->hasTransactions()) {
    $latest = $result->getLatestSuccessful();
    echo "Status: " . $latest['status'];
}
```

### Logging

[](#logging)

```
SSLCOMMERZ_LOG_ENABLED=true
```

By default, the package logs all gateway interactions using Laravel's default log configuration. You can disable logging by setting `SSLCOMMERZ_LOG_ENABLED=false`.

---

Callback Handling
-----------------

[](#callback-handling)

The package registers these routes automatically:

RouteNamePurposePOST `/ssl/success``sslcommerz.success`Successful paymentPOST `/ssl/fail``sslcommerz.fail`Failed paymentPOST `/ssl/cancel``sslcommerz.cancel`Cancelled paymentPOST `/ssl/ipn``sslcommerz.ipn`Instant Payment NotificationAll routes exclude CSRF verification since SSLCOMMERZ sends POST requests.

By default, the prefix is `ssl`. You can change it via `sslcommerz.routes.prefix` in `config/sslcommerz.php`, or publish routes to customize paths.

#### Redirect URLs After Payment

[](#redirect-urls-after-payment)

Define your own routes and views to show the payment result to the user:

```
// routes/web.php
Route::get('/payment/success', function () {
    return view('payment.success');
});
```

---

Events
------

[](#events)

Listen to these events in your `EventServiceProvider`:

```
use Sslcommerz\Laravel\Events\PaymentSucceeded;
use Sslcommerz\Laravel\Events\PaymentFailed;
use Sslcommerz\Laravel\Events\PaymentCancelled;
use Sslcommerz\Laravel\Events\IpnReceived;
use Sslcommerz\Laravel\Events\RefundInitiated;

protected $listen = [
    PaymentSucceeded::class => [
        UpdateOrderStatus::class,
        SendPaymentConfirmation::class,
    ],
    PaymentFailed::class => [
        HandleFailedPayment::class,
    ],
    IpnReceived::class => [
        ProcessIpnNotification::class,
    ],
];
```

### Persistence (Handling Orders)

[](#persistence-handling-orders)

Since this package is database-agnostic, you should handle transaction persistence in your own application using listeners.

**Example Listener:**

```
namespace App\Listeners;

use Sslcommerz\Laravel\Events\PaymentSucceeded;
use App\Models\Order;

class UpdateOrderStatus
{
    public function handle(PaymentSucceeded $event): void
    {
        // Access callback data via $event->payment
        // Access API validation data via $event->validation

        $tranId = $event->payment->tranId;
        $orderId = $event->payment->valueA; // Your custom reference

        Order::where('id', $orderId)->update([
            'status'     => 'paid',
            'paid_at'    => now(),
            'payment_id' => $tranId,
        ]);
    }
}
```

---

Hash Verification
-----------------

[](#hash-verification)

The package automatically verifies hash signatures on IPN callbacks. You can also verify manually:

```
$isValid = SSLCOMMERZ::verifyHash($request->all());
```

Or use the middleware on your own routes:

```
Route::middleware('sslcommerz.verify')
    ->post('/custom-callback', [CustomController::class, 'handle']);
```

---

Testing
-------

[](#testing)

### Run Package Tests

[](#run-package-tests)

```
composer install
./vendor/bin/phpunit
```

### Mock in Your Application Tests

[](#mock-in-your-application-tests)

```
use Sslcommerz\Laravel\Facades\SSLCOMMERZ;
use Sslcommerz\Laravel\DTOs\PaymentResponseDTO;

SSLCOMMERZ::shouldReceive('initiate')
    ->once()
    ->andReturn(PaymentResponseDTO::fromApiResponse([
        'status'         => 'SUCCESS',
        'GatewayPageURL' => 'https://sandbox.sslcommerz.com/gw.php',
        'sessionkey'     => 'TEST_SESSION',
    ]));
```

---

API Reference
-------------

[](#api-reference)

### `SSLCOMMERZ::initiate(PaymentRequestDTO|array $request): PaymentResponseDTO`

[](#sslcommerzinitiatepaymentrequestdtoarray-request-paymentresponsedto)

Creates a payment session. If an array is passed, it is automatically converted to a DTO with sensible defaults.

### `SSLCOMMERZ::validate(string $valId): ValidationResponseDTO`

[](#sslcommerzvalidatestring-valid-validationresponsedto)

Validates a transaction using the validation ID from callback/IPN.

### `SSLCOMMERZ::refund(RefundRequestDTO|array $request): RefundResponseDTO`

[](#sslcommerzrefundrefundrequestdtoarray-request-refundresponsedto)

Initiates a refund for a previously successful transaction.

### `SSLCOMMERZ::queryTransaction(string $tranId): TransactionQueryDTO`

[](#sslcommerzquerytransactionstring-tranid-transactionquerydto)

Queries all transactions associated with a merchant transaction ID.

### `SSLCOMMERZ::queryBySession(string $sessionKey): ValidationResponseDTO`

[](#sslcommerzquerybysessionstring-sessionkey-validationresponsedto)

Queries transaction status by SSLCOMMERZ session key.

### `SSLCOMMERZ::queryRefundStatus(string $refundRefId): RefundResponseDTO`

[](#sslcommerzqueryrefundstatusstring-refundrefid-refundresponsedto)

Checks the current status of a refund request.

### `SSLCOMMERZ::verifyHash(array $data): bool`

[](#sslcommerzverifyhasharray-data-bool)

Verifies the MD5 hash signature of callback data.

---

Security
--------

[](#security)

This package implements multiple layers of security:

1. **Hash Verification**: All IPN callbacks are verified using SSLCOMMERZ's MD5 signature algorithm
2. **API Validation**: Every successful payment is validated server-side via the Order Validation API
3. **CSRF Exemption**: Only callback routes from SSLCOMMERZ are CSRF-exempt
4. **Logging**: All gateway interactions are logged for audit trails
5. **Environment Isolation**: Separate endpoints for sandbox and production

### Best Practices

[](#best-practices)

- Always validate transactions via the API, never trust callback data alone
- Monitor `risk_level` in validation responses (0 = Safe, 1 = Risky)
- Use `value_a` through `value_d` to pass your own references
- Set up IPN as the primary notification method (works even if user closes browser)
- Register your production IP at SSLCOMMERZ for refund API access

---

Troubleshooting
---------------

[](#troubleshooting)

IssueSolution"Invalid Store ID"Check `SSLCOMMERZ_STORE_ID` in `.env`CSRF token mismatchCallback routes already exclude CSRF — check if you overrode routesIPN not receivedEnsure your server is reachable from internet on port 80/443Hash verification failsVerify `SSLCOMMERZ_STORE_PASSWORD` matches your SSLCOMMERZ dashboardConnection timeoutWhitelist SSLCOMMERZ IPs: `103.26.139.87` (sandbox), `103.26.139.81` (live)---

License
-------

[](#license)

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

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance95

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88% 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 ~25 days

Total

4

Last Release

24d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/34369086?v=4)[Motaleb Hossain](/maintainers/bdmotaleb)[@bdmotaleb](https://github.com/bdmotaleb)

---

Top Contributors

[![bdmotaleb12](https://avatars.githubusercontent.com/u/265696451?v=4)](https://github.com/bdmotaleb12 "bdmotaleb12 (22 commits)")[![bdmotaleb](https://avatars.githubusercontent.com/u/34369086?v=4)](https://github.com/bdmotaleb "bdmotaleb (2 commits)")[![risul3](https://avatars.githubusercontent.com/u/5075348?v=4)](https://github.com/risul3 "risul3 (1 commits)")

---

Tags

laravelpaymentgatewaybangladeshsslcommerzBDT

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.4M354](/packages/psalm-plugin-laravel)[laravel/cashier

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

2.5k31.8M163](/packages/laravel-cashier)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9922.4M147](/packages/roots-acorn)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45844.8k1](/packages/pressbooks-pressbooks)[api-platform/laravel

API Platform support for Laravel

58190.1k21](/packages/api-platform-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

265.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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