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

Symfony Mono Acquiring Bundle Laravel Package

12goyuriyr/symfony-mono-acquiring-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require 12goyuriyr/symfony-mono-acquiring-bundle
    

    Ensure MonobankAcquiring\MonobankAcquiringBundle is registered in config/bundles.php.

  2. Configuration: Add your Monobank token to .env:

    MONO_API_TOKEN=your_merchant_token_here
    

    Create config/packages/monobank_acquiring.yaml:

    monobank_acquiring:
        api_token: '%env(MONO_API_TOKEN)%'
    
  3. First Use Case: Inject the MonobankAcquiringClientInterface into a service/controller:

    use MonobankAcquiring\Client\MonobankAcquiringClientInterface;
    
    class PaymentController {
        public function __construct(
            private MonobankAcquiringClientInterface $client
        ) {}
    
        public function createInvoice(): void
        {
            $invoice = $this->client->createInvoice(
                amount: 100.00,
                currency: 'UAH',
                description: 'Test payment',
                orderId: 'order_123'
            );
            // Handle response (DTO object)
        }
    }
    

Implementation Patterns

Core Workflows

  1. Payment Invoice Creation: Use createInvoice() with required parameters (amount, currency, description, orderId).

    $invoice = $client->createInvoice(
        amount: 100.50,
        currency: 'USD',
        description: 'Product purchase',
        orderId: 'order_456',
        successUrl: '/payment/success',
        failureUrl: '/payment/failure'
    );
    
    • Response: Returns a typed Invoice DTO with id, status, and other metadata.
  2. Status Checks: Poll invoice status with getInvoice():

    $invoice = $client->getInvoice('invoice_id_123');
    if ($invoice->getStatus() === 'PAID') {
        // Process payment
    }
    
  3. Currency Exchange Rates: Fetch rates via getExchangeRates():

    $rates = $client->getExchangeRates(['USD', 'EUR']);
    // $rates['USD'] = 38.50 (example)
    

Integration Tips

  • Event-Driven Payments: Combine with Symfony Messenger for async status checks:
    $client->getInvoice('invoice_id')->then(
        fn(Invoice $invoice) => $bus->dispatch(new ProcessPayment($invoice))
    );
    
  • Validation: Use Symfony Validator to validate DTOs before API calls:
    $constraints = new Assert\Collection([
        'amount' => new Assert\NotBlank(),
        'currency' => new Assert\Choice(['UAH', 'USD', 'EUR']),
    ]);
    $validator->validate($data, $constraints);
    
  • Retry Logic: Implement exponential backoff for transient failures (e.g., PAYMENT_PENDING):
    use Symfony\Component\Retry\Retry;
    
    Retry::create()
        ->withMaxAttempts(3)
        ->withDelay(1000)
        ->execute(fn() => $client->getInvoice($invoiceId));
    

Gotchas and Tips

Pitfalls

  1. Token Security:

    • Never hardcode MONO_API_TOKEN in config files. Use .env and restrict file permissions.
    • Validate token format (should be a 32-character alphanumeric string).
  2. Idempotency:

    • Monobank API may reject duplicate orderId for the same amount. Use UUIDs or timestamps for uniqueness:
      $orderId = 'order_' . Str::uuid()->toString();
      
  3. Rate Limits:

    • Monobank enforces rate limits. Cache getExchangeRates() responses:
      $cache = $container->get('monobank_acquiring.cache.exchange_rates');
      $rates = $cache->get('rates', fn() => $client->getExchangeRates(['USD']));
      
  4. Webhook Validation:

    • The bundle doesn’t handle webhooks. Validate signatures manually:
      $signature = $_SERVER['HTTP_X_MONO_SIGNATURE'];
      $expected = hash_hmac('sha256', $payload, $apiToken);
      if (!hash_equals($signature, $expected)) {
          throw new \RuntimeException('Invalid signature');
      }
      

Debugging

  • Enable API Debugging: Set MONO_API_DEBUG=true in .env to log raw requests/responses to var/log/monobank_api.log.
  • DTO Mismatches: If API responses change, extend DTOs:
    namespace App\DTO;
    
    use MonobankAcquiring\DTO\Invoice as BaseInvoice;
    
    class Invoice extends BaseInvoice {
        public function getNewField(): ?string {
            return $this->data['new_field'] ?? null;
        }
    }
    
    Override the service in config/services.yaml:
    MonobankAcquiring\Client\MonobankAcquiringClientInterface: '@app.monobank_acquiring.client'
    

Extension Points

  1. Custom HTTP Client: Replace the default client by binding an interface:

    # config/services.yaml
    MonobankAcquiring\Client\MonobankAcquiringClientInterface: '@app.custom_monobank_client'
    

    Example implementation:

    class CustomMonobankClient implements MonobankAcquiringClientInterface {
        public function createInvoice(float $amount, string $currency, string $description, string $orderId): Invoice {
            // Add logging, retry logic, etc.
            return $this->delegate->createInvoice($amount, $currency, $description, $orderId);
        }
    }
    
  2. Event Listeners: Dispatch events for critical actions (e.g., InvoiceCreatedEvent):

    $event = new InvoiceCreatedEvent($invoice);
    $dispatcher->dispatch($event);
    

    Register in config/services.yaml:

    services:
        App\EventListener\MonobankListener:
            tags:
                - { name: kernel.event_listener, event: invoice.created, method: onInvoiceCreated }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky