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 PHP client for the Mollie Payments API. Easily create and manage payments, refunds, customers, subscriptions, and orders from your PHP app with a simple, well-documented wrapper around Mollie’s REST endpoints.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require mollie/mollie-api-php
    

    Add to composer.json if using a monorepo or strict versioning:

    "require": {
        "mollie/mollie-api-php": "^8.0"
    }
    
  2. First API Call Initialize the client in a service or config file:

    use Mollie\Api\MollieApiClient;
    
    $mollie = new MollieApiClient();
    $mollie->setApiKey('test_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
    
  3. First Use Case: Create a Payment

    $payment = $mollie->payments()->create([
        'amount' => [
            'currency' => 'EUR',
            'value' => '10.00',
        ],
        'description' => 'Order #12345',
        'method' => 'ideal',
        'metadata' => ['order_id' => '12345'],
    ]);
    

Where to Look First

  • Official Documentation (Mollie’s PHP SDK docs are minimal; refer to their API reference).
  • src/Mollie/Api/ – Core classes for payments, customers, refunds, etc.
  • tests/ – Real-world usage examples (e.g., PaymentTest.php).
  • examples/ (if included) – Quick-start snippets.

Implementation Patterns

Workflows

1. Payment Processing

  • Create → Redirect → Confirm
    // 1. Create payment (returns `Payment` object with `links` for redirect)
    $payment = $mollie->payments()->create([...]);
    
    // 2. Redirect user to `$payment->getCheckoutUrl()`
    return redirect($payment->getCheckoutUrl());
    
    // 3. Webhook handler (POST `/webhook`)
    $event = $mollie->payments()->webhook($request->getContent());
    if ($event->isPaid()) {
        // Fulfill order
    }
    
  • Store payment ID in your DB to avoid duplicate processing.

2. Subscription Management

$subscription = $mollie->subscriptions()->create([
    'amount' => ['currency' => 'EUR', 'value' => '9.99'],
    'interval' => 'month',
    'metadata' => ['user_id' => 123],
    'customerId' => $customerId,
]);

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

3. Refunds

$refund = $mollie->payments()->createRefund($paymentId, [
    'amount' => ['currency' => 'EUR', 'value' => '5.00'],
    'description' => 'Partial refund',
]);

Integration Tips

  • Laravel Service Provider Bind the client to the container for dependency injection:

    $this->app->singleton(MollieApiClient::class, function ($app) {
        $mollie = new MollieApiClient();
        $mollie->setApiKey(config('services.mollie.key'));
        return $mollie;
    });
    
  • Webhook Validation Use Mollie’s webhook signature verification:

    use Mollie\Api\Exceptions\ApiException;
    
    try {
        $event = $mollie->payments()->webhook($request->getContent());
        $event->validateWebhook($request->header('X-Mollie-Webhook-Signature'));
    } catch (ApiException $e) {
        abort(403, 'Invalid webhook signature');
    }
    
  • Retry Logic Wrap API calls in a retry helper for transient failures:

    use Mollie\Api\Exceptions\ApiException;
    
    function withRetry(callable $callback, int $retries = 3) {
        $attempt = 0;
        while ($attempt < $retries) {
            try {
                return $callback();
            } catch (ApiException $e) {
                if ($attempt === $retries - 1) throw $e;
                sleep(2 ** $attempt); // Exponential backoff
                $attempt++;
            }
        }
    }
    
  • Testing Use Mollie’s test mode (test_ API keys) with sandbox endpoints:

    $mollie->setApiKey('test_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
    $mollie->setBaseUrl('https://api.mollie.sandbox.eu'); // For sandbox
    

Gotchas and Tips

Pitfalls

  1. Webhook Idempotency

    • Mollie may retry webhooks. Always use idempotent logic (e.g., check if the payment/order exists before processing).
    • Store id and mode (live/test) in your DB to deduplicate.
  2. Rate Limits

    • Mollie’s API has rate limits. Cache responses for non-idempotent endpoints (e.g., GET /payments/{id}).
  3. Currency/Amount Precision

    • Amounts must be strings (e.g., '10.00'), not floats/integers. Mollie rejects 10 or 10.0.
    • Use number_format() or bcdiv() to avoid floating-point errors:
      $amount = number_format($price, 2, '.', '');
      
  4. Webhook Timeouts

    • Webhook handlers must respond within 10 seconds. Use queue jobs for heavy processing:
      // Webhook handler
      ProcessPaymentJob::dispatch($event->getId(), $event->getMode());
      return response()->json(['status' => 'queued']);
      
  5. Customer ID vs. Email

    • customerId is not the same as the customer’s email. Create a customer first:
      $customer = $mollie->customers()->create([
          'email' => 'user@example.com',
          'name' => 'John Doe',
      ]);
      $subscription = $mollie->subscriptions()->create([
          'customerId' => $customer->getId(), // Use this, not email!
          // ...
      ]);
      

Debugging

  • Enable Verbose Logging
    $mollie->setDebugMode(true); // Logs requests/responses to `storage/logs/mollie.log`
    
  • Inspect Raw Responses Use getLastResponse() to debug failed requests:
    try {
        $payment = $mollie->payments()->get($id);
    } catch (ApiException $e) {
        $response = $mollie->getLastResponse();
        Log::error('Mollie API Error', [
            'status' => $response->getStatusCode(),
            'body' => $response->getBody(),
        ]);
    }
    

Extension Points

  1. Custom API Endpoints Extend MollieApiClient to add non-standard endpoints:

    class CustomMollieClient extends MollieApiClient {
        public function customEndpoint() {
            return $this->sendApiRequest('GET', '/custom-endpoint', [], 'v2');
        }
    }
    
  2. Middleware for Requests Add headers or modify requests globally:

    $mollie->getClient()->getRequestOptions()['headers']['X-Custom-Header'] = 'value';
    
  3. Mocking for Tests Use Mollie\Api\Services\MockService to simulate API responses:

    $mockService = new MockService();
    $mockService->setResponse('payments/create', ['id' => 'tr_abc123']);
    $mollie->setService($mockService);
    
  4. Async Processing Offload heavy operations (e.g., refunds) to queues:

    RefundJob::dispatch($paymentId, $amount);
    

Config Quirks

  • Base URL Defaults to EU (api.mollie.eu). Override for US:
    $mollie->setBaseUrl('https://api.mollie.com');
    
  • Language/Locale Set default language for error messages:
    $mollie->setLanguage('nl_NL'); // Dutch
    
  • Timeouts Adjust HTTP client timeouts (default: 30s):
    $mollie->getClient()->setConfig(['timeout' => 60]);
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport