PHP code example of bd-payments / laravel-payment-gateway

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

    

bd-payments / laravel-payment-gateway example snippets




use BDPayments\LaravelPaymentGateway\Facades\PaymentGateway;

// Initialize a payment with security features
$response = PaymentGateway::initializePayment('nagad', [
    'order_id' => 'ORDER123',
    'amount' => 100.50,
    'currency' => 'BDT',
    'callback_url' => 'https://yourdomain.com/callback',
    'payment_hash' => PaymentGateway::generatePaymentHash([
        'order_id' => 'ORDER123',
        'amount' => 100.50,
        'currency' => 'BDT',
    ]),
]);

if ($response->success) {
    // Redirect to payment gateway
    return redirect($response->redirectUrl);
} else {
    // Handle error
    return back()->with('error', $response->message);
}



use BDPayments\LaravelPaymentGateway\Services\PaymentGatewayService;

class PaymentController extends Controller
{
    public function __construct(
        private readonly PaymentGatewayService $paymentService
    ) {}

    public function processPayment(Request $request)
    {
        $response = $this->paymentService->initializePayment('nagad', [
            'order_id' => $request->order_id,
            'amount' => $request->amount,
            'currency' => 'BDT',
        ]);

        return response()->json($response->toArray());
    }
}



use BDPayments\LaravelPaymentGateway\Models\Payment;

// Create a payment record
$payment = Payment::create([
    'user_id' => auth()->id(),
    'order_id' => 'ORDER123',
    'gateway' => 'nagad',
    'amount' => 100.50,
    'currency' => 'BDT',
    'status' => 'pending',
]);

// Check payment status
if ($payment->isPending()) {
    // Payment is still pending
}

// Mark as completed
$payment->markAsCompleted($gatewayResponse);

// Check if refundable
if ($payment->canBeRefunded()) {
    // Process refund
}

use BDPayments\LaravelPaymentGateway\Services\PaymentHistoryService;

$historyService = app(PaymentHistoryService::class);

// Log payment actions
$historyService->logPaymentCreated($payment);
$historyService->logPaymentCompleted($payment, $gatewayResponse);
$historyService->logPaymentFailed($payment, $gatewayResponse, 'Insufficient funds');

// Report payment problems
$problem = $historyService->reportProblem(
    $payment,
    'payment_failed',
    'Payment Processing Error',
    'Customer reported payment failure',
    'high',
    'urgent'
);

// Get payment history
$history = $historyService->getPaymentHistory($payment);

use BDPayments\LaravelPaymentGateway\Services\InvoiceService;

$invoiceService = app(InvoiceService::class);

// Generate invoice for payment
$invoice = $invoiceService->generateInvoice($payment, [
    'billing_address' => [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'address' => '123 Main St',
        'city' => 'Dhaka',
        'country' => 'Bangladesh',
    ],
    'items' => [
        [
            'description' => 'Product A',
            'quantity' => 2,
            'unit_price' => 50.00,
            'tax_rate' => 10,
        ],
    ],
]);

// Send invoice
$invoiceService->sendInvoice($invoice);

// Generate PDF
$pdf = $invoiceService->generateInvoicePdf($invoice);

use BDPayments\LaravelPaymentGateway\Services\PaymentSecurityService;

$securityService = app(PaymentSecurityService::class);

// Generate secure payment hash
$paymentHash = $securityService->generatePaymentHash([
    'amount' => 100.50,
    'currency' => 'BDT',
    'reference_id' => 'REF123',
]);

// Verify payment integrity
$isValid = $securityService->validatePaymentIntegrity($payment, $data);

// Check rate limiting
$canProceed = $securityService->checkRateLimit('user:123');

// Detect fraudulent activity
$fraudIndicators = $securityService->detectFraudulentActivity($ipAddress, $paymentData);

// Encrypt sensitive data
$encryptedData = $securityService->encryptPaymentData($sensitiveData);

// Generate secure transaction ID
$transactionId = $securityService->generateSecureTransactionId();

use BDPayments\LaravelPaymentGateway\Services\AIAgentService;

$aiAgent = app(AIAgentService::class);

// Analyze payment patterns and detect anomalies
$analysis = $aiAgent->analyzePaymentPatterns($payment);

// Generate intelligent notifications
$aiAgent->generateNotifications($payment, $analysis);

// Provide customer support
$support = $aiAgent->provideCustomerSupport(
    'I need help with my payment',
    ['payment_id' => $payment->id]
);

// Auto-resolve common problems
$resolved = $aiAgent->autoResolveProblems();

// Generate payment insights
$insights = $aiAgent->generateInsights();

// Suggest optimal gateway
$optimalGateway = $aiAgent->suggestOptimalGateway($paymentData);

// Predict payment failure
$prediction = $aiAgent->predictPaymentFailure($payment);

// Get refund recommendations
$refundStrategy = $aiAgent->recommendRefundStrategy($payment);

use BDPayments\LaravelPaymentGateway\Models\PaymentProblem;

// Get payment problems
$problems = PaymentProblem::open()->critical()->get();

// Assign problem to admin
$problem->assignTo($adminId);

// Resolve problem
$problem->markAsResolved($adminId, 'Issue resolved by contacting gateway support');

// Add comments to problems
$problem->comments()->create([
    'user_id' => auth()->id(),
    'comment' => 'Working on this issue',
    'is_internal' => true,
]);

// Access admin routes
Route::prefix('admin/payment')->middleware(['auth', 'admin'])->group(function () {
    Route::get('/', [PaymentAdminController::class, 'dashboard']);
    Route::get('/payments', [PaymentAdminController::class, 'index']);
    Route::get('/problems', [PaymentAdminController::class, 'problems']);
    Route::get('/invoices', [PaymentAdminController::class, 'invoices']);
});

