PHP code example of rayhan-bapari / sslcommerz

1. Go to this page and download the library: Download rayhan-bapari/sslcommerz library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rayhan-bapari / sslcommerz example snippets


// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
    'sslcommerz/success',
    'sslcommerz/fail',
    'sslcommerz/cancel',
    'sslcommerz/ipn',
];

use RayhanBapari\SslcommerzPayment\Facades\Sslcommerz;
use RayhanBapari\SslcommerzPayment\DTOs\PaymentData;

use RayhanBapari\SslcommerzPayment\Contracts\SslcommerzPaymentInterface;

public function __construct(protected SslcommerzPaymentInterface $sslcz) {}

use RayhanBapari\SslcommerzPayment\DTOs\PaymentData;
use RayhanBapari\SslcommerzPayment\Facades\Sslcommerz;

public function initiatePayment(Request $request)
{
    $dto               = new PaymentData();
    $dto->tran_id      = 'INV-' . uniqid();
    $dto->total_amount = 500.00;
    $dto->currency     = 'BDT';

    // Customer
    $dto->cus_name     = $request->user()->name;
    $dto->cus_email    = $request->user()->email;
    $dto->cus_phone    = $request->user()->phone;
    $dto->cus_add1     = '123 Dhanmondi';
    $dto->cus_city     = 'Dhaka';
    $dto->cus_country  = 'Bangladesh';
    $dto->cus_postcode = '1209';

    // Product
    $dto->product_name     = 'Premium Subscription';
    $dto->product_category = 'subscription';
    $dto->product_profile  = 'non-physical-goods';

    // Shipping (set to NO if digital)
    $dto->shipping_method = 'NO';

    // Pass-through — get them back in success/fail/cancel/ipn callbacks
    $dto->value_a = (string) $request->user()->id;
    $dto->value_b = 'order-reference';

    $response = Sslcommerz::initiatePayment($dto);

    if ($response->success()) {
        return redirect($response->gatewayPageURL());
    }

    return back()->with('error', 'Could not initiate payment: ' . $response->error());
}

// routes/web.php
Route::post('sslcommerz/success', [PaymentController::class, 'success'])->name('sslcommerz.success');
Route::post('sslcommerz/fail',    [PaymentController::class, 'fail'])->name('sslcommerz.fail');
Route::post('sslcommerz/cancel',  [PaymentController::class, 'cancel'])->name('sslcommerz.cancel');

// PaymentController.php

public function success(Request $request)
{
    // Step 1: Verify hash
    if (!Sslcommerz::verifyIpnHash($request->post())) {
        abort(403, 'Invalid signature.');
    }

    // Step 2: Server-side validation
    $validation = Sslcommerz::orderValidate($request->val_id);

    if (!in_array($validation['status'] ?? '', ['VALID', 'VALIDATED'])) {
        return redirect()->route('checkout')->with('error', 'Payment validation failed.');
    }

    // Step 3: Confirm the amount matches your order
    $paidAmount = (float) $validation['amount'];
    // ... compare with your stored order amount

    // Step 4: Fulfill order using $request->value_a (your user ID), tran_id, bank_tran_id
    $bankTranId = $request->bank_tran_id; // Save this — needed for refunds

    return redirect()->route('dashboard')->with('success', 'Payment successful!');
}

public function fail(Request $request)
{
    return redirect()->route('checkout')->with('error', 'Payment failed. Please try again.');
}

public function cancel(Request $request)
{
    return redirect()->route('checkout')->with('info', 'Payment cancelled.');
}

// app/Providers/EventServiceProvider.php
protected $listen = [
    'sslcommerz.ipn' => [
        App\Listeners\HandleSslcommerzIpn::class,
    ],
];

// app/Listeners/HandleSslcommerzIpn.php
namespace App\Listeners;

class HandleSslcommerzIpn
{
    public function handle(array $payload): void
    {
        if (!$payload['verified']) {
            return; // Hash check passed but server validation failed
        }

        $tranId     = $payload['tran_id'];
        $status     = $payload['status'];      // VALID | VALIDATED
        $bankTranId = $payload['bank_tran_id']; // Save for refunds
        $amount     = $payload['amount'];
        $userId     = $payload['value_a'];      // Your pass-through field

        // Update your order in the database here
    }
}

// By your tran_id
$result = Sslcommerz::transactionQueryById('INV-12345');

// By SSLCommerz sessionkey
$result = Sslcommerz::transactionQueryBySessionId('session_abc123');

// You need the bank_tran_id from the original transaction
$result = Sslcommerz::initiateRefund(
    bankTranId:    '1709162345070ANJdZV8LyI4cMw',
    refundAmount:  50.00,
    refundRemarks: 'Customer request',
    refe_id:       'REF-TRACK-001'   // optional tracking reference
);

// $result['status'] → 'success' | 'failed' | 'processing'
// $result['refund_ref_id'] → save this for status checking

// Check refund status
$status = Sslcommerz::refundStatus($result['refund_ref_id']);
// $status['status'] → 'refunded' | 'processing' | 'cancelled'

use RayhanBapari\SslcommerzPayment\Exceptions\SslcommerzException;
use RayhanBapari\SslcommerzPayment\Exceptions\SslcommerzIpnException;

try {
    $response = Sslcommerz::initiatePayment($dto);
} catch (SslcommerzException $e) {
    // Configuration or API communication error
    Log::error('SSLCommerz error: ' . $e->getMessage());
}
bash
php artisan vendor:publish --tag=sslcommerz-config
php artisan vendor:publish --tag=sslcommerz-migrations
php artisan migrate