bd-payments/laravel-payment-gateway

A comprehensive Laravel 12 package for 13+ payment gateways integration with AI-powered management, PHP 8.4+ support

Installs: 5

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/bd-payments/laravel-payment-gateway

1.0.0 2025-09-24 11:54 UTC

This package is auto-updated.

Last update: 2025-09-24 19:48:28 UTC


README

A comprehensive Laravel 12 package for integrating multiple payment gateways (Nagad, bKash, Binance, PayPal, Rocket, Upay, SureCash, UCash, MCash, MyCash, AamarPay, ShurjoPay, SSLCOMMERZ) with PHP 8.4+ support, featuring advanced payment management, invoice generation, problem resolution, enhanced security features, and AI-powered management.

Features

  • ๐Ÿš€ Laravel 12 & PHP 8.4+ Support - Built with modern Laravel and PHP features
  • ๐Ÿ’ณ Multiple Gateways - Support for 13+ payment gateways including Nagad, bKash, Binance, PayPal, Rocket, Upay, SureCash, UCash, MCash, MyCash, AamarPay, ShurjoPay, SSLCOMMERZ
  • ๐Ÿ”’ Enhanced Security - Advanced fraud detection, payment tampering protection, data encryption, and comprehensive security features
  • ๐Ÿ“ Comprehensive Logging - Track all payment operations with detailed logs
  • ๐Ÿงช Well Tested - Full test coverage with PHPUnit and Laravel testing
  • ๐Ÿ› ๏ธ Easy Integration - Simple facade and service provider integration
  • ๐Ÿ“Š Rich Models - Eloquent models for payments, logs, refunds, and invoices
  • ๐ŸŽจ Beautiful Views - Responsive payment forms and result pages
  • โšก Performance - Caching, rate limiting, and optimized database queries
  • ๐Ÿ“‹ Payment History - Complete payment lifecycle tracking
  • ๐Ÿงพ Invoice Generation - Automatic invoice creation and management
  • ๐Ÿ”„ Refund Management - Comprehensive refund tracking and history
  • ๐Ÿšจ Problem Resolution - Advanced problem reporting and resolution system
  • ๐Ÿ“Š Admin Dashboard - Complete admin interface for payment management
  • ๐Ÿ“ˆ Analytics - Payment statistics and reporting
  • ๐ŸŽฏ Status Tracking - Real-time payment status monitoring
  • ๐Ÿ›ก๏ธ Fraud Protection - Advanced fraud detection and prevention
  • ๐Ÿ” Data Encryption - Automatic encryption of sensitive payment data
  • ๐Ÿšซ Tampering Protection - Payment integrity verification and hash validation
  • โšก Rate Limiting - Intelligent rate limiting to prevent abuse
  • ๐Ÿค– AI Agent - Intelligent payment management, fraud detection, and automated support
  • ๐Ÿ“Š Smart Analytics - AI-powered insights and recommendations
  • ๐Ÿ”ฎ Predictive Analytics - Payment failure prediction and risk assessment
  • ๐ŸŽฏ Optimal Gateway Selection - AI-driven gateway recommendation based on success rates
  • ๐Ÿ“ฑ QR Code Generation - Dynamic QR codes for payments, invoices, and receipts
  • ๐Ÿ“Š Transaction Reports - Comprehensive analytics and reporting system
  • ๐Ÿ“ˆ Export Functionality - PDF, Excel, CSV export options
  • ๐Ÿ“Š Analytics Dashboard - Real-time insights and metrics
  • ๐Ÿ” Fraud Analysis - Advanced fraud detection and risk assessment
  • ๐Ÿ‘ฅ Customer Behavior Analysis - Customer segmentation and behavior insights

Installation

composer require bd-payments/laravel-payment-gateway

Publish Configuration

php artisan vendor:publish --provider="BDPayments\LaravelPaymentGateway\Providers\PaymentGatewayServiceProvider" --tag="config"

Publish Migrations

php artisan vendor:publish --provider="BDPayments\LaravelPaymentGateway\Providers\PaymentGatewayServiceProvider" --tag="migrations"

Run Migrations

php artisan migrate

Publish Views (Optional)

php artisan vendor:publish --provider="BDPayments\LaravelPaymentGateway\Providers\PaymentGatewayServiceProvider" --tag="views"

Configuration

Environment Variables

Add these to your .env file:

# Default Gateway
PAYMENT_DEFAULT_GATEWAY=nagad

# Nagad Configuration
NAGAD_MERCHANT_ID=your_merchant_id_here
NAGAD_MERCHANT_PRIVATE_KEY=your_merchant_private_key_here
NAGAD_PUBLIC_KEY=your_nagad_public_key_here
NAGAD_SANDBOX=true

# bKash Configuration
BKASH_APP_KEY=your_app_key_here
BKASH_APP_SECRET=your_app_secret_here
BKASH_USERNAME=your_username_here
BKASH_PASSWORD=your_password_here
BKASH_SANDBOX=true

# Binance Configuration
BINANCE_API_KEY=your_api_key_here
BINANCE_SECRET_KEY=your_secret_key_here
BINANCE_SANDBOX=true

# Logging Configuration
PAYMENT_LOGGING_ENABLED=true
PAYMENT_LOG_LEVEL=info

# QR Code Configuration
QR_CODE_ENABLED=true
QR_CODE_STORAGE_PATH=qr-codes
QR_CODE_SIZE=200
QR_CODE_FORMAT=png
QR_CODE_ERROR_CORRECTION=M
QR_CODE_MARGIN=1
QR_CODE_CLEANUP_DAYS=30

# Reports Configuration
REPORTS_ENABLED=true
REPORTS_CACHE_TTL=3600
REPORTS_DASHBOARD_REFRESH=300

# Notifications Configuration
PAYMENT_NOTIFICATIONS_MAIL_ENABLED=true
PAYMENT_NOTIFICATIONS_FROM_ADDRESS=noreply@example.com
PAYMENT_NOTIFICATIONS_FROM_NAME=Payment System
PAYMENT_NOTIFICATIONS_SLACK_ENABLED=false
PAYMENT_NOTIFICATIONS_SLACK_WEBHOOK_URL=
PAYMENT_NOTIFICATIONS_SLACK_CHANNEL=#payments

Configuration File

The package will create config/payment-gateway.php with comprehensive configuration options.

Quick Start

Basic Usage

<?php

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);
}

Using Service Injection

<?php

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());
    }
}

Using Models

<?php

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
}

Advanced Features

Payment History Tracking

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);

Invoice Generation

use BDPayments\LaravelPaymentGateway\Services\InvoiceService;

$invoiceService = app(InvoiceService::class);

// Generate invoice for payment
$invoice = $invoiceService->generateInvoice($payment, [
    'billing_address' => [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        '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);

Security Features

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();

AI Agent Features

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);

Problem Resolution System

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,
]);

Admin Dashboard

// 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']);
});

API Reference

PaymentGateway Facade

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);

QR Code Generation

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],
]);

Transaction Reports

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();

Payment Model

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();

Routes

The package automatically registers the following routes:

// 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

Middleware

The package includes several middleware for security and rate limiting:

PaymentGatewayMiddleware

Logs all payment operations and validates gateway parameters.

WebhookSignatureMiddleware

Verifies webhook signatures for secure webhook processing.

RateLimitMiddleware

Implements rate limiting for payment operations.

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

PaymentSecurityMiddleware

Advanced security middleware with fraud detection and tampering protection.

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

Views

The package includes beautiful, responsive views:

  • Payment Form (payment-gateway::payment-form) - Payment initialization form
  • Success Page (payment-gateway::success) - Payment success page
  • Failed Page (payment-gateway::failed) - Payment failure page

Customizing Views

php artisan vendor:publish --provider="BDPayments\LaravelPaymentGateway\Providers\PaymentGatewayServiceProvider" --tag="views"

Then modify the views in resources/views/vendor/payment-gateway/.

Logging

The package provides comprehensive logging:

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');

Testing

# Run tests
composer test

# Run tests with coverage
composer test-coverage

# Run static analysis
composer stan

