PHP code example of obrainwave / paygate

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

    

obrainwave / paygate example snippets


use Paygate;

// Initiate Payment
$payment = Paygate::initiatePayment([
    'provider' => 'paystack',
    'amount' => 250,
    'email' => '[email protected]',
    'reference' => 'TXN_' . time(),
    'redirect_url' => 'https://yoursite.com/payment/callback',
    'name' => 'John Doe',
    'phone_number' => '08012345678'
]);

// Verify Payment
$verification = Paygate::verifyPayment([
    'provider' => 'paystack',
    'reference' => 'TXN_1234567890'
]);

// Refund Payment
$refund = Paygate::refundPayment([
    'provider' => 'paystack',
    'reference' => 'TXN_1234567890',
    'amount' => 100, // Optional: partial refund
    'reason' => 'Customer requested refund'
]);

use Obrainwave\Paygate\Contracts\PaymentServiceInterface;

class PaymentController extends Controller
{
    public function __construct(
        protected PaymentServiceInterface $paymentService
    ) {}

    public function initiate(Request $request)
    {
        $result = $this->paymentService->initiatePayment($request->all());
        return response()->json($result);
    }
}

// POST /paygate/initiate
Route::post('/paygate/initiate', function(Request $request) {
    return Paygate::initiatePayment($request->all());
});

// GET /paygate/verify/{reference}
Route::get('/paygate/verify/{reference}', function($reference) {
    return Paygate::verifyPayment(['reference' => $reference]);
});

// POST /api/paygate/initiate
// GET /api/paygate/verify/{reference}
// POST /api/paygate/refund
// GET /api/paygate/status/{reference}
// GET /api/paygate/history
// GET /api/paygate/gateways

// Get payment by reference
$payment = Paygate::getPaymentByReference('TXN_1234567890');

// Get payment history with filters
$history = Paygate::getPaymentHistory([
    'status' => 'successful',
    'provider' => 'paystack',
    'customer_email' => '[email protected]',
    'date_from' => '2024-01-01',
    'date_to' => '2024-12-31'
]);

// Get available gateways
$gateways = Paygate::getAvailableGateways();

// Listen to payment events
use Obrainwave\Paygate\Events\PaymentInitiated;
use Obrainwave\Paygate\Events\PaymentCompleted;
use Obrainwave\Paygate\Events\PaymentFailed;

Event::listen(PaymentCompleted::class, function($payment) {
    // Send confirmation email
    Mail::to($payment->customer_email)->send(new PaymentConfirmation($payment));
});

Event::listen(PaymentFailed::class, function($payment) {
    // Log failed payment
    Log::error('Payment failed', (array) $payment);
});

use Paygate;

$payload = [
    'provider' => 'paystack',
    'provider_token' => 'PAYSTACK_SECRET_KEY', // Still supported
    'amount' => 250,
    'email' => '[email protected]',
    'reference' => 'TXN_1234567890',
    'redirect_url' => 'https://yoursite.com/verify-payment',
    'name' => 'John Doe',
    'contract_code' => '32904826734', // For Monnify
    'payment_methods' => ["card", "bank", "ussd", "qr", "mobile_money", "bank_transfer", "eft"],
    'pass_charge' => false, // For GTPay
    'title' => "Your Store Name", // For Flutterwave
    'logo' => 'https://yoursite.com/logo.png', // For Flutterwave
    'phone_number' => '08012345678' // For Flutterwave
];

$payment = Paygate::initiatePayment($payload);

// Get payment by reference
$payment = Paygate::getPaymentByReference('TXN_1234567890');

// Get payment history with filters
$history = Paygate::getPaymentHistory([
    'status' => 'successful',
    'provider' => 'paystack',
    'customer_email' => '[email protected]',
    'date_from' => '2024-01-01',
    'date_to' => '2024-12-31'
]);

// Use Eloquent model directly
use Obrainwave\Paygate\Models\Payment;

$payments = Payment::successful()
    ->byProvider('paystack')
    ->where('amount', '>', 100)
    ->orderBy('created_at', 'desc')
    ->get();

use Obrainwave\Paygate\Events\PaymentInitiated;
use Obrainwave\Paygate\Events\PaymentCompleted;
use Obrainwave\Paygate\Events\PaymentFailed;

// In your EventServiceProvider
protected $listen = [
    PaymentCompleted::class => [
        SendPaymentConfirmationEmail::class,
        UpdateOrderStatus::class,
    ],
    PaymentFailed::class => [
        LogFailedPayment::class,
        SendFailureNotification::class,
    ],
];

// Or use Event::listen
Event::listen(PaymentCompleted::class, function($payment) {
    // Send confirmation email
    Mail::to($payment->customer_email)->send(new PaymentConfirmation($payment));
    
    // Update order status
    Order::where('payment_reference', $payment->reference)
         ->update(['status' => 'paid']);
});

// Webhook endpoint is automatically available at:
// POST /paygate/webhook
// POST /api/paygate/webhook

// Configure webhook secrets in your .env:
PAYSTACK_WEBHOOK_SECRET=your_webhook_secret
GTPAY_WEBHOOK_SECRET=your_webhook_secret
FLUTTERWAVE_WEBHOOK_SECRET=your_webhook_secret
MONNIFY_WEBHOOK_SECRET=your_webhook_secret

// In your routes file
Route::group(['middleware' => [VerifyPaymentMiddleware::class]], function () {
    Route::get('/download/{reference}', [DownloadController::class, 'download']);
    Route::get('/access/{reference}', [AccessController::class, 'grant']);
});

// The middleware automatically:
// - Verifies payment exists
// - Checks payment status is 'successful'
// - Adds payment data to request

// Payment Operations
POST   /api/paygate/initiate     # Initiate payment
GET    /api/paygate/verify/{ref} # Verify payment
POST   /api/paygate/refund      # Refund payment
GET    /api/paygate/status/{ref}# Get payment status
GET    /api/paygate/history     # Get payment history
GET    /api/paygate/gateways    # Get available gateways
POST   /api/paygate/webhook     # Webhook endpoint

// Web Routes
POST   /paygate/initiate        # Initiate payment
GET    /paygate/verify/{ref}    # Verify payment
GET    /paygate/callback        # Payment callback
GET    /paygate/status/{ref}    # Payment status
GET    /paygate/history         # Payment history
GET    /paygate/success/{ref}   # Success page (protected)

// config/paygate.php
return [
    'default_currency' => 'NGN',
    'default_provider' => 'paystack',
    'enable_logging' => true,
    'store_payments' => true,
    'webhook_enabled' => true,
    'rate_limit' => 60,
    'retry_attempts' => 3,
    'encrypt_sensitive_data' => true,
    // ... more options
];

// Get payment statistics
$stats = [
    'total_payments' => Payment::count(),
    'successful_payments' => Payment::successful()->count(),
    'failed_payments' => Payment::failed()->count(),
    'total_amount' => Payment::successful()->sum('amount'),
    'average_amount' => Payment::successful()->avg('amount'),
];

// Get provider performance
$providerStats = Payment::selectRaw('provider, COUNT(*) as count, SUM(amount) as total')
    ->groupBy('provider')
    ->get();

use Paygate;

$payload = array(
  'provider' => 'gtpay',
  'provider_token' => 'GTPAY_SECRET_KEY', // Make sure you don't expose this in your code
  'reference' => 'T2CZ143DUMG',
  
 );

$payment = Paygate::verifyPayment($payload);

// Enable caching in config
'enable_caching' => true,
'cache_ttl' => 300, // 5 minutes

// Cache is automatically handled, but you can manage it manually
$cacheService = app(CacheService::class);

// Clear payment cache
$cacheService->clearPaymentCache('payment_initiate_paystack_' . $reference);

// Clear all caches
$cacheService->clearAllPaymentCaches();

// Data encryption (automatic)
'encrypt_sensitive_data' => true,

// Log masking (automatic)
'mask_sensitive_logs' => true,

// Fraud detection
$fraudService = app(FraudDetectionService::class);
$riskAnalysis = $fraudService->analyzePayment($paymentData);

if ($riskAnalysis['recommendation'] === 'decline') {
    // Handle high-risk payment
}

// Create a custom plugin
class CustomNotificationPlugin implements PluginInterface
{
    public function getName(): string
    {
        return 'CustomNotificationPlugin';
    }
    
    public function registerHooks(): array
    {
        return ['payment.completed'];
    }
    
    public function handleHook(string $hook, array $data = []): mixed
    {
        // Custom logic here
        return null;
    }
}

// Register the plugin
$pluginManager = app(PluginManager::class);
$pluginManager->registerPlugin(new CustomNotificationPlugin());

// Rate limiting
'rate_limit' => 60, // requests per minute

// Retry logic
'retry_attempts' => 3,
'retry_delay' => 1000, // milliseconds

// Response caching
'cache_ttl' => 300, // 5 minutes
bash
php artisan paygate:install
bash
php artisan config:cache
blade
<!-- Use the payment form component -->
<x-paygate-payment-form />

<!-- Or 
blade
<!-- Payment Form Component -->
<x-paygate-payment-form />

<!-- Or y -->
@if($payment->status === 'successful')
    <div class="alert alert-success">
        Payment successful! Reference: {{ $payment->reference }}
    </div>
@endif
bash
# Run tests
php artisan test

# Run specific test suites
php artisan test --filter=PaymentTest
php artisan test --filter=PaymentServiceTest

# Test coverage
php artisan test --coverage
bash
# Install the package
php artisan paygate:install

# Publish migrations only
php artisan vendor:publish --tag=paygate-migrations

# Publish config only
php artisan vendor:publish --tag=paygate-config

# Clear payment cache
php artisan cache:clear