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

Mollie Api Php Laravel Package

mollie/mollie-api-php

Official Mollie API client for PHP. Create and manage payments, orders, customers, subscriptions, refunds, and settlements. Supports iDEAL, card, PayPal, Apple Pay, Google Pay, Bancontact, SEPA and more. Includes webhooks and OAuth support.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require mollie/mollie-api-php
  1. Initialize Client (in config/services.php or directly in code):
    $mollie = new \Mollie\Api\MollieApiClient();
    $mollie->setApiKey(env('MOLLIE_API_KEY')); // Use `test_` or `live_` prefix
    
  2. First Use Case: Create a payment in a Laravel controller:
    use Mollie\Api\Http\Data\Money;
    use Mollie\Api\Http\Requests\CreatePaymentRequest;
    
    $payment = $mollie->send(new CreatePaymentRequest(
        description: 'Order #123',
        amount: new Money('EUR', '29.99'),
        redirectUrl: route('mollie.redirect'),
        webhookUrl: route('mollie.webhook')
    ));
    

Key Starting Points

  • Documentation: Mollie Developer Portal (official)
  • Recipes: docs/recipes/ (pre-built workflows for payments, subscriptions, etc.)
  • Webhook Handling: docs/webhooks.md (critical for async operations)

Implementation Patterns

Core Workflows

1. Payment Processing

// Create a payment (sync)
$payment = $mollie->payments->create([
    'amount' => ['currency' => 'EUR', 'value' => '10.00'],
    'description' => 'Premium Subscription',
    'metadata' => ['user_id' => auth()->id()],
    'redirectUrl' => route('checkout.success'),
]);

// Capture a deferred payment (e.g., for credit cards)
$payment->capture();

// Refund a payment
$refund = $payment->refund(['amount' => ['currency' => 'EUR', 'value' => '5.00']]);

2. Webhook Integration

// Laravel Route (webhook endpoint)
Route::post('/mollie/webhook', function (Request $request) {
    $event = $request->json()->all();
    $mollie->webhooks->handle($event); // Auto-verifies signature
    // Handle specific events (e.g., payment.completed)
    if ($event['type'] === 'payment.completed') {
        orderConfirmed($event['data']['id']);
    }
});

3. Subscription Management

// Create a subscription
$subscription = $mollie->subscriptions->create([
    'amount' => ['currency' => 'EUR', 'value' => '9.99'],
    'interval' => 'month',
    'metadata' => ['customer_email' => 'user@example.com'],
]);

// Cancel a subscription
$subscription->cancel();

4. Customer Management

// Create/update a customer
$customer = $mollie->customers->create([
    'email' => 'user@example.com',
    'name' => 'John Doe',
]);

// Attach a payment to a customer
$payment->setCustomerId($customer->id);

Laravel-Specific Patterns

Service Provider Integration

// app/Providers/MollieServiceProvider.php
public function register()
{
    $this->app->singleton(\Mollie\Api\MollieApiClient::class, function ($app) {
        $mollie = new \Mollie\Api\MollieApiClient();
        $mollie->setApiKey(config('services.mollie.key'));
        return $mollie;
    });
}

Request Macros (for Reusability)

// app/Http/Controllers/MollieController.php
use Mollie\Api\Http\Requests\CreatePaymentRequest;

public function createPayment()
{
    $request = new CreatePaymentRequest(
        description: 'Order #' . $order->id,
        amount: new Money('EUR', $order->total),
        metadata: ['order_id' => $order->id],
        // ... other params
    );
    return $mollie->payments->create($request);
}

Event Listeners for Webhooks

// app/Listeners/HandleMollieWebhook.php
public function handle($event)
{
    $data = $event['data'];
    switch ($event['type']) {
        case 'payment.completed':
            Order::find($data['metadata']['order_id'])->markAsPaid();
            break;
        case 'subscription.cancelled':
            User::find($data['metadata']['user_id'])->cancelSubscription();
            break;
    }
}

Testing with Mocks

// tests/Feature/MolliePaymentTest.php
public function test_payment_creation()
{
    $mollie = Mockery::mock(\Mollie\Api\MollieApiClient::class);
    $mollie->shouldReceive('payments->create')
           ->once()
           ->andReturn(new Payment(['id' => 'tr_abc123']));

    $response = $this->post('/checkout', ['amount' => '10.00']);
    $response->assertRedirect('/order/confirmed');
}

Advanced Patterns

Idempotency Keys

// Ensure retries don’t duplicate payments
$payment = $mollie->payments->create([
    'amount' => ['currency' => 'EUR', 'value' => '10.00'],
    'idempotencyKey' => 'unique_order_123', // Must be unique per order
]);

Custom HTTP Adapters

// For custom logging/retries
$mollie->setHttpAdapter(new \Mollie\Api\Http\Adapters\GuzzleAdapter([
    'handler' => HandlerStack::create([
        new RetryMiddleware(),
        new LoggingMiddleware(),
    ]),
]));

Batch Operations

// Refund multiple payments
$refunds = $mollie->payments->refund([
    'payments' => ['tr_123', 'tr_456'],
    'amount' => ['currency' => 'EUR', 'value' => '5.00'],
]);

Gotchas and Tips

Common Pitfalls

  1. Webhook Signature Verification

    • Issue: Webhook payloads may fail verification if the X-Mollie-Signature header is missing or malformed.
    • Fix: Ensure your Laravel middleware validates signatures:
      $mollie->webhooks->validate($request->header('X-Mollie-Signature'), $request->getContent());
      
  2. Currency/Amount Formatting

    • Issue: Using strings like "10,00" (comma) instead of "10.00" (dot) for decimal amounts.
    • Fix: Always use dot notation (new Money('EUR', '10.00')).
  3. Redirect URLs

    • Issue: Forgetting to include redirectUrl in payment requests causes Mollie to redirect to a default page.
    • Fix: Always specify redirectUrl and webhookUrl:
      'redirectUrl' => route('mollie.redirect', ['payment_id' => $payment->id]),
      'webhookUrl' => route('mollie.webhook'),
      
  4. Idempotency Key Conflicts

    • Issue: Reusing the same idempotencyKey for different payments may silently fail.
    • Fix: Use unique keys (e.g., order_id + timestamp).
  5. Payment Method Restrictions

    • Issue: Some payment methods (e.g., ideal) require additional configuration in the Mollie dashboard.
    • Fix: Check Mollie’s payment method docs for prerequisites.
  6. Webhook Retries

    • Issue: Mollie retries failed webhook deliveries (default: 3 times). Ensure your endpoint is idempotent.
    • Fix: Use database transactions or deduplication logic:
      if (Webhook::where('event_id', $event['id'])->exists()) {
          return response()->json(['status' => 'ok']);
      }
      

Debugging Tips

  1. Enable Debug Logging

    $mollie->setDebugMode(true); // Logs requests/responses to storage/logs/mollie.log
    
  2. Inspect Raw Responses

    $response = $mollie->send($request);
    \Log::debug('Mollie Response:', $response->getData());
    
  3. Test Mode Quirks

    • Test payments expire after 1 hour (use test_123 cards for immediate success).
    • Test webhooks use a different signature key than live mode.
  4. Common HTTP Errors

    • 400 Bad Request: Validate all required fields (e.g., amount, description).
    • 401 Unauthorized: Check your
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor