Mollie API client for PHP

repository·main·Indexed 20 days ago

https://github.com/mollie/mollie-api-php

A PHP library for integrating Mollie's payment services, supporting methods such as iDEAL, Apple Pay, Google Pay, and Credit Cards. The client provides tools for managing payments, customers, mandates, subscriptions, chargebacks, refunds, and webhooks. It supports both associative arrays and typed Data objects for API requests, includes built-in debugging and sanitization features, and requires PHP >= 7.4 and cURL >= 7.19.4.

Tokens
75.6K
Snippets
196
Records
233
Agent score
70%

What's inside mollie-api-php

  1. Explore Mollie API PHP Recipes by resource type

    main

    The recipes directory provides practical, complete code examples for common use cases organized by resource. Use these to implement specific workflows for payments, customers, or webhooks. The available resource categories are:

    • Payments: Create, update, and manage payments.
    • Customers: Customer management operations.
    • Mandates: Mandate-related operations.
    • Subscriptions: Handling recurring subscriptions.
    • Captures: Payment capture operations.
    • Chargebacks: Handling chargeback events.
    • Refunds: Processing refunds.
    • Connect Balance Transfers: Managing balance transfers via Connect.
    • Webhooks: Managing and handling webhook events.
  2. Security and sanitization in debug mode

    main

    The Mollie API client includes built-in security features to prevent accidental exposure of sensitive information during debugging:

    • Automatic Sanitization: The client automatically removes sensitive headers (such as Authorization and User-Agent) and sanitizes request data to prevent credential exposure.
    • Safe Exception Handling: When an ApiException is thrown, the debug information included in the exception is automatically sanitized.
    • Execution Control: You can use the die: true parameter in debug methods to halt execution immediately after the debug output is rendered, which is useful for inspecting state in development.
  3. How customer payment sequences work

    main

    Mollie uses a sequence system to manage recurring billing via mandates:

    • SequenceType::FIRST: This is used for the initial transaction. It creates a mandate for the customer, allowing you to charge them again in the future without their direct intervention. This requires a redirectUrl for customer authorization.
    • SequenceType::RECURRING: This is used for subsequent transactions. It utilizes the existing mandate created by the 'first' payment. These payments are processed automatically and do not require a redirectUrl.

    Important Considerations:

    • A customer must be created before you can create customer payments.
    • The ability to create recurring payments depends on the status of the mandate.
    • Not all payment methods support recurring payments.
    • Always implement webhook handling to track status changes reliably.
  4. How HTTP Adapters work in the Mollie API client

    main

    HTTP adapters abstract the communication between your application and the API. They allow you to swap different HTTP clients (like Guzzle, cURL, or PSR-18 compliant clients) without changing your core API interaction logic.

    The MollieHttpAdapterPicker manages this selection process:

    • Default Behavior: If you do not provide a client to the MollieApiClient constructor, the picker checks for Guzzle. If Guzzle is available, it uses a Guzzle adapter; otherwise, it defaults to a cURL adapter.
    • Custom Clients: If you provide a client that implements HttpAdapterContract, it is used directly. If you provide a Guzzle client, it is automatically wrapped in a GuzzleMollieHttpAdapter.
    • Errors: If the provided client is not recognized, an UnrecognizedClientException is thrown.
  5. Inspect webhook provenance and metadata

    main

    Resources hydrated from a webhook via $event->asResource($mollie) carry a WebhookSnapshotOrigin instead of a standard HTTP Response. This allows you to inspect event metadata without making additional API calls.

    Key methods on the origin object:

    • getEventId(): Returns the event ID (e.g., event_...).
    • getSignature(): Returns the X-Mollie-Signature header value.
    • getReceivedAt(): Returns a DateTimeImmutable of when the webhook was received.
    • getResponse(): Returns null for webhook-origin resources (unlike API-fetched resources).
    $resource = $event->asResource($mollie);
    
    $resource->getResponse();                 // null
    $resource->getOrigin();                   // WebhookSnapshotOrigin
    $resource->getOrigin()->getEventId();     // 'event_GvJ8WHrp5isUdRub9CJyH'
    $resource->getOrigin()->getSignature();   // the X-Mollie-Signature header
    $resource->getOrigin()->getReceivedAt();  // DateTimeImmutable
  6. Identify when retries are triggered

    main

    Retries are not performed for all errors. They only occur when the HTTP layer encounters an error that is considered retryable and wraps it in a Mollie\Api\Exceptions\RetryableNetworkRequestException.

    Other exceptions (such as client errors or logic errors) will be thrown immediately without any retry attempts.

  7. Best practices for processing Webhook Events

    main

    When implementing webhook handling, follow these guidelines:

    • Idempotency: Webhook events are not guaranteed to be delivered in order and may be delivered multiple times. Use the createdAt timestamp to determine order and ensure your processing logic is idempotent.
    • Security: Always verify webhook signatures to ensure authenticity. Treat webhook events as notifications, but use the primary API as the source of truth for critical state changes.
    • Data Access: Always use hasEntity() before calling getEntity() to avoid errors, as entity data may be null for certain event types.
    • Identification: Use the id to track specific events and entityId to identify which object the event belongs to.
  8. Use Resource Wrappers to hydrate custom classes

    main

    If you want to map API responses directly to your own domain objects or a specific subset of properties, you can use Resource Wrappers. A wrapper class extends ResourceWrapper and allows you to transform raw API data into dedicated objects using Utility::transform().

    Defining a Wrapper

    To create a wrapper, implement a fromResource static method. This method should take the API resource, transform the necessary fields, and call setWrapped($resource) to maintain access to the underlying API resource.

    Using a Wrapper

    To use your custom wrapper, you must tell the Request object to hydrate into your wrapper instead of the default resource by using setHydratableResource() with a WrapperResource instance.

    // 1. Define the wrapper
    use Mollie\[Api\\Utils\\Utility;
    use Mollie\[Api\\Resources\\Payment;
    use Mollie\[Api\\Resources\\ResourceWrapper;
    
    class PaymentWrapper extends ResourceWrapper
    {
        public function __construct(
            public Money $amount,
            public Timestamp $createdAt,
        ) {}
    
        public static function fromResource($resource): self
        {
            /** @var Payment $resource */
            return (new self(
                amount: Utility::transform($resource->amount, fn (stdClass $amount) => Money::fromMollieObject($amount)),
                createdAt: Utility::transform($resource->createdAt, fn (string $timestamp) => Timestamp::fromIsoString($timestamp))
            ))->setWrapped($resource);
        }
    }
    
    // 2. Use the wrapper in a request
    use Mollie\[Api\\Resources\\WrapperResource;
    
    $request = new GetPaymentRequest('tr_*********');
    $request->setHydratableResource(new WrapperResource(PaymentWrapper::class));
    
    /** @var PaymentWrapper $paymentWrapper */
    $paymentWrapper = $mollie->send($request);
    
    // 3. Access properties or methods
    echo $paymentWrapper->status; // property
    echo $paymentWrapper->status(); // method
  9. Understand default retry behavior

    main

    The Mollie PHP client automatically retries requests that fail due to retryable network errors. By default, it uses the Mollie\Api\Http\Retry\LinearRetryStrategy.

    Default settings:

    • Max retries: 5 (performed after the initial attempt).
    • Delay pattern: Linear backoff starting at 1000ms and increasing by 1000ms per attempt (e.g., 1000ms, 2000ms, 3000ms, etc.).

    If all retry attempts are exhausted, the client throws a Mollie\Api\Exceptions\RetryableNetworkRequestException.

  10. Paginate API Results

    main

    Most list methods in the Mollie API support pagination. You can retrieve the first page using page(), or specify a starting point and limit using page(from: 'ID', limit: 50). For iterating through all items across all pages, use the iterator() method.

    // Get first page
    $payments = $mollie->payments->page();
    
    // Get specific page
    $payments = $mollie->payments->page(
        from: 'tr_7UhSN1zuXS',  // Start from this ID
        limit: 50               // Items per page
    );
    
    // Get all items using iterator
    foreach ($mollie->payments->iterator() as $payment) {
        echo $payment->id;
    }
  11. Important considerations for Payment Captures

    main

    When working with captures in the Mollie API, keep the following rules in mind:

    • Capture Mode: You can only retrieve captures for payments that were created with captureMode: 'manual'.
    • Multiple Captures: A single payment can have multiple captures if partial captures were utilized.
    • Pagination: The list of captures is paginated. When using the standard request (without an iterator), use next() to retrieve the next page of results.
    • Payment Status: A payment's status will only transition to paid once all associated captures have reached a succeeded status.
    • Webhooks: It is highly recommended to implement webhook handling to process asynchronous updates to capture statuses.