PHPackages                             room/laravel-payment-gateways - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. room/laravel-payment-gateways

ActiveLibrary[Payment Processing](/categories/payments)

room/laravel-payment-gateways
=============================

A Laravel package for managing multiple payment gateways (Cinetpay, Bizao, Winipayer) with automatic failover and dynamic configuration

631PHP

Since Jul 13Pushed 10mo agoCompare

[ Source](https://github.com/roomdada/laravel-payment-gateways)[ Packagist](https://packagist.org/packages/room/laravel-payment-gateways)[ RSS](/packages/room-laravel-payment-gateways/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Payment Gateways
========================

[](#laravel-payment-gateways)

Un package Laravel réutilisable pour gérer plusieurs agrégateurs de paiement (Cinetpay, Bizao, Winipayer) de manière modulaire, configurable et hautement flexible.

🚀 Fonctionnalités
-----------------

[](#-fonctionnalités)

- **Interface unifiée** : Une interface commune pour tous les gateways de paiement
- **Failover automatique** : Basculement automatique entre les gateways en cas de défaillance
- **Configuration dynamique** : Configuration via fichiers ou base de données
- **Webhooks intégrés** : Gestion automatique des notifications de paiement
- **Logging complet** : Traçabilité de toutes les opérations
- **Extensible** : Facile d'ajouter de nouveaux gateways
- **Tests complets** : Tests unitaires et d'intégration inclus

📋 Prérequis
-----------

[](#-prérequis)

- PHP 8.1+
- Laravel 9.0+ ou 10.0+
- Composer

🔧 Installation
--------------

[](#-installation)

1. **Installer le package via Composer :**

```
composer require room/laravel-payment-gateways
```

2. **Publier la configuration :**

```
php artisan vendor:publish --tag=laravel-payment-gateways-config
```

3. **Exécuter les migrations :**

```
php artisan migrate
```

⚙️ Configuration
----------------

[](#️-configuration)

### 🎯 Flexibilité des Endpoints

[](#-flexibilité-des-endpoints)

Le package est conçu pour être **maximalement flexible** :

- ✅ **Contrôle total des endpoints** : Vous définissez vos propres URLs d'API
- ✅ **Pas de vérification automatique** : Le package ne fait pas de vérification de santé automatique
- ✅ **Endpoints de production par défaut** : Utilise les URLs de production des agrégateurs
- ✅ **Configuration simple** : Juste les credentials et l'URL de base

**Exemple de configuration flexible :**

```
# Production
CINETPAY_BASE_URL=https://api-checkout.cinetpay.com/v2
BIZAO_BASE_URL=https://api.bizao.com
WINIPAYER_BASE_URL=https://api.winipayer.com

# Ou vos propres endpoints
CINETPAY_BASE_URL=https://votre-api-cinetpay.com
BIZAO_BASE_URL=https://votre-api-bizao.com
WINIPAYER_BASE_URL=https://votre-api-winipayer.com
```

### Variables d'environnement

[](#variables-denvironnement)

Ajoutez ces variables à votre fichier `.env` :

```
# Gateway par défaut
PAYMENT_DEFAULT_GATEWAY=cinetpay

# Configuration Cinetpay
CINETPAY_ENABLED=true
CINETPAY_API_KEY=your_api_key
CINETPAY_SITE_ID=your_site_id
CINETPAY_BASE_URL=https://api-checkout.cinetpay.com/v2
CINETPAY_CURRENCY=XOF
CINETPAY_WEBHOOK_URL=https://your-domain.com/payment/webhook/cinetpay

# Configuration Bizao
BIZAO_ENABLED=true
BIZAO_CLIENT_ID=your_client_id
BIZAO_CLIENT_SECRET=your_client_secret
BIZAO_BASE_URL=https://api.bizao.com
BIZAO_CURRENCY=XOF
BIZAO_WEBHOOK_URL=https://your-domain.com/payment/webhook/bizao

# Configuration Winipayer
WINIPAYER_ENABLED=true
WINIPAYER_MERCHANT_ID=your_merchant_id
WINIPAYER_API_KEY=your_api_key
WINIPAYER_BASE_URL=https://api.winipayer.com
WINIPAYER_CURRENCY=XOF
WINIPAYER_WEBHOOK_URL=https://your-domain.com/payment/webhook/winipayer

# Configuration du failover
PAYMENT_FAILOVER_ENABLED=true
PAYMENT_MAX_RETRIES=3
PAYMENT_RETRY_DELAY=2
PAYMENT_EXPONENTIAL_BACKOFF=true

# Configuration des webhooks
PAYMENT_WEBHOOKS_ENABLED=true
PAYMENT_WEBHOOK_ROUTE_PREFIX=payment/webhook
PAYMENT_WEBHOOK_TIMEOUT=10

# Configuration du logging
PAYMENT_LOGGING_ENABLED=true
PAYMENT_LOG_CHANNEL=payment
PAYMENT_LOG_LEVEL=info
```

### Configuration avancée

[](#configuration-avancée)

Vous pouvez également configurer les gateways via le fichier `config/laravel-payment-gateways.php` :

```
return [
    'default' => env('PAYMENT_DEFAULT_GATEWAY', 'cinetpay'),

    'gateways' => [
        'cinetpay' => [
            'enabled' => env('CINETPAY_ENABLED', true),
            'priority' => 1,
            'api_key' => env('CINETPAY_API_KEY'),
            'site_id' => env('CINETPAY_SITE_ID'),
            'environment' => env('CINETPAY_ENVIRONMENT', 'PROD'),
            'base_url' => env('CINETPAY_BASE_URL', 'https://api-checkout.cinetpay.com/v2'),
            'currency' => env('CINETPAY_CURRENCY', 'XOF'),
            'timeout' => env('CINETPAY_TIMEOUT', 30),
            'webhook_url' => env('CINETPAY_WEBHOOK_URL'),
        ],
        // ... autres gateways
    ],

    'failover' => [
        'enabled' => env('PAYMENT_FAILOVER_ENABLED', true),
        'max_retries' => env('PAYMENT_MAX_RETRIES', 3),
        'retry_delay' => env('PAYMENT_RETRY_DELAY', 2),
        'exponential_backoff' => env('PAYMENT_EXPONENTIAL_BACKOFF', true),
    ],
];
```

🎯 Utilisation
-------------

[](#-utilisation)

### Initialisation d'un paiement

[](#initialisation-dun-paiement)

```
use PaymentManager\Contracts\PaymentManagerInterface;

class PaymentController extends Controller
{
    public function __construct(
        private PaymentManagerInterface $paymentManager
    ) {}

    public function initializePayment(Request $request)
    {
        $paymentData = [
            'amount' => 1000.00,
            'currency' => 'XOF',
            'description' => 'Paiement pour commande #123',
            'return_url' => route('payment.success'),
            'cancel_url' => route('payment.cancel'),
            'customer_email' => 'client@example.com',
            'customer_phone' => '+22670123456',
            'customer_name' => 'John Doe',
        ];

        try {
            // Utiliser le gateway par défaut
            $response = $this->paymentManager->initializePayment($paymentData);

            // Ou spécifier un gateway préféré
            // $response = $this->paymentManager->initializePayment($paymentData, 'bizao');

            if ($response->isSuccessful()) {
                return redirect($response->getPaymentUrl());
            }

            return back()->withErrors(['payment' => $response->getErrorMessage()]);

        } catch (\Exception $e) {
            return back()->withErrors(['payment' => 'Erreur lors de l\'initialisation du paiement']);
        }
    }
}
```

### Vérification du statut d'un paiement

[](#vérification-du-statut-dun-paiement)

```
public function verifyPayment(string $transactionId)
{
    try {
        $response = $this->paymentManager->verifyPayment($transactionId);

        if ($response->isSuccessful()) {
            switch ($response->getStatus()) {
                case 'completed':
                    return response()->json(['status' => 'success', 'message' => 'Paiement réussi']);
                case 'pending':
                    return response()->json(['status' => 'pending', 'message' => 'Paiement en cours']);
                case 'failed':
                    return response()->json(['status' => 'failed', 'message' => 'Paiement échoué']);
                default:
                    return response()->json(['status' => 'unknown', 'message' => 'Statut inconnu']);
            }
        }

        return response()->json(['status' => 'error', 'message' => $response->getErrorMessage()]);

    } catch (\Exception $e) {
        return response()->json(['status' => 'error', 'message' => 'Erreur lors de la vérification']);
    }
}
```

### Gestion des webhooks

[](#gestion-des-webhooks)

Les webhooks sont automatiquement configurés aux routes suivantes :

- `POST /payment/webhook/cinetpay`
- `POST /payment/webhook/bizao`
- `POST /payment/webhook/winipayer`

Vous pouvez personnaliser la gestion des webhooks en créant votre propre contrôleur :

```
use PaymentManager\Contracts\PaymentManagerInterface;

class CustomWebhookController extends Controller
{
    public function __construct(
        private PaymentManagerInterface $paymentManager
    ) {}

    public function handleCinetpayWebhook(Request $request)
    {
        try {
            $response = $this->paymentManager->processWebhook($request->all(), 'cinetpay');

            if ($response->isSuccessful()) {
                // Traiter le paiement réussi
                $this->processSuccessfulPayment($response);
                return response('OK', 200);
            }

            return response('Error', 400);

        } catch (\Exception $e) {
            return response('Error: ' . $e->getMessage(), 500);
        }
    }

    private function processSuccessfulPayment($response)
    {
        // Votre logique métier ici
        // Par exemple, mettre à jour le statut de la commande
    }
}
```

### Gestion avancée des gateways

[](#gestion-avancée-des-gateways)

```
// Obtenir tous les gateways disponibles
$availableGateways = $this->paymentManager->getAvailableGateways();

// Obtenir un gateway spécifique
$cinetpayGateway = $this->paymentManager->getGateway('cinetpay');

// Changer le gateway par défaut
$this->paymentManager->setDefaultGateway('bizao');

// Activer/désactiver le failover
$this->paymentManager->setFailoverEnabled(false);
```

🔧 Extension du package
----------------------

[](#-extension-du-package)

### Ajouter un nouveau gateway

[](#ajouter-un-nouveau-gateway)

1. **Créer la classe du gateway :**

```
