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

Mangopay Bundle Laravel Package

appventus/mangopay-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle (if using the forked version):

    composer require troopers/mangopay-bundle
    

    (Note: The original appventus/mangopay-bundle is archived; use the Troopers fork instead.)

  2. Enable the Bundle in config/bundles.php:

    Troopers\MangopayBundle\TroopersMangopayBundle::class => ['all' => true],
    
  3. Configure Mangopay in config/packages/troopers_mangopay.yaml:

    mangopay:
        client_id: "%env(MANGOPAY_CLIENT_ID)%"
        client_password: "%env(MANGOPAY_CLIENT_PASSWORD)%"
        base_url: "%env(MANGOPAY_BASE_URL)%"  # e.g., "https://api.sandbox.mangopay.com/v2"
    
  4. First Use Case: Fetch a User’s Wallet Balance Inject the MangoPayClient service (auto-registered) into a controller/service:

    use Troopers\MangopayBundle\Service\MangoPayClient;
    
    public function getUserBalance(MangoPayClient $mangoPay, User $user)
    {
        $wallet = $mangoPay->getWallet($user->mangopayWalletId);
        return $wallet->getBalance();
    }
    

Implementation Patterns

Core Workflows

  1. Service Integration:

    • Use dependency injection for MangoPayClient to interact with Mangopay’s API.
    • Example: Create a payment:
      $payment = $mangoPay->createPayment([
          'AuthorId' => $user->mangopayUserId,
          'DebitedFunds' => ['WalletId' => $user->walletId, 'Amount' => 1000, 'Currency' => 'EUR'],
          'CreditedFunds' => [['WalletId' => $merchantWalletId, 'Amount' => 950, 'Currency' => 'EUR']],
          'Fees' => [['Amount' => 50, 'Currency' => 'EUR']],
      ]);
      
  2. Event-Driven Extensions:

    • Subscribe to Mangopay webhooks (e.g., PaymentSucceeded) via Symfony’s event system.
    • Example listener:
      use Troopers\MangopayBundle\Event\MangoPayEvent;
      
      public function onPaymentSucceeded(MangoPayEvent $event)
      {
          $payment = $event->getPayment();
          // Update your database or trigger logic.
      }
      
    • Register in services.yaml:
      services:
          App\EventListener\MangoPayListener:
              tags:
                  - { name: 'kernel.event_listener', event: 'mangopay.payment.succeeded', method: 'onPaymentSucceeded' }
      
  3. Model Mapping:

    • Map Mangopay entities (e.g., User, Wallet, Payment) to your Eloquent models.
    • Example trait for a User model:
      use Troopers\MangopayBundle\Traits\MangoPayUserTrait;
      
      class User extends Model
      {
          use MangoPayUserTrait;
      }
      
  4. Batch Operations:

    • Use the SDK’s batch endpoints (e.g., createPayIns) for bulk operations:
      $payIns = $mangoPay->createPayIns([
          ['WalletId' => $walletId1, 'Amount' => 500, 'Currency' => 'EUR'],
          ['WalletId' => $walletId2, 'Amount' => 300, 'Currency' => 'EUR'],
      ]);
      

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle:

    • The original appventus/mangopay-bundle is archived. Use the Troopers fork for updates.
    • Verify compatibility with your Symfony/Laravel version (the bundle targets Symfony 2.3+).
  2. Environment Variables:

    • Ensure MANGOPAY_CLIENT_ID, MANGOPAY_CLIENT_PASSWORD, and MANGOPAY_BASE_URL are set in .env.
    • Sandbox vs. Production: Always test in Mangopay’s sandbox (https://api.sandbox.mangopay.com/v2) before going live.
  3. Error Handling:

    • Mangopay’s SDK throws exceptions for API errors. Catch them explicitly:
      try {
          $mangoPay->createPayment($data);
      } catch (\Mangopay\Exception\MangopayException $e) {
          Log::error("Mangopay Error: " . $e->getMessage());
          throw new \RuntimeException("Payment failed: " . $e->getCode());
      }
      
  4. Idempotency:

    • Mangopay requires IdempotencyKey for idempotent requests (e.g., payments). Generate a unique key per request:
      $idempotencyKey = Str::uuid()->toString();
      $mangoPay->createPayment($data + ['IdempotencyKey' => $idempotencyKey]);
      
  5. Webhook Verification:

    • Mangopay sends webhooks to a Symfony endpoint. Verify signatures using the MangoPayWebhookValidator service:
      use Troopers\MangopayBundle\Service\MangoPayWebhookValidator;
      
      public function verifyWebhook(MangoPayWebhookValidator $validator, Request $request)
      {
          if (!$validator->validate($request)) {
              abort(403, 'Invalid webhook signature');
          }
          // Process webhook.
      }
      

Tips

  1. Logging:

    • Enable debug logging for Mangopay requests in config/packages/monolog.yaml:
      handlers:
          mangopay:
              type: stream
              path: "%kernel.logs_dir%/mangopay.log"
              level: debug
              channels: ["mangopay"]
      
    • Add the channel to your MangoPayClient configuration.
  2. Testing:

    • Use Mangopay’s sandbox for unit/integration tests. Mock the MangoPayClient in PHPUnit:
      $this->mock(MangoPayClient::class)->shouldReceive('createPayment')->andReturn($mockPayment);
      
  3. Custom Entities:

    • Extend Mangopay’s entities (e.g., User, Wallet) to add custom fields:
      class CustomUser extends \Mangopay\User
      {
          public function getCustomField()
          {
              return $this->customField;
          }
      }
      
    • Register the custom class in the bundle’s configuration.
  4. Performance:

    • Cache frequent API calls (e.g., wallet balances) using Symfony’s cache system:
      $cache = $this->container->get('cache.app');
      $balance = $cache->get("wallet_{$walletId}_balance", function() use ($mangoPay, $walletId) {
          return $mangoPay->getWallet($walletId)->getBalance();
      });
      
  5. Documentation:

    • Refer to the Mangopay PHP SDK docs for advanced use cases (e.g., direct debits, payouts).
    • The bundle wraps the SDK but may not expose all features. Check the source for unsupported endpoints.
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui