PHP code example of sunucode / afripay

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

    

sunucode / afripay example snippets


// Payer via Wave
$payment = AfriPay::via('wave')->charge([
    'amount'      => 15000,
    'currency'    => 'XOF',
    'description' => 'Abonnement Premium',
    'success_url' => route('payment.success'),
    'error_url'   => route('payment.error'),
]);

return redirect($payment['redirect_url']);

AfriPay::via('stripe')->charge([...]);
AfriPay::via('paydunya')->charge([...]);
AfriPay::via('orange_money')->charge([...]);

use SunuCode\AfriPay\Facades\AfriPay;

$payment = AfriPay::via('wave')->charge([
    'amount'      => 25000,
    'currency'    => 'XOF',
    'description' => 'Commande #1234',
    'success_url' => route('orders.payment.success'),
    'error_url'   => route('orders.payment.error'),
    'metadata'    => [
        'order_id' => 1234,
        'user_id'  => auth()->id(),
    ],
]);

// $payment['redirect_url']  -> URL de paiement (rediriger l'utilisateur)
// $payment['transaction']   -> Instance Transaction (sauvegardée en DB)

return redirect($payment['redirect_url']);

// Abonnement
$payment = AfriPay::via('wave')->charge([
    'amount'        => 9900,
    'success_url'   => route('payment.success'),
    'error_url'     => route('payment.error'),
    'payable_type'  => Subscription::class,
    'payable_id'    => $subscription->id,
]);

// Commande e-commerce
$payment = AfriPay::via('paydunya')->charge([
    'amount'        => 25000,
    'success_url'   => route('payment.success'),
    'error_url'     => route('payment.error'),
    'payable_type'  => Order::class,
    'payable_id'    => $order->id,
]);

// Recharge de wallet (sans modèle lié)
$payment = AfriPay::via('orange_money')->charge([
    'amount'        => 5000,
    'success_url'   => route('payment.success'),
    'error_url'     => route('payment.error'),
    'metadata'      => ['user_id' => auth()->id(), 'type' => 'wallet_topup'],
]);

Event::listen(PaymentCompleted::class, function ($event) {
    $order = $event->transaction->payable;
    $order->markAsPaid();
});

// app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Event;
use SunuCode\AfriPay\Events\PaymentCompleted;
use SunuCode\AfriPay\Events\PaymentFailed;
use SunuCode\AfriPay\Events\PaymentRefunded;

public function boot(): void
{
    Event::listen(PaymentCompleted::class, function ($event) {
        $transaction = $event->transaction;
        $payable = $transaction->payable; // Le modèle lié (Order, Subscription...)

        match ($transaction->payable_type) {
            \App\Models\Subscription::class => $payable->activate(),
            \App\Models\Order::class        => $payable->markAsPaid(),
            default                         => $this->handleGenericPayment($transaction),
        };
    });

    Event::listen(PaymentFailed::class, function ($event) {
        $transaction = $event->transaction;

        match ($transaction->payable_type) {
            \App\Models\Order::class => $transaction->payable->cancel(),
            default                  => null,
        };

        // Notifier l'utilisateur dans tous les cas
        // Notification::send($transaction->payable?->user, new PaymentFailedNotification($transaction));
    });

    Event::listen(PaymentRefunded::class, function ($event) {
        // $event->reason contient le motif du remboursement
    });
}

Event::listen(PaymentCompleted::class, HandleCompletedPayment::class);
Event::listen(PaymentFailed::class, HandleFailedPayment::class);

use SunuCode\AfriPay\Facades\AfriPay;
use SunuCode\AfriPay\Models\Transaction as AfriPayTransaction;

public function success(string $reference)
{
    $transaction = AfriPayTransaction::where('reference', $reference)->firstOrFail();

    // Vérifie auprès de la passerelle ET dispatche PaymentCompleted si confirmé
    $transaction = AfriPay::verifyAndProcess($transaction);

    if ($transaction->status->isCompleted()) {
        return view('payment.success', compact('transaction'));
    }

    // Le paiement n'est pas encore confirmé (webhook en attente)
    return view('payment.pending', compact('transaction'));
}

$transaction = AfriPay::refund($transaction, 'Client insatisfait');
// Dispatche PaymentRefunded

// Toutes les passerelles activées via .env
$gateways = AfriPay::enabledGateways();
// ['wave', 'stripe', 'paydunya', 'paytech']

// Vérifier si une passerelle est active
if (AfriPay::isEnabled('orange_money')) {
    // ...
}

// Dans un ServiceProvider
use SunuCode\AfriPay\PaymentManager;

PaymentManager::extend('cinetpay', function (array $config) {
    return new CinetPayGateway($config);
});

// Utilisation
AfriPay::via('cinetpay')->charge([...]);

$payment = AfriPay::via('wave')->charge([
    'amount'      => 15000,
    'currency'    => 'XOF',
    'description' => 'Premium Subscription',
    'success_url' => route('payment.success'),
    'error_url'   => route('payment.error'),
]);

return redirect($payment['redirect_url']);

use Illuminate\Support\Facades\Event;
use SunuCode\AfriPay\Events\PaymentCompleted;
use SunuCode\AfriPay\Events\PaymentFailed;

public function boot(): void
{
    Event::listen(PaymentCompleted::class, function ($event) {
        $transaction = $event->transaction;
        $payable = $transaction->payable;

        match ($transaction->payable_type) {
            \App\Models\Subscription::class => $payable->activate(),
            \App\Models\Order::class        => $payable->markAsPaid(),
            default                         => null,
        };
    });

    Event::listen(PaymentFailed::class, function ($event) {
        // Notify user, log failure, etc.
    });
}

use SunuCode\AfriPay\Facades\AfriPay;
use SunuCode\AfriPay\Models\Transaction as AfriPayTransaction;

public function success(string $reference)
{
    $transaction = AfriPayTransaction::where('reference', $reference)->firstOrFail();
    $transaction = AfriPay::verifyAndProcess($transaction);

    if ($transaction->status->isCompleted()) {
        return view('payment.success', compact('transaction'));
    }

    return view('payment.pending', compact('transaction'));
}

use SunuCode\AfriPay\Contracts\GatewayInterface;
use SunuCode\AfriPay\PaymentManager;

class CinetPayGateway implements GatewayInterface
{
    // Implement the 4 methods: charge(), handleWebhook(), verify(), verifySignature()
}

PaymentManager::extend('cinetpay', fn($config) => new CinetPayGateway($config));
bash
php artisan afripay:install
php artisan migrate
bash
# Exemple : app/Http/Controllers/Payment/AfriPayController.php
php artisan afripay:install --controller-path=Http/Controllers/Payment
bash
php artisan vendor:publish --tag=afripay-config
php artisan migrate
bash
composer up (recommended) — scaffolds controller, views, routes, and listeners
php artisan afripay:install
php artisan migrate
bash
php artisan afripay:install --controller-path=Http/Controllers/Payment