PHP code example of dontka / all-php-payment-gateway-manager

1. Go to this page and download the library: Download dontka/all-php-payment-gateway-manager 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/ */

    

dontka / all-php-payment-gateway-manager example snippets


// config/app.php
'providers' => [
    // ...
    PaymentGateway\ServiceProvider::class,
],

'aliases' => [
    // ...
    'Payment' => PaymentGateway\Facades\Payment::class,
],

namespace App\Controller;

use PaymentGateway\Core\PaymentManager;

class PaymentController extends AbstractController
{
    public function __construct(private PaymentManager $paymentManager) {}

    public function charge()
    {
        $result = $this->paymentManager->charge([
            'gateway' => 'paypal',
            'amount' => 99.99,
            'currency' => 'USD',
        ]);
    }
}


PaymentGateway\Core\PaymentManager;
use PaymentGateway\Gateways\PayPalGateway;

$paymentManager = new PaymentManager();

// Enregistrer le gateway PayPal
$paypalGateway = new PayPalGateway(
    apiKey: getenv('PAYPAL_CLIENT_ID'),
    secret: getenv('PAYPAL_CLIENT_SECRET'),
    mode: 'sandbox' // ou 'live'
);

$paymentManager->registerGateway('paypal', $paypalGateway);

$result = $paymentManager->charge([
    'gateway' => 'paypal',
    'amount' => 99.99,
    'currency' => 'USD',
    'customer' => ['email' => '[email protected]'],
]);

if ($result['success']) {
    echo "✅ Paiement approuvé: " . $result['approval_link'];
} else {
    echo "❌ Erreur: " . $result['error'];
}

use PaymentGateway\Facades\Payment;

// 1. Créer une commande PayPal
$order = Payment::gateway('paypal')->charge([
    'amount' => 99.99,
    'currency' => 'USD',
    'customer' => [
        'email' => '[email protected]',
        'name' => 'Jean Dupont'
    ],
    'description' => 'Achat Premium - Produit XYZ'
]);

// 2. Rediriger le client vers PayPal
if ($order['success']) {
    return redirect($order['approval_link']);
}

// 3. Après approbation (Callback)
$captured = Payment::gateway('paypal')->captureOrderPayment($orderId);

if ($captured['success']) {
    echo "✅ Paiement réussi: " . $captured['capture_id'];
    // Sauvegarder en BDD, envoyer email, etc.
}

use PaymentGateway\Facades\Payment;

$result = Payment::gateway('stripe')->charge([
    'amount' => 99.99,
    'currency' => 'USD',
    'source' => 'tok_visa', // Token du client
    'description' => 'Achat Premium'
]);

if ($result['success']) {
    echo "✅ Paiement réussi: " . $result['transaction_id'];
} else {
    echo "❌ Erreur: " . $result['error'];
}

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use PaymentGateway\Traits\HasPayments;

class Order extends Model
{
    use HasPayments;

    protected $fillable = ['user_id', 'amount', 'currency', 'status'];

    public function processPayment()
    {
        return $this->payment([
            'amount' => $this->amount,
            'currency' => $this->currency,
            'customer' => ['email' => $this->user->email],
            'description' => "Commande #{$this->id}"
        ]);
    }
}

// Usage
$order = Order::create([
    'user_id' => auth()->id(),
    'amount' => 199.99,
    'currency' => 'EUR'
]);

$result = $order->processPayment();

// Vérifier le statut d'un paiement
$status = Payment::gateway('paypal')->verify($transactionId);

if ($status['status'] === 'COMPLETED') {
    $order->update(['status' => 'paid']);
    $order->sendConfirmationEmail();
}

Route::post('/webhooks/paypal', [\App\Http\Controllers\WebhookController::class, 'handlePayPal']);

namespace App\Http\Controllers;

use PaymentGateway\Facades\Payment;

class WebhookController extends Controller
{
    public function handlePayPal(Request $request)
    {
        $payload = $request->all();
        
        // Traiter le webhook
        $result = Payment::gateway('paypal')->handleWebhook(
            $payload,
            $request->headers->all()
        );
        
        if ($result['success']) {
            // Paiement complété/échoué
            $order = Order::where('transaction_id', $result['transaction_id'])
                ->update(['status' => $result['status']]);
            
            return response()->json(['status' => 'ok']);
        }
        
        return response()->json(['status' => 'error'], 400);
    }
}

use PaymentGateway\Events\PaymentSuccessEvent;
use PaymentGateway\Events\PaymentFailedEvent;

// Dans un service provider ou contrôleur
Payment::on(PaymentSuccessEvent::class, function($event) {
    // Envoyer email de confirmation
    Mail::send('emails.payment-confirmed', $event->toArray());
    
    // Logger l'événement
    Log::info('Payment successful', $event->toArray());
});

Payment::on(PaymentFailedEvent::class, function($event) {
    // Notifier l'utilisateur
    Notification::send($event->user, new PaymentFailedNotification());
});

use PaymentGateway\Exceptions\PaymentException;
use PaymentGateway\Exceptions\ValidationException;

try {
    $result = Payment::charge([
        'amount' => 99.99,
        'currency' => 'INVALID', // ❌ Devise invalide
    ]);
} catch (ValidationException $e) {
    echo "❌ Validation échouée: " . $e->getField();
} catch (PaymentException $e) {
    echo "❌ Erreur de paiement: " . $e->getMessage();
}

// Remboursement complet
$refund = Payment::gateway('stripe')->refund($transactionId);

// Remboursement partiel
$refund = Payment::gateway('stripe')->refund(
    $transactionId,
    50.00, // Montant à rembourser
    ['reason' => 'Demande client']
);

if ($refund['success']) {
    echo "✅ Remboursement traité: " . $refund['refund_id'];
}

// 1. Créer une commande
$order = Order::create([
    'user_id' => auth()->id(),
    'items' => $cartItems,
    'total' => 199.99,
    'currency' => 'EUR',
    'status' => 'pending'
]);

// 2. Traiter le paiement Stripe
$payment = Payment::gateway('stripe')->charge([
    'amount' => 199.99,
    'currency' => 'EUR',
    'source' => $request->get('stripe_token'),
    'description' => "Commande #{$order->id}",
    'metadata' => ['order_id' => $order->id]
]);

// 3. Mettre à jour le statut
if ($payment['success']) {
    $order->update([
        'status' => 'paid',
        'transaction_id' => $payment['transaction_id'],
        'paid_at' => now()
    ]);
    
    // Envoyer email de confirmation
    Mail::send('emails.order-confirmed', ['order' => $order]);
    
    return redirect()->route('orders.show', $order)->with('success', '✅ Paiement réussi!');
} else {
    return back()->with('error', '❌ ' . $payment['error']);
}

// 1. Créer une commande non-payée
$order = Order::create([
    'user_id' => auth()->id(),
    'status' => 'pending_payment',
    'total' => 299.99
]);

// 2. Créer l'ordre PayPal
$paypalOrder = Payment::gateway('paypal')->charge([
    'amount' => 299.99,
    'currency' => 'EUR',
    'customer' => [
        'email' => auth()->user()->email,
        'name' => auth()->user()->name
    ],
    'description' => "Commande #{$order->id}"
]);

if ($paypalOrder['success']) {
    // Sauvegarder l'order_id PayPal
    $order->update(['paypal_order_id' => $paypalOrder['order_id']]);
    
    // Rediriger vers PayPal
    return redirect($paypalOrder['approval_link']);
}

// 3. Après approbation (callback)
$captured = Payment::gateway('paypal')->captureOrderPayment(
    $request->get('orderId')
);

if ($captured['success']) {
    $order->update([
        'status' => 'paid',
        'paypal_capture_id' => $captured['capture_id'],
        'paid_at' => now()
    ]);
    
    return redirect()->route('orders.success', $order);
}