use BDPayments\LaravelPaymentGateway\Facades\PaymentGateway;

// Initialize payment
$response = PaymentGateway::initializePayment(string $gateway, array $data);

// Verify payment
$response = PaymentGateway::verifyPayment(string $gateway, string $paymentId);

// Refund payment
$response = PaymentGateway::refundPayment(string $gateway, string $paymentId, float $amount, string $reason = '');

// Get payment status
$response = PaymentGateway::getPaymentStatus(string $gateway, string $paymentId);

// Get supported gateways
$gateways = PaymentGateway::getSupportedGateways();

// Check if gateway is supported
$supported = PaymentGateway::isGatewaySupported(string $gateway);

use BDPayments\LaravelPaymentGateway\Services\QRCodeService;

$qrCodeService = app(QRCodeService::class);

// Generate QR code for payment
$qrCode = $qrCodeService->generatePaymentQRCode($payment, [
    'size' => 200,
    'format' => 'png',
    'store' => true,
]);

// Generate QR code for payment URL
$qrCode = $qrCodeService->generatePaymentURLQRCode('https://example.com/payment/123');

// Generate QR code for invoice
$qrCode = $qrCodeService->generateInvoiceQRCode($payment);

// Generate QR code with logo
$qrCode = $qrCodeService->generateQRCodeWithLogo($data, '/path/to/logo.png');

// Generate styled QR code
$qrCode = $qrCodeService->generateStyledQRCode($data, [
    'color' => [0, 0, 0],
    'background_color' => [255, 255, 255],
]);

use BDPayments\LaravelPaymentGateway\Services\TransactionReportService;

$reportService = app(TransactionReportService::class);

// Generate transaction report
$report = $reportService->generateTransactionReport([
    'date_from' => '2024-01-01',
    'date_to' => '2024-12-31',
    'gateway' => 'nagad',
]);

// Generate gateway performance report
$performanceReport = $reportService->generateGatewayPerformanceReport();

// Generate financial report
$financialReport = $reportService->generateFinancialReport();

// Generate fraud analysis report
$fraudReport = $reportService->generateFraudAnalysisReport();

// Generate customer behavior report
$behaviorReport = $reportService->generateCustomerBehaviorReport();

// Export report
$exportedData = $reportService->exportReport($report, 'pdf');

// Get dashboard data
$dashboardData = $reportService->getDashboardData();

use BDPayments\LaravelPaymentGateway\Models\Payment;

// Create payment
$payment = Payment::create($data);

// Status checks
$payment->isPending();
$payment->isCompleted();
$payment->isFailed();
$payment->isRefunded();
$payment->isExpired();

// Status updates
$payment->markAsCompleted($gatewayResponse);
$payment->markAsFailed($gatewayResponse);
$payment->markAsCancelled();

// Refund operations
$payment->canBeRefunded();
$payment->getTotalRefundedAmount();
$payment->getRemainingRefundableAmount();
$payment->updateRefundedAmount();

// Payment form
GET /payment/form

// Initialize payment
POST /payment/initialize

// Gateway-specific operations
POST /payment/{gateway}/verify
POST /payment/{gateway}/refund
GET /payment/{gateway}/status
GET /payment/{gateway}/callback
POST /payment/{gateway}/webhook

// Result pages
GET /payment/success
GET /payment/failed

// API routes (with api middleware)
POST /api/payment/initialize
POST /api/payment/{gateway}/verify
POST /api/payment/{gateway}/refund
GET /api/payment/{gateway}/status
POST /api/payment/{gateway}/webhook

// Apply middleware to routes
Route::middleware(['payment.gateway', 'payment.rate_limit:60,1'])->group(function () {
    // Payment routes
});

// Apply security middleware to routes
Route::middleware(['payment.security'])->group(function () {
    // Secure payment routes
});

use BDPayments\LaravelPaymentGateway\Services\PaymentLogger;

$logger = app(PaymentLogger::class);

// Get all logs
$logs = $logger->getLogs();

// Get logs by gateway
$nagadLogs = $logger->getLogsByGateway('nagad');

// Get logs by payment ID
$paymentLogs = $logger->getLogsByPaymentId('PAYMENT123');

// Export logs
$logger->exportToFile('payment_logs.json');

use BDPayments\LaravelPaymentGateway\Exceptions\PaymentException;
use BDPayments\LaravelPaymentGateway\Exceptions\ValidationException;
use BDPayments\LaravelPaymentGateway\Exceptions\ConfigurationException;
use BDPayments\LaravelPaymentGateway\Exceptions\NetworkException;

try {
    $response = PaymentGateway::initializePayment('nagad', $data);
} catch (ValidationException $e) {
    // Handle validation errors
} catch (ConfigurationException $e) {
    // Handle configuration errors
} catch (NetworkException $e) {
    // Handle network errors
} catch (PaymentException $e) {
    // Handle other payment errors
}
bash
php artisan vendor:publish --provider="BDPayments\LaravelPaymentGateway\Providers\PaymentGatewayServiceProvider" --tag="config"
bash
php artisan vendor:publish --provider="BDPayments\LaravelPaymentGateway\Providers\PaymentGatewayServiceProvider" --tag="migrations"
bash
php artisan migrate
bash
php artisan vendor:publish --provider="BDPayments\LaravelPaymentGateway\Providers\PaymentGatewayServiceProvider" --tag="views"
bash
php artisan vendor:publish --provider="BDPayments\LaravelPaymentGateway\Providers\PaymentGatewayServiceProvider" --tag="views"