laravel-payment-gateway maintained by bd-payments
Laravel Payment Gateway Package
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 recordspayment_logs- Payment operation logspayment_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
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- 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 trackingpayment_logs- Detailed operation logspayment_refunds- Refund managementpayment_histories- Complete payment historypayment_problems- Problem reporting and resolutionpayment_problem_comments- Problem discussion threadsinvoices- Invoice generation and managementinvoice_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