// 1. Créer un abonnement
$subscription = Subscription::create([
    'user_id' => auth()->id(),
    'plan' => 'premium',
    'price' => 9.99,
    'currency' => 'USD',
    'billings_cycle' => 'monthly',
    'status' => 'pending'
]);

// 2. Premier paiement
$payment = Payment::gateway('stripe')->charge([
    'amount' => 9.99,
    'currency' => 'USD',
    'source' => $request->get('token'),
    'description' => "Abonnement Premium - Mois 1",
    'metadata' => [
        'subscription_id' => $subscription->id,
        'billing_cycle' => 1
    ]
]);

if ($payment['success']) {
    $subscription->update([
        'status' => 'active',
        'stripe_subscription_id' => $payment['subscription_id'],
        'current_period_start' => now(),
        'current_period_end' => now()->addMonth()
    ]);
}

// 3. Renouvellement automatique via Webhook
// Le webhook PayPal/Stripe mettra automatiquement à jour

// routes/api.php
Route::post('/webhooks/payment', [PaymentWebhookController::class, 'handle']);

// App/Http/Controllers/PaymentWebhookController.php
class PaymentWebhookController extends Controller
{
    public function handle(Request $request)
    {
        $gateway = $request->get('gateway'); // paypal, stripe, etc.
        
        // Traiter le webhook
        $result = Payment::gateway($gateway)->handleWebhook(
            $request->all(),
            $request->headers->all()
        );
        
        if (!$result['success']) {
            return response()->json(['error' => 'Invalid webhook'], 400);
        }
        
        // Mettre à jour le paiement
        $order = Order::where('transaction_id', $result['transaction_id'])->first();
        
        if (!$order) {
            return response()->json(['error' => 'Order not found'], 404);
        }
        
        // Synchroniser le statut
        $order->update(['status' => $result['status']]);
        
        // Déclencher les actions
        match($result['status']) {
            'completed' => $this->handlePaymentCompleted($order),
            'failed' => $this->handlePaymentFailed($order),
            'refunded' => $this->handlePaymentRefunded($order),
            default => null
        };
        
        return response()->json(['status' => 'ok']);
    }
    
    private function handlePaymentCompleted(Order $order)
    {
        // Activer la commande
        $order->activate();
        
        // Envoyer email
        Mail::send('emails.payment-confirmed', ['order' => $order]);
        
        // Déclencher événement personnalisé
        event(new OrderPaid($order));
    }
}

// 1. Initier un remboursement
public function refundOrder(Order $order, Request $request)
{
    // Valider que le paiement peut être remboursé
    if ($order->status !== 'paid') {
        return back()->with('error', 'Seuls les paiements complétés peuvent être remboursés');
    }
    
    // Montant du remboursement (optionnel)
    $amount = $request->get('amount', $order->total);
    
    // Traiter le remboursement
    $refund = Payment::gateway($order->gateway)->refund(
        $order->transaction_id,
        $amount,
        ['reason' => $request->get('reason')]
    );
    
    if ($refund['success']) {
        $order->update([
            'status' => 'refunded',
            'refund_id' => $refund['refund_id'],
            'refunded_at' => now(),
            'refund_amount' => $amount
        ]);
        
        // Notifier le client
        Mail::send('emails.refund-processed', ['order' => $order]);
        
        return back()->with('success', '✅ Remboursement traité');
    } else {
        return back()->with('error', '❌ ' . $refund['error']);
    }
}

// 2. Vérifier le statut du remboursement
$status = Payment::gateway($order->gateway)->verify($order->transaction_id);

if ($status['status'] === 'refunded') {
    echo "✅ Remboursement complété";
    echo "Montant: " . $status['refund_amount'];
}

// Accepter les paiements en plusieurs devises
$order = Order::create([
    'amount' => 100,
    'currency' => $request->get('currency') // EUR, USD, GBP, etc.
]);

