PHP code example of unipay / unipay-bd

1. Go to this page and download the library: Download unipay/unipay-bd 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/ */

    

unipay / unipay-bd example snippets


use Unipay\BD\Facades\Payment;
use Unipay\BD\DTOs\PaymentRequest;

$paymentRequest = PaymentRequest::builder()
    ->amount(1500.00, 'BDT')
    ->invoice('INV-' . time())
    ->customer(
        mobile: '01712345678',
        email: '[email protected]',
        name: 'Rahim Uddin'
    )
    ->coupon('PROMO20', 100.00)
    ->build();

// Initiate with default or specific gateway
$response = Payment::driver('bkash')->createPayment($paymentRequest);

if ($response->isSuccessful() || $response->isPending()) {
    // Redirect customer to payment portal
    return redirect()->away($response->redirectUrl);
}

return back()->withErrors(['message' => $response->message]);

use Unipay\BD\Events\PaymentSucceeded;
use Unipay\BD\Events\PaymentFailed;
use Unipay\BD\Events\PaymentRefunded;

protected $listen = [
    PaymentSucceeded::class => [
        \App\Listeners\MarkOrderAsPaid::class,
    ],
    PaymentFailed::class => [
        \App\Listeners\HandleFailedPayment::class,
    ],
];

namespace App\Listeners;

use Unipay\BD\Events\PaymentSucceeded;
use App\Models\Order;

class MarkOrderAsPaid
{
    public function handle(PaymentSucceeded $event)
    {
        $response = $event->response; // PaymentResponse DTO
        
        $order = Order::where('invoice_id', $response->invoiceId)->first();

        if ($order) {
            $order->update([
                'status' => 'paid',
                'transaction_id' => $response->transactionId,
                'gateway' => $response->gatewayName,
            ]);
        }
    }
}

use Unipay\BD\Facades\Payment;
use Unipay\BD\DTOs\RefundRequest;

$refundRequest = new RefundRequest(
    paymentId: 'PAY_12345678',
    transactionId: 'TRX_98765432',
    amount: 500.00,
    reason: 'Customer return request'
);

$response = Payment::driver('bkash')->refund($refundRequest);

if ($response->isSuccessful()) {
    // Refund complete
    $refundTrxId = $response->refundTransactionId;
}

use Unipay\BD\Facades\Payment;

$response = Payment::driver('nagad')->queryPayment('NAGAD_REF_1001');

if ($response->isSuccessful()) {
    $trxId = $response->transactionId;
    $amount = $response->amount;
}

use Unipay\BD\Facades\Payment;

public function boot()
{
    Payment::resolveTenantConfigUsing(function ($tenant, string $driver) {
        // Retrieve tenant's credentials from your database or encrypted settings
        return [
            'app_key'    => $tenant->bkash_app_key,
            'app_secret' => $tenant->bkash_app_secret,
            'username'   => $tenant->bkash_username,
            'password'   => $tenant->bkash_password,
        ];
    });
}

$tenant = Tenant::find(12);

$response = Payment::forTenant($tenant)
    ->driver('bkash')
    ->createPayment($paymentRequest);

$customBkash = Payment::driver('bkash')->withConfig([
    'app_key'    => 'vendor_key_99',
    'app_secret' => 'vendor_secret_99',
    'username'   => 'vendor_user',
    'password'   => 'vendor_pass',
]);

$response = $customBkash->createPayment($paymentRequest);

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Unipay\BD\Traits\Billable;

class User extends Authenticatable
{
    use Billable;
}

$user = auth()->user();

// Create a monthly Pro subscription with a 7-day trial
$subscription = $user->newSubscription('pro-plan', 999.00)
    ->monthly()
    ->trialDays(7)
    ->create();

// Check subscription status
if ($user->subscribed('pro-plan')) {
    // User has an active or trialing subscription
}

// Check if user is currently in free trial
if ($subscription->onTrial()) {
    $daysLeft = $subscription->trial_ends_at->diffInDays(now());
}

// Cancel or pause subscription
$subscription->cancel();
$subscription->pause();
$subscription->resume();

use Illuminate\Support\Facades\Schedule;

Schedule::command('unipay:billing:process')->dailyAt('00:01');

use Unipay\BD\Models\PaymentLink;

$link = PaymentLink::create([
    'title' => 'Web Design Retainer - Invoice #1024',
    'amount' => 15000.00,
    'customer_name' => 'Tech Corp BD',
    'customer_email' => '[email protected]',
    'expires_at' => now()->addDays(3),
    'allowed_gateways' => ['bkash', 'nagad', 'aamarpay'],
]);

// Send $link->url to the customer!
// Example: https://yourapp.com/unipay/pay/Xy9K1z

$wallet = $user->getWallet(); // Auto-creates wallet if not existing

// Add balance
$wallet->deposit(500.00, 'Top-up via bKash', ['payment_id' => 'PAY_888']);

// Check balance
if ($wallet->hasSufficientBalance(120.00)) {
    // Withdraw for purchase
    $wallet->withdraw(120.00, 'Purchased digital sticker pack');
}

// Transaction ledger
$history = $wallet->transactions()->latest()->get();

use Unipay\BD\Services\CurrencyConverter;

$converter = app(CurrencyConverter::class);

// Converts 10.00 USD to BDT using current exchange rates + safety buffer
$bdtAmount = $converter->convertToBdt(10.00, 'USD');

use Unipay\BD\Services\UniPayShield;

$shield = app(UniPayShield::class);

// Checks IP velocity, phone number fraud patterns, and blacklists
$shield->protect(
    ip: request()->ip(),
    phone: '01712345678',
    amount: 50000.00
);

$response = Payment::driver('mock')->createPayment($paymentRequest);

// Immediately succeeds and provides mock redirect & transaction IDs
$trxId = $response->transactionId; 

use Unipay\BD\Facades\Payment;

Payment::extend('custom_mfs', function ($app) {
    return new CustomMfsGateway(config('unipay.gateways.custom_mfs'));
});
bash
php artisan unipay:install
php artisan migrate
bash
php artisan unipay:billing:process
bash
php artisan unipay:doctor