Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Mollie API PHP Client
https://github.com/mollie/mollie-api-php
Admin
A PHP client library for the Mollie payment API, enabling developers to accept international and
...
Tokens:
61,518
Snippets:
485
Trust Score:
9.9
Update:
1 week ago
Context
Skills
Chat
Benchmark
88.5
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Mollie API PHP Client The Mollie API PHP Client is the official PHP library for integrating with Mollie's payment services. It enables developers to accept a wide range of international and local payment methods including iDEAL, Apple Pay, Google Pay, credit cards, PayPal, Bancontact, SOFORT Banking, SEPA Direct Debit, Klarna, and many more. The library provides a clean, type-safe interface for creating payments, managing customers, handling subscriptions, processing refunds, and implementing webhooks. Built on modern PHP practices (PHP 7.4+), the client offers two approaches: endpoint collections for familiar patterns and request classes for more explicit, type-safe operations. It includes comprehensive testing utilities with mock responses, debugging capabilities, automatic retry logic, and idempotency support. The library handles authentication via API keys or OAuth access tokens, making it suitable for both simple integrations and complex marketplace platforms using Mollie Connect. ## Installation Install the library via Composer. ```bash composer require mollie/mollie-api-php ``` ## Client Initialization Initialize the Mollie API client with your API key or OAuth access token. The `setToken` method automatically detects whether you're using an API key (`test_`/`live_`) or an OAuth access token (`access_`). You can also use `setApiKey()` or `setAccessToken()` directly. ```php use Mollie\Api\MollieApiClient; // Initialize with API key $mollie = new MollieApiClient(); $mollie->setToken("test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM"); // Or use explicit methods $mollie->setApiKey("test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM"); // For OAuth access tokens (required for certain endpoints) $mollie->setAccessToken("access_xxx"); // Enable test mode globally $mollie->test(true); ``` ## Create a Payment Create a payment and redirect the customer to complete the checkout process. The `CreatePaymentRequest` class provides a type-safe way to create payments with all required and optional parameters. The response includes a checkout URL where you should redirect your customer. ```php use Mollie\Api\Http\Data\Money; use Mollie\Api\Http\Requests\CreatePaymentRequest; $orderId = 12345; $payment = $mollie->send( new CreatePaymentRequest( description: "Order #{$orderId}", amount: Money::euro('10.00'), redirectUrl: 'https://example.org/return', cancelUrl: 'https://example.org/cancel', webhookUrl: 'https://example.org/webhook', metadata: ['order_id' => $orderId] ) ); // Redirect customer to complete payment $checkoutUrl = $payment->getCheckoutUrl(); header("Location: {$checkoutUrl}", true, 303); // Payment properties echo $payment->id; // "tr_7UhSN1zuXS" echo $payment->status; // "open" echo $payment->amount->value; // "10.00" echo $payment->amount->currency; // "EUR" ``` ## Create an iDEAL Payment Create a payment specifically using the iDEAL payment method popular in the Netherlands. Specify the payment method to pre-select it for the customer. The iDEAL method is commonly used for Dutch bank transfers. ```php use Mollie\Api\Http\Data\Money; use Mollie\Api\Http\Requests\CreatePaymentRequest; use Mollie\Api\Types\PaymentMethod; $payment = $mollie->send( new CreatePaymentRequest( description: "Order #{$orderId}", amount: Money::euro('27.50'), redirectUrl: "https://example.com/return.php", webhookUrl: "https://example.com/webhook.php", method: PaymentMethod::IDEAL ) ); header("Location: " . $payment->getCheckoutUrl(), true, 303); ``` ## Create a Capturable Payment (Manual Capture) Create a payment with manual capture mode for credit card payments where you want to authorize first and capture later. Manual capture is useful for scenarios where you want to verify the order before capturing the funds, such as checking inventory availability. ```php use Mollie\Api\Http\Data\Money; use Mollie\Api\Http\Requests\CreatePaymentRequest; use Mollie\Api\Http\Requests\CreatePaymentCaptureRequest; use Mollie\Api\Types\PaymentMethod; // Create payment with manual capture $payment = $mollie->send( new CreatePaymentRequest( description: "Order #{$orderId}", amount: Money::euro('100.00'), redirectUrl: "https://example.com/return.php", webhookUrl: "https://example.com/webhook.php", method: PaymentMethod::CREDITCARD, captureMode: 'manual' ) ); // Later, capture the authorized payment (full or partial amount) $capture = $mollie->send( new CreatePaymentCaptureRequest( paymentId: $payment->id, description: 'Captured for Order #12345', amount: Money::euro('50.00') // Partial capture ) ); echo $capture->id; // "cpt_4qqhO89gsT" echo $capture->status; // "succeeded" ``` ## Create a Routed Payment (Split Payments) Create a payment that splits funds between multiple connected organizations in a marketplace scenario. Routed payments are used in marketplace applications where you need to distribute funds between the platform and merchants. ```php use Mollie\Api\Http\Data\Money; use Mollie\Api\Http\Data\Route; use Mollie\Api\Http\Requests\CreatePaymentRequest; $payment = $mollie->send( new CreatePaymentRequest( profileId: 'pfl_v9hTwCvYqw', description: "Marketplace Order #{$orderId}", amount: new Money(currency: 'EUR', value: '100.00'), redirectUrl: 'https://example.com/return.php', webhookUrl: 'https://example.com/webhook.php', routing: [ new Route( amount: new Money(currency: 'EUR', value: '75.00'), destination: [ 'type' => 'organization', 'organizationId' => 'org_merchant123' ], releaseDate: '2025-01-15' // Optional: delay fund release ) ] ) ); // Platform keeps EUR 25.00, merchant receives EUR 75.00 ``` ## Retrieve and Check Payment Status Retrieve a payment and check its status using helper methods. The payment resource provides convenient methods to check the payment status without comparing strings directly. ```php use Mollie\Api\Http\Requests\GetPaymentRequest; $payment = $mollie->send(new GetPaymentRequest(id: 'tr_7UhSN1zuXS')); // Or using endpoint collection $payment = $mollie->payments->get('tr_7UhSN1zuXS'); // Check payment status if ($payment->isPaid()) { echo "Payment completed successfully!"; } elseif ($payment->isOpen()) { echo "Payment is still pending"; } elseif ($payment->isFailed()) { echo "Payment failed"; } elseif ($payment->isExpired()) { echo "Payment expired"; } elseif ($payment->isCanceled()) { echo "Payment was canceled"; } // Check for refunds and chargebacks if ($payment->hasRefunds()) { echo "Payment has been (partially) refunded"; } if ($payment->hasChargebacks()) { echo "Payment has chargebacks"; } // Access metadata $orderId = $payment->metadata->order_id; ``` ## Update a Payment Update an existing payment's description, redirect URL, or metadata. Payments can only be updated while they are still open and not yet paid. ```php use Mollie\Api\Http\Requests\UpdatePaymentRequest; $payment = $mollie->send( new UpdatePaymentRequest( id: 'tr_7UhSN1zuXS', description: "Updated Order #{$newOrderId}", redirectUrl: 'https://example.com/return.php?order_id=' . $newOrderId, metadata: ['order_id' => $newOrderId, 'updated' => true] ) ); ``` ## Refund a Payment Create a full or partial refund for a completed payment. You can check if a payment can be refunded before attempting the refund operation. ```php use Mollie\Api\Http\Data\Money; use Mollie\Api\Http\Requests\CreatePaymentRefundRequest; use Mollie\Api\Http\Requests\GetPaymentRequest; $payment = $mollie->send(new GetPaymentRequest(id: 'tr_7UhSN1zuXS')); if ($payment->canBeRefunded()) { // Partial refund $refund = $mollie->send( new CreatePaymentRefundRequest( paymentId: $payment->id, amount: Money::euro('5.00'), description: 'Product return - Order #12345' ) ); echo "Refund {$refund->id} created"; echo "Status: {$refund->status}"; // "pending", "processing", "refunded" } // Full refund (omit amount to refund entire payment) $fullRefund = $mollie->send( new CreatePaymentRefundRequest( paymentId: $payment->id, description: 'Full refund requested by customer' ) ); ``` ## List Payments with Pagination Retrieve a paginated list of payments with optional filters. The response supports iteration and provides methods to navigate between pages. ```php use Mollie\Api\Http\Requests\GetPaginatedPaymentsRequest; // Get payments with pagination $payments = $mollie->send(new GetPaginatedPaymentsRequest(limit: 50)); foreach ($payments as $payment) { echo "Payment {$payment->id}: {$payment->status}\n"; echo "Amount: {$payment->amount->currency} {$payment->amount->value}\n"; } // Navigate to next page if ($payments->hasNext()) { $nextPayments = $payments->next(); } // Use iterator for all payments (auto-pagination) foreach ($mollie->payments->iterator() as $payment) { echo $payment->id . "\n"; } ``` ## List Payment Methods Retrieve available payment methods for your account or a specific payment amount. You can filter methods by amount, locale, and other parameters to show only relevant options. ```php // Get all enabled payment methods $methods = $mollie->methods->allEnabled(); foreach ($methods as $method) { echo "{$method->id}: {$method->description}\n"; echo "Min: {$method->minimumAmount->value} {$method->minimumAmount->currency}\n"; echo "Max: {$method->maximumAmount->value} {$method->maximumAmount->currency}\n"; } // Get methods available for a specific amount $methods = $mollie->methods->allEnabled([ 'amount' => ['currency' => 'EUR', 'value' => '100.00'], 'locale' => 'nl_NL' ]); // Get all methods (including inactive) $allMethods = $mollie->methods->all(); ``` ## Manage Customers Create, update, and delete customers for storing payment details and enabling recurring payments. Customers are required for recurring payments and subscriptions. ```php use Mollie\Api\Http\Requests\CreateCustomerRequest; use Mollie\Api\Http\Requests\UpdateCustomerRequest; use Mollie\Api\Http\Requests\DeleteCustomerRequest; use Mollie\Api\Http\Requests\GetPaginatedCustomersRequest; // Create a customer $customer = $mollie->send( new CreateCustomerRequest( name: 'John Doe', email: 'john@example.com', locale: 'en_US', metadata: ['userId' => 12345] ) ); echo "Customer created: {$customer->id}"; // "cst_8wmqcHMN4U" // Update a customer $customer = $mollie->send( new UpdateCustomerRequest( id: 'cst_8wmqcHMN4U', name: 'John Smith', email: 'john.smith@example.com' ) ); // List all customers $customers = $mollie->send(new GetPaginatedCustomersRequest()); foreach ($customers as $customer) { echo "{$customer->name} ({$customer->email})\n"; } // Delete a customer $mollie->send(new DeleteCustomerRequest(id: 'cst_8wmqcHMN4U')); ``` ## Create Customer Payment (First Payment for Recurring) Create the first payment for a customer to set up recurring payments. The first payment with `sequenceType: FIRST` creates a mandate that can be used for future recurring payments. ```php use Mollie\Api\Http\Data\Money; use Mollie\Api\Http\Requests\CreateCustomerPaymentRequest; use Mollie\Api\Types\SequenceType; // First payment - creates a mandate $payment = $mollie->send( new CreateCustomerPaymentRequest( customerId: 'cst_8wmqcHMN4U', description: 'First payment - Order #12345', amount: Money::euro('29.95'), redirectUrl: 'https://example.com/return', webhookUrl: 'https://example.com/webhook', sequenceType: SequenceType::FIRST ) ); // Redirect customer to complete first payment header("Location: " . $payment->getCheckoutUrl(), true, 303); // After first payment is completed, create recurring payments $recurringPayment = $mollie->send( new CreateCustomerPaymentRequest( customerId: 'cst_8wmqcHMN4U', description: 'Monthly subscription payment', amount: Money::euro('29.95'), webhookUrl: 'https://example.com/webhook', sequenceType: SequenceType::RECURRING // No redirect needed ) ); ``` ## Manage Mandates Create and manage mandates for SEPA Direct Debit recurring payments. Mandates authorize you to collect payments from a customer's bank account. ```php use Mollie\Api\Http\Requests\CreateMandateRequest; use Mollie\Api\Http\Requests\GetPaginatedMandateRequest; use Mollie\Api\Http\Requests\RevokeMandateRequest; use Mollie\Api\Types\MandateMethod; // Create a SEPA Direct Debit mandate $mandate = $mollie->send( new CreateMandateRequest( customerId: 'cst_8wmqcHMN4U', method: MandateMethod::DIRECTDEBIT, consumerName: 'John Doe', consumerAccount: 'NL34ABNA0243341423', consumerBic: 'ABNANL2A', // Optional signatureDate: '2024-01-15', mandateReference: 'MANDATE-12345' // Optional ) ); echo "Mandate created: {$mandate->id}"; // "mdt_h3gAaD5zP" echo "Status: {$mandate->status}"; // "valid", "pending", "invalid" // List all mandates for a customer $mandates = $mollie->send( new GetPaginatedMandateRequest(customerId: 'cst_8wmqcHMN4U') ); foreach ($mandates as $mandate) { echo "{$mandate->id}: {$mandate->method} - {$mandate->status}\n"; } // Revoke a mandate $mollie->send( new RevokeMandateRequest( customerId: 'cst_8wmqcHMN4U', mandateId: 'mdt_h3gAaD5zP' ) ); ``` ## Manage Subscriptions Create and manage recurring subscriptions for customers. Subscriptions automatically create payments at specified intervals using the customer's mandate. ```php use Mollie\Api\Http\Requests\CreateSubscriptionRequest; use Mollie\Api\Http\Requests\GetPaginatedSubscriptionsRequest; use Mollie\Api\Http\Requests\CancelSubscriptionRequest; // Create a monthly subscription $subscription = $mollie->send( new CreateSubscriptionRequest( customerId: 'cst_8wmqcHMN4U', parameters: [ 'amount' => ['value' => '25.00', 'currency' => 'EUR'], 'interval' => '1 month', 'description' => 'Monthly Pro Subscription', 'webhookUrl' => 'https://example.com/webhook', 'startDate' => '2024-02-01', 'times' => 12 // Optional: limit to 12 payments ] ) ); echo "Subscription created: {$subscription->id}"; echo "Status: {$subscription->status}"; // "active" echo "Next payment: {$subscription->nextPaymentDate}"; // List subscriptions $subscriptions = $mollie->send( new GetPaginatedSubscriptionsRequest(customerId: 'cst_8wmqcHMN4U') ); foreach ($subscriptions as $sub) { echo "{$sub->description}: {$sub->status}\n"; } // Cancel a subscription $mollie->send( new CancelSubscriptionRequest( customerId: 'cst_8wmqcHMN4U', subscriptionId: 'sub_rVKGtNd6s3' ) ); ``` ## Webhook Handler Handle webhook notifications from Mollie to update payment status in your system. Mollie sends POST requests to your webhook URL when payment status changes. Always return HTTP 200 to acknowledge receipt. ```php use Mollie\Api\Http\Requests\GetPaymentRequest; // Webhook endpoint (e.g., https://example.com/webhook.php) $paymentId = $_POST['id'] ?? null; if (!$paymentId) { http_response_code(400); exit('Missing payment ID'); } try { $payment = $mollie->send(new GetPaymentRequest(id: $paymentId)); $orderId = $payment->metadata->order_id; if ($payment->isPaid() && !$payment->hasRefunds() && !$payment->hasChargebacks()) { // Payment successful - fulfill the order fulfillOrder($orderId); } elseif ($payment->isOpen()) { // Payment still pending markOrderAsPending($orderId); } elseif ($payment->isFailed()) { // Payment failed markOrderAsFailed($orderId); } elseif ($payment->isExpired()) { // Payment expired cancelOrder($orderId); } elseif ($payment->isCanceled()) { // Customer canceled the payment cancelOrder($orderId); } if ($payment->hasRefunds()) { handleRefund($orderId, $payment); } if ($payment->hasChargebacks()) { handleChargeback($orderId, $payment); } } catch (\Mollie\Api\Exceptions\ApiException $e) { // Log the error but return 200 to prevent retries error_log("Webhook error: " . $e->getMessage()); } // Always return 200 OK http_response_code(200); ``` ## Webhook Signature Verification Verify webhook signatures to ensure requests are genuinely from Mollie. Signature verification prevents attackers from sending fake webhook requests to your endpoint. ```php use Mollie\Api\Webhooks\SignatureValidator; use Mollie\Api\Exceptions\InvalidSignatureException; $signingSecret = 'whsec_your_signing_secret'; $validator = new SignatureValidator($signingSecret); // Get the raw request body and signature header $requestBody = file_get_contents('php://input'); $signature = $_SERVER['HTTP_MOLLIE_SIGNATURE'] ?? ''; try { $isValid = $validator->validatePayload($requestBody, $signature); // Process the webhook... $payment = $mollie->payments->get($_POST['id']); } catch (InvalidSignatureException $e) { http_response_code(401); exit('Invalid webhook signature'); } // For PSR-7 compatible requests $isValid = $validator->validateRequest($psr7Request); // Support key rotation with multiple secrets $validator = new SignatureValidator(['current_secret', 'previous_secret']); ``` ## Webhook Event Mapping Map incoming webhook payloads to strongly-typed event objects. The WebhookEventMapper converts raw webhook data into specific event classes for type-safe handling. ```php use Mollie\Api\Webhooks\WebhookEventMapper; use Mollie\Api\Webhooks\Events\PaymentLinkPaid; use Mollie\Api\Webhooks\Events\BalanceTransactionCreated; $mapper = new WebhookEventMapper(); $event = $mapper->processPayload($_POST); // Access event data $entityId = $event->entityData('id'); $resource = $event->entity()->asResource($mollie); // Handle different event types match (true) { $event instanceof PaymentLinkPaid => handlePaymentLinkPaid($event), $event instanceof BalanceTransactionCreated => handleBalanceTransaction($event), default => logUnhandledEvent($event) }; ``` ## Create and Manage Webhooks Create webhooks programmatically to receive notifications for specific events. Webhooks can be configured to receive notifications for payment links, balance transfers, and other events. ```php use Mollie\Api\Http\Requests\CreateWebhookRequest; use Mollie\Api\Types\WebhookEventType; // Create a webhook $webhook = $mollie->send( new CreateWebhookRequest( url: 'https://example.com/mollie-webhook', name: 'Payment Link Notifications', eventTypes: WebhookEventType::PAYMENT_LINK_PAID ) ); echo "Webhook created: {$webhook->id}"; echo "Signing secret: {$webhook->signingSecret}"; // Store this securely! // List all webhooks $webhooks = $mollie->webhooks->page(); foreach ($webhooks as $wh) { echo "{$wh->name}: {$wh->url}\n"; } // Get a specific webhook $webhook = $mollie->webhooks->get('wh_4KgGJJSZpH'); // Update webhook URL $webhook->update(['url' => 'https://new-url.com/webhook']); // Test webhook (sends a test event) $webhook->test(); // Delete webhook $webhook->delete(); ``` ## Create Payment Links Create shareable payment links that can be sent via email, chat, or QR code. Payment links are useful when you don't have a checkout flow and need to request payment from customers. ```php use Mollie\Api\Http\Requests\CreatePaymentLinkRequest; use Mollie\Api\Http\Requests\GetPaginatedPaymentLinksRequest; // Create a payment link $paymentLink = $mollie->send( new CreatePaymentLinkRequest([ 'amount' => ['currency' => 'EUR', 'value' => '25.00'], 'description' => 'Invoice #12345', 'expiresAt' => '2025-12-31T23:59:59+00:00', 'webhookUrl' => 'https://example.com/webhook' ]) ); // Share this URL with your customer $shareableUrl = $paymentLink->getCheckoutUrl(); echo "Payment link: {$shareableUrl}"; // Payment link properties echo $paymentLink->id; // "pl_4Y0eZitmBnQ6IDoMqZQKh" echo $paymentLink->status; // "open", "paid", "expired" // List all payment links $links = $mollie->send(new GetPaginatedPaymentLinksRequest()); foreach ($links as $link) { echo "{$link->description}: {$link->status}\n"; } ``` ## Manage Profiles Create and manage website profiles for different businesses or websites. Profiles represent your business or website and are required for OAuth-based integrations. ```php use Mollie\Api\Http\Requests\CreateProfileRequest; use Mollie\Api\Http\Requests\UpdateProfileRequest; use Mollie\Api\Http\Requests\GetPaginatedProfilesRequest; use Mollie\Api\Http\Requests\DeleteProfileRequest; // Create a profile (requires OAuth) $profile = $mollie->send( new CreateProfileRequest([ 'name' => 'My Online Store', 'website' => 'https://www.mystore.com', 'email' => 'support@mystore.com', 'phone' => '+31208202070', 'businessCategory' => 'RETAIL', 'mode' => 'live' ]) ); echo "Profile created: {$profile->id}"; // "pfl_v9hTwCvYqw" echo "Status: {$profile->status}"; // "verified", "unverified" // Update a profile $profile = $mollie->send( new UpdateProfileRequest( id: 'pfl_v9hTwCvYqw', name: 'Updated Store Name', website: 'https://www.updatedstore.com', email: 'new-support@store.com' ) ); // List all profiles $profiles = $mollie->send(new GetPaginatedProfilesRequest()); foreach ($profiles as $profile) { echo "{$profile->name}: {$profile->mode}\n"; } // Delete a profile $mollie->send(new DeleteProfileRequest(profileId: 'pfl_v9hTwCvYqw')); ``` ## Balance and Settlements Retrieve balance information and settlement reports. Settlements show how payments are grouped and paid out to your bank account. ```php use Mollie\Api\Http\Requests\GetPaginatedSettlementsRequest; // List settlements (requires OAuth) $settlements = $mollie->send(new GetPaginatedSettlementsRequest()); foreach ($settlements as $settlement) { echo "Settlement {$settlement->reference}:\n"; echo "Status: {$settlement->status}\n"; // "open", "pending", "paidout" echo "Amount: {$settlement->amount->currency} {$settlement->amount->value}\n"; echo "Settled: {$settlement->settledAt}\n"; // Settlement periods contain revenue and costs breakdown foreach ($settlement->periods as $year => $months) { foreach ($months as $month => $data) { echo "\nPeriod {$year}-{$month}:\n"; foreach ($data->revenue as $revenue) { echo "Revenue: {$revenue->description}\n"; echo " Count: {$revenue->count}\n"; echo " Net: {$revenue->amountNet->value}\n"; } foreach ($data->costs as $cost) { echo "Cost: {$cost->description}\n"; echo " Amount: {$cost->amountGross->value}\n"; } } } } ``` ## Connect Balance Transfers Transfer funds between connected organization balances in a marketplace platform. Balance transfers are used in Mollie Connect to move funds between the platform and connected merchants. ```php use Mollie\Api\Http\Data\Money; use Mollie\Api\Http\Data\TransferParty; use Mollie\Api\Http\Requests\CreateConnectBalanceTransferRequest; use Mollie\Api\Types\ConnectBalanceTransferCategory; // Create a balance transfer (requires OAuth) $transfer = $mollie->send( new CreateConnectBalanceTransferRequest( amount: new Money(currency: 'EUR', value: '100.00'), description: 'Commission payout to merchant', source: new TransferParty( id: 'org_platform123', description: 'Platform fee collection' ), destination: new TransferParty( id: 'org_merchant456', description: 'Merchant payout' ), category: ConnectBalanceTransferCategory::PURCHASE ) ); echo "Transfer: {$transfer->id}"; echo "Status: {$transfer->status}"; // "created", "succeeded", "failed" echo "Executed: {$transfer->executedAt}"; ``` ## Client Links (Merchant Onboarding) Create client links to onboard new merchants through your platform. Client links are used in Mollie Connect to onboard merchants and connect them to your OAuth application. ```php use Mollie\Api\Http\Data\Owner; use Mollie\Api\Http\Data\OwnerAddress; use Mollie\Api\Http\Requests\CreateClientLinkRequest; // Create a client link for merchant onboarding $clientLink = $mollie->send( new CreateClientLinkRequest( owner: new Owner( email: 'merchant@example.com', givenName: 'John', familyName: 'Doe', locale: 'en_US' ), organizationName: 'Merchant Store', address: new OwnerAddress( countryCode: 'NL', streetAndNumber: 'Keizersgracht 313', postalCode: '1016 EE', city: 'Amsterdam' ), registrationNumber: '30204462', vatNumber: 'NL123456789B01' ) ); // Generate OAuth redirect URL for the merchant $redirectUrl = $clientLink->getRedirectUrl( clientId: 'app_j9Pakf56Ajta6Y65AkdTtAv', state: bin2hex(random_bytes(8)), // CSRF protection prompt: 'force', scopes: ['payments.read', 'payments.write', 'refunds.write'] ); // Redirect merchant to complete onboarding header("Location: {$redirectUrl}", true, 303); ``` ## List Capabilities Check which capabilities are enabled for an account. Capabilities indicate what features are available, such as payments, refunds, and settlements. ```php use Mollie\Api\Http\Requests\ListCapabilitiesRequest; use Mollie\Api\Http\Requests\GetCapabilityRequest; // List all capabilities (requires OAuth) $capabilities = $mollie->send(new ListCapabilitiesRequest()); foreach ($capabilities as $capability) { echo "{$capability->name}: {$capability->status}\n"; // Status: "active", "pending", "inactive" } // Get specific capability $paymentsCapability = $mollie->send( new GetCapabilityRequest(id: 'payments') ); if ($paymentsCapability->status === 'active') { echo "Payments are enabled!"; } ``` ## Testing with Mock Responses Create mock clients for testing without making real API calls. The mock client allows you to define expected responses and assert that specific requests were made. ```php use Mollie\Api\MollieApiClient; use Mollie\Api\Fake\MockResponse; use Mollie\Api\Http\Requests\GetPaymentRequest; use Mollie\Api\Http\Requests\CreatePaymentRequest; use Mollie\Api\Resources\Payment; use Mollie\Api\Resources\PaymentCollection; // Create a fake client with predefined responses $client = MollieApiClient::fake([ GetPaymentRequest::class => MockResponse::ok([ 'resource' => 'payment', 'id' => 'tr_test123', 'status' => 'paid', 'amount' => ['value' => '10.00', 'currency' => 'EUR'] ]) ]); // Use the fake client in tests $payment = $client->send(new GetPaymentRequest(id: 'tr_test123')); assert($payment->id === 'tr_test123'); assert($payment->isPaid()); // Assert requests were made $client->assertSent(GetPaymentRequest::class); $client->assertSentCount(1); // Mock a collection response $client = MollieApiClient::fake([ 'payments.page' => MockResponse::list(PaymentCollection::class) ->add(['resource' => 'payment', 'id' => 'tr_1', 'status' => 'paid']) ->add(['resource' => 'payment', 'id' => 'tr_2', 'status' => 'open']) ->create() ]); // Mock error responses $client = MollieApiClient::fake([ GetPaymentRequest::class => MockResponse::notFound('Payment not found'), CreatePaymentRequest::class => MockResponse::unprocessableEntity( 'Amount must be at least 1.00', 'amount' ) ]); ``` ## Sequence Mock Responses Define different responses for consecutive calls to the same endpoint. Useful for testing retry logic or multi-step workflows. ```php use Mollie\Api\MollieApiClient; use Mollie\Api\Fake\MockResponse; use Mollie\Api\Fake\SequenceMockResponse; use Mollie\Api\Http\Requests\GetPaymentRequest; $client = MollieApiClient::fake([ GetPaymentRequest::class => new SequenceMockResponse( MockResponse::ok(['id' => 'tr_1', 'status' => 'open']), MockResponse::ok(['id' => 'tr_1', 'status' => 'pending']), MockResponse::ok(['id' => 'tr_1', 'status' => 'paid']) ) ]); // First call returns 'open' $payment1 = $client->send(new GetPaymentRequest(id: 'tr_1')); assert($payment1->status === 'open'); // Second call returns 'pending' $payment2 = $client->send(new GetPaymentRequest(id: 'tr_1')); assert($payment2->status === 'pending'); // Third call returns 'paid' $payment3 = $client->send(new GetPaymentRequest(id: 'tr_1')); assert($payment3->status === 'paid'); ``` ## Debugging API Requests Enable debugging to inspect requests and responses during development. Debug mode outputs detailed information about HTTP requests and responses. ```php // Enable all debugging $mollie->debug(); // Debug only requests or responses $mollie->debugRequest(); $mollie->debugResponse(); // Debug with die after output $mollie->debugRequest(die: true); // Debug specific request $payment = $mollie->send( (new GetPaymentRequest(id: 'tr_xxx'))->debug() ); // Custom debug handler $mollie->debugRequest(function ($pendingRequest, $psrRequest) { Log::debug('Mollie Request', [ 'method' => $psrRequest->getMethod(), 'uri' => (string) $psrRequest->getUri(), 'headers' => $psrRequest->getHeaders(), 'body' => (string) $psrRequest->getBody() ]); }); $mollie->debugResponse(function ($response, $psrResponse) { Log::debug('Mollie Response', [ 'status' => $psrResponse->getStatusCode(), 'body' => (string) $psrResponse->getBody() ]); }); ``` ## Idempotency Use idempotency keys to prevent duplicate operations from network retries. Idempotent requests ensure that if the same request is sent multiple times, only one operation is performed. ```php // Set a custom idempotency key for the next request $mollie->setIdempotencyKey('order_12345_payment'); $payment = $mollie->send( new CreatePaymentRequest( description: 'Order #12345', amount: Money::euro('10.00'), redirectUrl: 'https://example.com/return' ) ); // The key is automatically cleared after use // Use a custom key generator use Mollie\Api\Contracts\IdempotencyKeyGeneratorContract; class MyIdempotencyGenerator implements IdempotencyKeyGeneratorContract { public function generate(): string { return 'myapp_' . uniqid('', true); } } $mollie->setIdempotencyKeyGenerator(new MyIdempotencyGenerator()); ``` ## Retry Strategy Configure automatic retry behavior for failed requests. The default strategy retries failed requests with linear backoff, useful for handling temporary network issues. ```php use Mollie\Api\Http\Retry\LinearRetryStrategy; // Default: 5 retries with 1000ms linear backoff // Retry 1: immediate, Retry 2: 1000ms, Retry 3: 2000ms, etc. // Custom retry strategy $mollie->setRetryStrategy( new LinearRetryStrategy( maxRetries: 3, // Maximum number of retries delayIncrease: 500 // Delay increase per retry (ms) ) ); // Disable retries entirely $mollie->setRetryStrategy(new LinearRetryStrategy(0, 0)); ``` ## Exception Handling Handle specific exceptions for different error scenarios. The library provides typed exceptions for different HTTP status codes and error conditions. ```php use Mollie\Api\Exceptions\ApiException; use Mollie\Api\Exceptions\UnauthorizedException; use Mollie\Api\Exceptions\NotFoundException; use Mollie\Api\Exceptions\ValidationException; use Mollie\Api\Exceptions\TooManyRequestsException; try { $payment = $mollie->payments->get('tr_xxx'); } catch (UnauthorizedException $e) { // 401 - Invalid API key echo "Invalid API key: " . $e->getMessage(); } catch (NotFoundException $e) { // 404 - Resource not found echo "Payment not found: " . $e->getMessage(); } catch (ValidationException $e) { // 422 - Validation error echo "Validation error: " . $e->getMessage(); echo "Field: " . $e->getField(); } catch (TooManyRequestsException $e) { // 429 - Rate limited echo "Rate limited, retry after: " . $e->getRetryAfterHeader(); } catch (ApiException $e) { // Other API errors echo "API error ({$e->getCode()}): " . $e->getMessage(); } catch (\Exception $e) { // Network or other errors echo "Error: " . $e->getMessage(); } ``` ## Adding Custom Parameters Add unsupported or custom parameters to requests. Use the payload and query methods to add parameters not covered by the request class. ```php use Mollie\Api\Http\Requests\CreatePaymentRequest; use Mollie\Api\Http\Data\Money; $request = new CreatePaymentRequest( description: 'Order #12345', amount: Money::euro('10.00'), redirectUrl: 'https://example.com/return' ); // Add custom payload parameters $request->payload()->add('customField', 'customValue'); $request->payload()->add('nested', ['key' => 'value']); // Add custom query parameters $request->query()->add('include', 'details'); $payment = $mollie->send($request); ``` ## Summary The Mollie API PHP Client provides a comprehensive solution for integrating payment processing into PHP applications. It supports the full range of Mollie's payment services including one-time payments, recurring payments via subscriptions and mandates, refunds, and payment links. The library is particularly well-suited for marketplace platforms using Mollie Connect, offering OAuth authentication, balance transfers between connected organizations, and merchant onboarding through client links. Key integration patterns include: using request classes for type-safe API interactions, implementing webhooks with signature verification for real-time payment status updates, setting up recurring payments through the customer-mandate-subscription flow, and leveraging the testing utilities for comprehensive test coverage without making live API calls. The library handles common production concerns like idempotency for preventing duplicate operations, automatic retries for network resilience, and detailed debugging capabilities for troubleshooting issues.