// PayPal supporte 20+ devises
$payment = Payment::gateway('paypal')->charge([
    'amount' => 100,
    'currency' => 'EUR', // ✅ Non USD!
    'customer' => ['email' => '[email protected]']
]);

// Taux de change automatique appliqué

// Tous les paiements sont automatiquement loggés
use PaymentGateway\Models\WebhookLog;
use PaymentGateway\Models\Transaction;

// Voir tous les paiements
$transactions = Transaction::where('gateway', 'paypal')
    ->where('status', 'completed')
    ->get();

// Voir tous les webhooks reçus
$webhooks = WebhookLog::where('gateway', 'paypal')
    ->where('status', 'received')
    ->latest()
    ->paginate(20);

// Voir les erreurs
$failed = Transaction::where('status', 'failed')
    ->whereDate('created_at', today())
    ->get();

// Logger personnalisé
Log::info('Payment processed', [
    'order_id' => $order->id,
    'transaction_id' => $payment['transaction_id'],
    'amount' => $payment['amount'],
    'gateway' => 'paypal'
]);

use PaymentGateway\Events\PaymentSuccessEvent;
use PaymentGateway\Events\PaymentFailedEvent;
use PaymentGateway\Events\WebhookReceivedEvent;

// Dans un service provider
Payment::on(PaymentSuccessEvent::class, function($event) {
    // Envoyer email
    Mail::send('emails.payment-success', ['event' => $event]);
    
    // Mettre à jour les stats
    Stats::increment('payments_completed', $event->amount);
    
    // Déclencher action
    $event->order->activate();
});

Payment::on(PaymentFailedEvent::class, function($event) {
    // Notifier l'admin
    Notification::send(Admin::all(), new PaymentFailedNotification($event));
    
    // Logger l'erreur
    Log::error('Payment failed', $event->toArray());
});

Payment::on(WebhookReceivedEvent::class, function($event) {
    // Audit trail
    AuditLog::create([
        'event' => 'webhook_received',
        'gateway' => $event->gateway,
        'type' => $event->event_type,
        'ip' => request()->ip()
    ]);
});

return [
    'default_gateway' => 'stripe',
    
    'gateways' => [
        'stripe' => [
            'driver' => 'stripe',
            'api_key' => env('STRIPE_API_KEY'),
            'secret_key' => env('STRIPE_SECRET_KEY'),
            'test_mode' => env('APP_ENV') !== 'production'
        ],
        
        'paypal' => [
            'driver' => 'paypal',
            'mode' => env('PAYPAL_MODE', 'sandbox'),
            'client_id' => env('PAYPAL_CLIENT_ID'),
            'client_secret' => env('PAYPAL_CLIENT_SECRET')
        ],
        
        'square' => [
            'driver' => 'square',
            'access_token' => env('SQUARE_ACCESS_TOKEN')
        ]
    ],
    
    'webhook_url' => env('APP_URL') . '/webhooks/payment',
    'webhook_secret' => env('PAYMENT_WEBHOOK_SECRET'),
    'log_channel' => env('PAYMENT_LOG_CHANNEL', 'single')
];

// ✅ BON
Payment::charge([
    'amount' => $amount,
    'currency' => 'USD',
    'source' => $token  // Token Stripe/PayPal
]);

// ❌ MAUVAIS - Ne jamais envoyer les numéros de carte
$payment = Payment::charge([
    'amount' => $amount,
    'card_number' => '4242' // ❌ DANGER!
]);
bash
php artisan vendor:publish --provider="PaymentGateway\ServiceProvider"
bash
php artisan migrate
bash
# Tests unitaires
php ./vendor/bin/phpunit

# Tests spécifiques à Stripe
php ./vendor/bin/phpunit tests/Integration/StripeTest.php

# Avec couverture
php ./vendor/bin/phpunit --coverage-html coverage/
bash
php artisan payment:test --gateway=stripe --amount=10 --currency=USD
bash
# Formater le code
php ./vendor/bin/php-cs-fixer fix

# Analyser statiquement
php ./vendor/bin/phpstan analyse