# Run code style checks
composer cs

# Fix code style issues
composer cs-fix

Error Handling

The package provides specific exception types:

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
}

Webhooks

Configure webhook endpoints in your .env:

NAGAD_WEBHOOK_ENABLED=true
NAGAD_WEBHOOK_SECRET=your_webhook_secret
NAGAD_WEBHOOK_URL=https://yourdomain.com/payment/nagad/webhook

BKASH_WEBHOOK_ENABLED=true
BKASH_WEBHOOK_SECRET=your_webhook_secret
BKASH_WEBHOOK_URL=https://yourdomain.com/payment/bkash/webhook

BINANCE_WEBHOOK_ENABLED=true
BINANCE_WEBHOOK_SECRET=your_webhook_secret
BINANCE_WEBHOOK_URL=https://yourdomain.com/payment/binance/webhook

PAYPAL_WEBHOOK_ENABLED=true
PAYPAL_WEBHOOK_SECRET=your_webhook_secret
PAYPAL_WEBHOOK_URL=https://yourdomain.com/payment/paypal/webhook

Database Schema

The package includes migrations for:

  • payments - Payment records
  • payment_logs - Payment operation logs
  • payment_refunds - Refund records

Security Features

  • Advanced Fraud Detection - Multi-layered fraud detection system
  • Payment Tampering Protection - Hash-based integrity verification
  • Data Encryption - Automatic encryption of sensitive payment data
  • Rate Limiting - Intelligent rate limiting to prevent abuse
  • Webhook Signature Verification - Secure webhook processing
  • Data Sanitization - Automatic sanitization of sensitive data
  • HTTPS Enforcement - Optional HTTPS requirement
  • Input Validation - Comprehensive validation rules
  • CSRF Protection - Nonce-based CSRF protection
  • IP-based Security - Suspicious IP detection and blocking

Performance Features

  • Caching - Configurable caching for improved performance
  • Database Optimization - Efficient queries with proper indexing
  • Logging Control - Optional logging to reduce overhead
  • Async Processing - Support for background job processing

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

This package is open-sourced software licensed under the MIT license.

Support

For support and questions, please open an issue on GitHub or contact us at support@bdpayments.com.

Database Schema

The package includes comprehensive database migrations:

  • payments - Payment records with full lifecycle tracking
  • payment_logs - Detailed operation logs
  • payment_refunds - Refund management
  • payment_histories - Complete payment history
  • payment_problems - Problem reporting and resolution
  • payment_problem_comments - Problem discussion threads
  • invoices - Invoice generation and management
  • invoice_items - Invoice line items

Admin Features

Payment Management

  • View all payments with filtering and search
  • Update payment status manually
  • View detailed payment information
  • Export payment data to CSV
  • Real-time payment statistics

Problem Resolution

  • Report and track payment problems
  • Assign problems to admin users
  • Add comments and attachments
  • Set priority and severity levels
  • Resolve problems with detailed notes

Invoice Management

  • Generate invoices automatically
  • Send invoices via email
  • Download invoice PDFs
  • Track invoice status
  • Manage invoice items and calculations

Analytics Dashboard

  • Payment statistics and trends
  • Problem resolution metrics
  • Invoice generation reports
  • Gateway performance analysis
  • Revenue tracking

Changelog

v3.0.0

  • Payment History Tracking - Complete payment lifecycle monitoring
  • Invoice Generation - Automatic invoice creation and management
  • Problem Resolution System - Advanced problem reporting and resolution
  • Admin Dashboard - Comprehensive admin interface
  • Refund Management - Enhanced refund tracking and history
  • Analytics & Reporting - Payment statistics and insights
  • Status Monitoring - Real-time payment status tracking
  • Enhanced Security - Advanced problem resolution workflows

v2.0.0

  • Laravel 12 support
  • PHP 8.4+ support
  • Added Binance payment gateway
  • Complete Laravel package structure
  • Comprehensive testing
  • Beautiful responsive views
  • Advanced security features
  • Performance optimizations

v1.0.0

  • Initial release
  • Support for Nagad and bKash payment gateways
  • Basic Laravel integration