Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Multipayment Gateways Laravel Package

musahmusah/laravel-multipayment-gateways

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require musahmusah/laravel-multipayment-gateways
    php artisan vendor:publish --provider="MusahMusah\MultiPaymentGateways\MultiPaymentGatewaysServiceProvider" --tag="config"
    

    Publish the config file to customize gateway settings.

  2. Configuration Update config/multipayment-gateways.php with your API keys and preferred gateways (e.g., PayPal, Stripe, Flutterwave). Example:

    'gateways' => [
        'paypal' => [
            'enabled' => true,
            'client_id' => env('PAYPAL_CLIENT_ID'),
            'secret' => env('PAYPAL_SECRET'),
        ],
        'stripe' => [
            'enabled' => true,
            'secret_key' => env('STRIPE_SECRET_KEY'),
        ],
    ],
    
  3. First Use Case: Create a Payment Use the Payment facade to initiate a payment:

    use MusahMusah\MultiPaymentGateways\Facades\Payment;
    
    $payment = Payment::create([
        'gateway' => 'paypal', // or 'stripe', etc.
        'amount' => 100.00,
        'currency' => 'USD',
        'description' => 'Order #12345',
        'metadata' => ['order_id' => 12345],
    ]);
    

    This returns a Payment model with a gateway_response attribute containing the gateway-specific response (e.g., PayPal approval URL).


Where to Look First

  • Documentation: Check the GitHub README for gateway-specific examples and webhook setup.
  • Config File: config/multipayment-gateways.php defines enabled gateways, API keys, and default settings.
  • Facade: Payment facade is the primary entry point for all operations (create, verify, refund, etc.).
  • Webhook Routes: The package includes a webhook route handler (see routes/web.php after publishing).

Implementation Patterns

Core Workflows

1. Payment Creation and Redirection

  • Use the Payment facade to create a payment and redirect users to the gateway:
    $payment = Payment::create(['gateway' => 'paypal', 'amount' => 100.00, ...]);
    return redirect()->away($payment->gateway_response->redirect_url);
    
  • Store the payment_id in the session or database for later verification.

2. Webhook Handling

  • The package auto-registers a webhook route (/payment/webhook). Handle gateway-specific events in a service:
    use MusahMusah\MultiPaymentGateways\Events\PaymentSucceeded;
    
    PaymentSucceeded::subscribe(function ($event) {
        // Update order status, send notifications, etc.
        Order::find($event->payment->metadata['order_id'])
            ->update(['status' => 'paid']);
    });
    
  • For custom logic, extend the PaymentWebhookHandler class or override the handleWebhook method.

3. Verification and Callback

  • After redirection, verify the payment on callback:
    $payment = Payment::find($request->payment_id);
    $verified = $payment->verify($request->all());
    
  • Use verify() to check the gateway's response (e.g., PayPal's PayerID or Stripe's payment_intent).

4. Refunds and Cancellations

  • Initiate a refund via the Payment model:
    $payment->refund(['amount' => 50.00, 'reason' => 'Customer dispute']);
    
  • The package handles gateway-specific refund logic internally.

Integration Tips

Database Schema

  • The package includes a payments table migration. Customize it if needed (e.g., add user_id or invoice_number):
    Schema::table('payments', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained()->nullable();
    });
    

Testing

  • Use the PaymentGatewayMock trait to simulate responses in tests:
    use MusahMusah\MultiPaymentGateways\Testing\PaymentGatewayMock;
    
    public function test_payment_creation()
    {
        $this->mockPaymentGateway('paypal', 'success');
        $payment = Payment::create([...]);
        $this->assertEquals('success', $payment->status);
    }
    

Dynamic Gateway Selection

  • Choose gateways dynamically based on user location or preferences:
    $gateway = request()->input('gateway') ?? config('multipayment-gateways.default_gateway');
    $payment = Payment::create(['gateway' => $gateway, ...]);
    

Logging and Monitoring

  • Enable debug logging in config/multipayment-gateways.php:
    'debug' => env('APP_ENV') === 'local',
    
  • Monitor webhook failures with Laravel's failed_jobs table or a third-party service.

Gotchas and Tips

Pitfalls

1. Webhook Signatures

  • Some gateways (e.g., Stripe) require signature verification. Ensure your webhook handler validates signatures:
    $valid = $payment->verifyWebhook($request->all());
    if (!$valid) {
        abort(403, 'Invalid webhook signature');
    }
    
  • The package includes basic signature verification, but extend it for custom gateways.

2. Idempotency

  • Webhook payloads may be retried. Use idempotency keys to avoid duplicate processing:
    $payment->update(['idempotency_key' => $request->idempotency_key]);
    
  • Store the key in the payments table and check it before processing.

3. Gateway-Specific Quirks

  • PayPal: Requires cancel_url and return_url in the initial request. Add them to the Payment facade config:
    'paypal' => [
        'return_url' => route('paypal.callback'),
        'cancel_url' => route('paypal.cancel'),
    ],
    
  • Flutterwave: Uses a different API structure for verification. Ensure the verify() method is called with the correct payload:
    $payment->verify(['tx_ref' => $request->tx_ref, 'flw_ref' => $request->flw_ref]);
    

4. Rate Limiting

  • Gateways like Stripe may throttle requests. Implement middleware to limit payment creation:
    Route::middleware(['throttle:10,1'])->group(function () {
        Route::post('/create-payment', [PaymentController::class, 'create']);
    });
    

5. Currency and Amount Formatting

  • Ensure amounts are passed as integers (e.g., 100.0010000 for cents) and currencies are ISO codes (e.g., USD). The package handles conversion internally, but validate inputs:
    $amount = (int) ($request->amount * 100);
    

Debugging Tips

1. Enable Debug Mode

  • Set 'debug' => true in the config to log raw gateway responses and errors to storage/logs/laravel.log.

2. Gateway-Specific Logs

  • Check the gateway_response attribute on the Payment model for raw responses:
    $payment = Payment::find(1);
    \Log::info('Gateway Response:', [$payment->gateway_response]);
    

3. Testing Webhooks Locally

  • Use tools like ngrok to expose your local webhook endpoint to gateways for testing:
    ngrok http 8000
    
  • Configure the gateway to send webhooks to https://your-ngrok-url.ngrok.io/payment/webhook.

4. Common Errors

  • GatewayNotFound: Ensure the gateway is enabled in the config and the name matches exactly (case-sensitive).
  • InvalidSignature: Verify your webhook secret matches the gateway's configuration.
  • AmountMismatch: Double-check currency and amount formatting (e.g., 100.00 vs. 10000 for cents).

Extension Points

1. Custom Gateways

  • Extend the Gateway class to add support for unsupported gateways:
    namespace App\Gateways;
    
    use MusahMusah\MultiPaymentGateways\Contracts\Gateway;
    
    class CustomGateway implements Gateway {
        public function create(array $data): array {
            // Custom logic for your gateway
            return ['redirect_url
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope