Initial commit
This commit is contained in:
commit
2b9e58beee
822 files changed
+62544
No files matched your search
+102
@@ -0,0 +1,102 @@
|
||||
# Debugging with Mollie API Client
|
||||
|
||||
## Overview
|
||||
|
||||
The Mollie API client provides debugging callbacks to help you inspect and troubleshoot API requests and responses. The built-in Symfony VarDumper debugger prints request and response details for local development. Exception handling sanitizes sensitive request data before it is attached to thrown exceptions, but default debug output itself is not a production-safe logging surface.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Enable All Debugging
|
||||
|
||||
To enable both request and response debugging:
|
||||
|
||||
```php
|
||||
$mollie = new \Mollie\Api\MollieApiClient();
|
||||
$mollie->debug(); // Enables both request and response debugging
|
||||
```
|
||||
|
||||
The default debugger requires `symfony/var-dumper`. If that package is not installed, calling the default debugger throws an actionable runtime exception. Pass custom callbacks to `debugRequest()` or `debugResponse()` if you want to avoid that optional dependency.
|
||||
|
||||
### Enable on Request
|
||||
|
||||
To enable debugging for a specific request:
|
||||
|
||||
```php
|
||||
$request = new CreatePaymentRequest(...);
|
||||
|
||||
// enable output for request and response
|
||||
$mollie->send($request->debug());
|
||||
|
||||
// only debug request
|
||||
$mollie->send($request->debugRequest(die: true));
|
||||
|
||||
// only debug response
|
||||
$mollie->send($request->debugResponse(die: true));
|
||||
```
|
||||
|
||||
### Debug Specific Parts
|
||||
|
||||
You can choose to debug only requests or only responses:
|
||||
|
||||
```php
|
||||
// Debug only requests
|
||||
$mollie->debugRequest();
|
||||
|
||||
// Debug only responses
|
||||
$mollie->debugResponse();
|
||||
```
|
||||
|
||||
## Custom Debuggers
|
||||
|
||||
You can provide your own debugging functions to customize how debugging information is displayed:
|
||||
|
||||
```php
|
||||
// Custom request debugger
|
||||
$mollie->debugRequest(function($pendingRequest, $psrRequest) {
|
||||
// Your custom debugging logic here
|
||||
});
|
||||
|
||||
// Custom response debugger
|
||||
$mollie->debugResponse(function($response, $psrResponse) {
|
||||
// Your custom debugging logic here
|
||||
});
|
||||
```
|
||||
|
||||
## Security Features
|
||||
|
||||
### Automatic Sanitization
|
||||
|
||||
When an exception is thrown while debugging is enabled, the client sanitizes the request data attached to the exception. The default request/response debug callbacks are for local inspection and may print headers and request bodies. Treat their output as sensitive.
|
||||
|
||||
### Die After Debug
|
||||
|
||||
For development purposes, you can halt execution after debugging output:
|
||||
|
||||
```php
|
||||
$mollie->debug(die: true); // Will stop execution after debugging output
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Development Only**: Never enable debugging in production environments
|
||||
2. **Custom Debuggers**: When implementing custom debuggers, redact credentials and personal data before writing to logs
|
||||
3. **Exception Handling**: Debug mode works with exceptions, and exception request data is sanitized before being exposed
|
||||
|
||||
## Example Usage
|
||||
|
||||
```php
|
||||
try {
|
||||
$mollie = new \Mollie\Api\MollieApiClient();
|
||||
$mollie->setApiKey("test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM");
|
||||
|
||||
// Enable debugging for development
|
||||
$mollie->debug();
|
||||
|
||||
// Your API calls here
|
||||
$payment = $mollie->payments->create([...]);
|
||||
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
// Exception will include sanitized debug information
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,765 @@
|
||||
# Introduction
|
||||
Endpoint collections provide a fluent interface for interacting with Mollie's API. Each collection manages specific resource types like payments, customers, and subscriptions, offering methods to create, retrieve, update, and delete these resources.
|
||||
|
||||
## Setup
|
||||
|
||||
1. **Initialize the Mollie Client:**
|
||||
|
||||
```php
|
||||
$mollie = new \Mollie\Api\MollieApiClient();
|
||||
$mollie->setApiKey("test_*************************");
|
||||
```
|
||||
|
||||
2. **Access Endpoints via the Client:**
|
||||
```php
|
||||
// Payments endpoint
|
||||
$mollie->payments->...
|
||||
|
||||
// Customers endpoint
|
||||
$mollie->customers->...
|
||||
|
||||
// Other endpoints
|
||||
$mollie->balances->...
|
||||
$mollie->orders->...
|
||||
```
|
||||
|
||||
3. **Call methods**
|
||||
|
||||
**Simple: Using arrays**
|
||||
This approach is direct but provides less type safety:
|
||||
```php
|
||||
$payment = $mollie->payments->create([
|
||||
'amount' => [
|
||||
'currency' => 'EUR',
|
||||
'value' => '10.00'
|
||||
],
|
||||
'description' => 'My first API payment'
|
||||
]);
|
||||
```
|
||||
|
||||
**Advanced: Using typed array params**
|
||||
You can use dedicated `Data` objects to add partial type safety to your parameters.
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Data\CreatePaymentPayload;
|
||||
|
||||
$payment = $mollie->payments->create([
|
||||
'description' => 'My first API payment',
|
||||
'amount' => new Money(currency: 'EUR', value: '10.00')
|
||||
]);
|
||||
```
|
||||
|
||||
If you're starting with an array and need to convert it into a structured request, you can use a specific factory designed for this purpose.
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Factories\CreatePaymentRequestFactory;
|
||||
|
||||
// Fully untyped data
|
||||
$createPaymentRequest = CreatePaymentRequestFactory::new([
|
||||
'amount' => [
|
||||
'currency' => 'EUR',
|
||||
'value' => '10.00'
|
||||
],
|
||||
'description' => 'My first API payment'
|
||||
]);
|
||||
|
||||
// Partially untyped
|
||||
$createPaymentRequest = CreatePaymentRequestFactory::new([
|
||||
'amount' => new Money(currency: 'EUR', value: '10.00'),
|
||||
'description' => 'My first API payment'
|
||||
]);
|
||||
```
|
||||
|
||||
This method lets you effortlessly transform arrays into typed objects, thereby enhancing IDE support and increasing type safety while handling your data.
|
||||
|
||||
# Available Endpoints
|
||||
|
||||
## Balances
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/balances-api/get-balance)
|
||||
|
||||
### Balance Information
|
||||
|
||||
```php
|
||||
// Get primary balance
|
||||
$balance = $mollie->balances->primary();
|
||||
|
||||
// Get specific balance
|
||||
$balance = $mollie->balances->get('bal_12345');
|
||||
|
||||
// List balances
|
||||
$balances = $mollie->balances->page();
|
||||
```
|
||||
|
||||
## Balance Reports
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/balance-reports-api/get-balance-report)
|
||||
|
||||
### Balance Report Details
|
||||
|
||||
```php
|
||||
// Get report for specific balance
|
||||
$report = $mollie->balanceReports->getForId('bal_12345', [
|
||||
'from' => '2024-01-01',
|
||||
'until' => '2024-01-31',
|
||||
'grouping' => 'transaction-categories'
|
||||
]);
|
||||
```
|
||||
|
||||
## Balance Transactions
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/balance-transactions-api/list-balance-transactions)
|
||||
|
||||
### Balance Transaction Management
|
||||
|
||||
```php
|
||||
// Get transactions for a balance
|
||||
$transactions = $mollie->balanceTransactions->pageFor($balance);
|
||||
|
||||
// Use iterator for all transactions
|
||||
foreach ($mollie->balanceTransactions->iteratorFor($balance) as $transaction) {
|
||||
echo $transaction->id;
|
||||
}
|
||||
```
|
||||
|
||||
## Chargebacks
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/chargebacks-api/get-chargeback)
|
||||
|
||||
### Chargeback Management
|
||||
|
||||
```php
|
||||
// Get all chargebacks
|
||||
$chargebacks = $mollie->chargebacks->page();
|
||||
|
||||
// Use iterator for all chargebacks
|
||||
foreach ($mollie->chargebacks->iterator() as $chargeback) {
|
||||
echo $chargeback->id;
|
||||
}
|
||||
```
|
||||
|
||||
## Clients
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/clients-api/get-client)
|
||||
|
||||
### Client Management
|
||||
|
||||
```php
|
||||
// Get a specific client
|
||||
$client = $mollie->clients->get('org_12345678', [
|
||||
'testmode' => true
|
||||
]);
|
||||
|
||||
// List all clients
|
||||
$clients = $mollie->clients->page(
|
||||
from: 'org_12345678',
|
||||
limit: 50
|
||||
);
|
||||
```
|
||||
|
||||
## Customers
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/customers-api/create-customer)
|
||||
|
||||
### Customer Management
|
||||
|
||||
```php
|
||||
// Create a customer
|
||||
$customer = $mollie->customers->create([
|
||||
'name' => 'John Doe',
|
||||
'email' => 'john@example.org',
|
||||
]);
|
||||
|
||||
// Get a customer
|
||||
$customer = $mollie->customers->get('cst_8wmqcHMN4U');
|
||||
|
||||
// Update a customer
|
||||
$customer = $mollie->customers->update('cst_8wmqcHMN4U', [
|
||||
'name' => 'Updated Name'
|
||||
]);
|
||||
|
||||
// Delete a customer
|
||||
$mollie->customers->delete('cst_8wmqcHMN4U');
|
||||
|
||||
// List customers
|
||||
$customers = $mollie->customers->page();
|
||||
```
|
||||
|
||||
## Invoices
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/invoices-api/get-invoice)
|
||||
|
||||
### Invoice Management
|
||||
|
||||
```php
|
||||
// Get a specific invoice
|
||||
$invoice = $mollie->invoices->get('inv_xBEbP9rvAq');
|
||||
|
||||
// List all invoices
|
||||
$invoices = $mollie->invoices->page(
|
||||
from: 'inv_xBEbP9rvAq',
|
||||
limit: 50
|
||||
);
|
||||
```
|
||||
|
||||
## Mandates
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/mandates-api/create-mandate)
|
||||
|
||||
### Mandate Management
|
||||
|
||||
```php
|
||||
// Create a mandate for a customer
|
||||
$mandate = $mollie->mandates->createFor($customer, [
|
||||
'method' => \Mollie\Api\Types\PaymentMethod::Directdebit,
|
||||
'consumerName' => 'John Doe',
|
||||
'consumerAccount' => 'NL55INGB0000000000',
|
||||
'consumerBic' => 'INGBNL2A',
|
||||
'signatureDate' => '2024-01-01',
|
||||
'mandateReference' => 'YOUR-COMPANY-MD13804'
|
||||
]);
|
||||
|
||||
// Get a mandate
|
||||
$mandate = $mollie->mandates->getFor($customer, 'mdt_h3gAaD5zP');
|
||||
|
||||
// Revoke a mandate
|
||||
$mollie->mandates->revokeFor($customer, 'mdt_h3gAaD5zP');
|
||||
|
||||
// List mandates
|
||||
$mandates = $mollie->mandates->pageFor($customer);
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/methods-api/get-method)
|
||||
|
||||
### Payment Methods
|
||||
|
||||
```php
|
||||
// Get a method
|
||||
$method = $mollie->methods->get(\Mollie\Api\Types\PaymentMethod::Ideal);
|
||||
|
||||
// List all methods
|
||||
$methods = $mollie->methods->all();
|
||||
|
||||
// List enabled methods
|
||||
$methods = $mollie->methods->allEnabled([
|
||||
'amount' => [
|
||||
'currency' => 'EUR',
|
||||
'value' => '100.00'
|
||||
]
|
||||
]);
|
||||
```
|
||||
|
||||
### Method Issuers
|
||||
|
||||
```php
|
||||
// Enable an issuer
|
||||
$issuer = $mollie->methodIssuers->enable(
|
||||
'pfl_v9hTwCvYqw',
|
||||
\Mollie\Api\Types\PaymentMethod::Ideal,
|
||||
'ideal_INGBNL2A'
|
||||
);
|
||||
|
||||
// Disable an issuer
|
||||
$mollie->methodIssuers->disable(
|
||||
'pfl_v9hTwCvYqw',
|
||||
\Mollie\Api\Types\PaymentMethod::Ideal,
|
||||
'ideal_INGBNL2A'
|
||||
);
|
||||
```
|
||||
|
||||
## Onboarding
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/onboarding-api/get-onboarding-status)
|
||||
|
||||
### Onboarding Management
|
||||
|
||||
```php
|
||||
// Get onboarding status
|
||||
$onboarding = $mollie->onboarding->status();
|
||||
```
|
||||
|
||||
## Organizations
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/organizations-api/get-organization)
|
||||
|
||||
### Organization Management
|
||||
|
||||
```php
|
||||
// Get an organization
|
||||
$organization = $mollie->organizations->get('org_12345678');
|
||||
|
||||
// Get current organization
|
||||
$organization = $mollie->organizations->current();
|
||||
|
||||
// Get partner status
|
||||
$partner = $mollie->organizations->partnerStatus();
|
||||
```
|
||||
|
||||
## Permissions
|
||||
|
||||
[API Reference](https://docs.mollie.com/reference/v2/permissions-api/get-permission) · [Full list of permission scopes](https://docs.mollie.com/docs/permissions)
|
||||
|
||||
### Permission Management
|
||||
|
||||
```php
|
||||
// Get a permission
|
||||
$permission = $mollie->permissions->get('payments.read');
|
||||
|
||||
// List all permissions
|
||||
$permissions = $mollie->permissions->list();
|
||||
```
|
||||
|
||||
## Payments
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/payments-api/create-payment)
|
||||
|
||||
### Payment Management
|
||||
|
||||
```php
|
||||
// Create a payment
|
||||
$payment = $mollie->payments->create([
|
||||
'description' => 'Order #12345',
|
||||
'amount' => [
|
||||
'currency' => 'EUR',
|
||||
'value' => '10.00'
|
||||
],
|
||||
'redirectUrl' => 'https://webshop.example.org/order/12345/',
|
||||
'webhookUrl' => 'https://webshop.example.org/mollie-webhook/'
|
||||
]);
|
||||
|
||||
// Get a payment
|
||||
$payment = $mollie->payments->get('tr_7UhSN1zuXS');
|
||||
|
||||
// Update a payment
|
||||
$payment = $mollie->payments->update('tr_7UhSN1zuXS', [
|
||||
'description' => 'Updated description'
|
||||
]);
|
||||
|
||||
// Cancel a payment
|
||||
$mollie->payments->cancel('tr_7UhSN1zuXS');
|
||||
|
||||
// List payments
|
||||
$payments = $mollie->payments->page();
|
||||
```
|
||||
|
||||
### Payment Links
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/payment-links-api/create-payment-link)
|
||||
|
||||
### Payment Captures
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/captures-api/get-capture)
|
||||
|
||||
### Payment Chargebacks
|
||||
|
||||
```php
|
||||
// Get a chargeback
|
||||
$chargeback = $mollie->paymentChargebacks->getFor($payment, 'chb_n9z0tp');
|
||||
|
||||
// List chargebacks for payment
|
||||
$chargebacks = $mollie->paymentChargebacks->pageFor($payment);
|
||||
```
|
||||
|
||||
### Payment Routes
|
||||
|
||||
```php
|
||||
// Create a delayed route
|
||||
$route = $mollie->paymentRoutes->createFor(
|
||||
$payment,
|
||||
['value' => '10.00', 'currency' => 'EUR'],
|
||||
['type' => 'organization', 'organizationId' => 'org_12345'],
|
||||
'2025-01-01' // optional release date
|
||||
);
|
||||
|
||||
// List payment routes
|
||||
$routes = $mollie->paymentRoutes->listFor($payment);
|
||||
|
||||
// Update release date for a route
|
||||
$route = $mollie->paymentRoutes->updateReleaseDateFor(
|
||||
$payment,
|
||||
'rt_abc123',
|
||||
'2024-01-01'
|
||||
);
|
||||
```
|
||||
|
||||
## Profiles
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/profiles-api/create-profile)
|
||||
|
||||
### Profile Management
|
||||
|
||||
```php
|
||||
// Create a profile
|
||||
$profile = $mollie->profiles->create([
|
||||
'name' => 'My Test Profile',
|
||||
'website' => 'https://example.org',
|
||||
'email' => 'info@example.org',
|
||||
'phone' => '+31612345678',
|
||||
'mode' => 'test'
|
||||
]);
|
||||
|
||||
// Get a profile
|
||||
$profile = $mollie->profiles->get('pfl_v9hTwCvYqw');
|
||||
|
||||
// Get current profile
|
||||
$profile = $mollie->profiles->getCurrent();
|
||||
|
||||
// Update a profile
|
||||
$profile = $mollie->profiles->update('pfl_v9hTwCvYqw', [
|
||||
'name' => 'Updated Profile Name'
|
||||
]);
|
||||
|
||||
// Delete a profile
|
||||
$mollie->profiles->delete('pfl_v9hTwCvYqw');
|
||||
|
||||
// List profiles
|
||||
$profiles = $mollie->profiles->page();
|
||||
```
|
||||
|
||||
### Profile Methods
|
||||
|
||||
```php
|
||||
// Enable a method
|
||||
$method = $mollie->profileMethods->enable(
|
||||
'pfl_v9hTwCvYqw',
|
||||
\Mollie\Api\Types\PaymentMethod::Ideal
|
||||
);
|
||||
|
||||
// Disable a method
|
||||
$mollie->profileMethods->disable(
|
||||
'pfl_v9hTwCvYqw',
|
||||
\Mollie\Api\Types\PaymentMethod::Ideal
|
||||
);
|
||||
```
|
||||
|
||||
## Refunds
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/refunds-api/create-refund)
|
||||
|
||||
### Refund Management
|
||||
|
||||
```php
|
||||
// Create a refund for a payment
|
||||
$refund = $mollie->refunds->createForPayment($paymentId, [
|
||||
'amount' => [
|
||||
'currency' => 'EUR',
|
||||
'value' => '15.00'
|
||||
],
|
||||
'description' => 'Refund for returned item'
|
||||
]);
|
||||
|
||||
// List refunds
|
||||
$refunds = $mollie->refunds->page();
|
||||
```
|
||||
|
||||
## Sales Invoices
|
||||
|
||||
[Official Documentation TBA]
|
||||
|
||||
### Sales Invoice Management
|
||||
|
||||
```php
|
||||
use Mollie\Api\Types\VatMode;
|
||||
use Mollie\Api\Types\VatScheme;
|
||||
use Mollie\Api\Types\PaymentTerm;
|
||||
use Mollie\Api\Types\RecipientType;
|
||||
use Mollie\Api\Types\SalesInvoiceStatus;
|
||||
|
||||
// Create a sales invoice
|
||||
$salesInvoice = $mollie->salesInvoices->create([
|
||||
'currency' => 'EUR',
|
||||
'status' => SalesInvoiceStatus::Draft,
|
||||
'vatScheme' => VatScheme::Standard,
|
||||
'vatMode' => VatMode::Inclusive,
|
||||
'paymentTerm' => PaymentTerm::Days30,
|
||||
'recipientIdentifier' => 'XXXXX',
|
||||
'recipient' => [
|
||||
'type' => RecipientType::Consumer,
|
||||
'email' => 'darth@vader.deathstar',
|
||||
'streetAndNumber' => 'Sample Street 12b',
|
||||
'postalCode' => '2000 AA',
|
||||
'city' => 'Amsterdam',
|
||||
'country' => 'NL',
|
||||
'locale' => 'nl_NL'
|
||||
],
|
||||
'lines' => [
|
||||
[
|
||||
'description' => 'Monthly subscription fee',
|
||||
'quantity' => 1,
|
||||
'vatRate' => '21',
|
||||
'unitPrice' => [
|
||||
'currency' => 'EUR',
|
||||
'value' => '10,00'
|
||||
]
|
||||
]
|
||||
]
|
||||
]);
|
||||
|
||||
// Get a sales invoice
|
||||
$salesInvoice = $mollie->salesInvoices->get('invoice_12345');
|
||||
|
||||
// Update a sales invoice
|
||||
$salesInvoice = $mollie->salesInvoices->update('invoice_12345', [
|
||||
'description' => 'Updated description'
|
||||
]);
|
||||
|
||||
// Delete a sales invoice
|
||||
$mollie->salesInvoices->delete('invoice_12345');
|
||||
|
||||
// List sales invoices
|
||||
$salesInvoices = $mollie->salesInvoices->page();
|
||||
```
|
||||
|
||||
## Sessions
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/sessions-api/create-session)
|
||||
|
||||
### Session Management
|
||||
|
||||
```php
|
||||
// Create a session
|
||||
$session = $mollie->sessions->create([
|
||||
'amount' => [
|
||||
'currency' => 'EUR',
|
||||
'value' => '100.00'
|
||||
],
|
||||
'description' => 'Session for service'
|
||||
]);
|
||||
|
||||
// Get a session
|
||||
$session = $mollie->sessions->get('sessionId');
|
||||
```
|
||||
|
||||
## Settlements
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/settlements-api/get-settlement)
|
||||
|
||||
### Settlement Management
|
||||
|
||||
```php
|
||||
// Get a settlement
|
||||
$settlement = $mollie->settlements->get('settlementId');
|
||||
|
||||
// List settlements
|
||||
$settlements = $mollie->settlements->page();
|
||||
```
|
||||
|
||||
### Settlement Captures
|
||||
|
||||
```php
|
||||
// Get captures for a settlement
|
||||
$captures = $mollie->settlementCaptures->pageFor($settlement);
|
||||
|
||||
// Use iterator
|
||||
foreach ($mollie->settlementCaptures->iteratorFor($settlement) as $capture) {
|
||||
echo $capture->id;
|
||||
}
|
||||
```
|
||||
|
||||
### Settlement Chargebacks
|
||||
|
||||
```php
|
||||
// List chargebacks for a settlement
|
||||
$chargebacks = $mollie->settlementChargebacks->pageFor($settlement);
|
||||
|
||||
// Use iterator
|
||||
foreach ($mollie->settlementChargebacks->iteratorFor($settlement) as $chargeback) {
|
||||
echo $chargeback->id;
|
||||
}
|
||||
```
|
||||
|
||||
### Settlement Payments
|
||||
|
||||
```php
|
||||
// List payments in a settlement
|
||||
$payments = $mollie->settlementPayments->pageFor($settlement);
|
||||
|
||||
// Use iterator
|
||||
foreach ($mollie->settlementPayments->iteratorFor($settlement) as $payment) {
|
||||
echo $payment->id;
|
||||
}
|
||||
```
|
||||
|
||||
## Subscriptions
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/subscriptions-api/create-subscription)
|
||||
|
||||
### Subscription Management
|
||||
|
||||
```php
|
||||
// Create a subscription
|
||||
$subscription = $mollie->subscriptions->createForCustomer('customerId', [
|
||||
'amount' => [
|
||||
'currency' => 'EUR',
|
||||
'value' => '25.00'
|
||||
],
|
||||
'interval' => '1 month',
|
||||
'description' => 'Monthly subscription'
|
||||
]);
|
||||
|
||||
// List subscriptions
|
||||
$subscriptions = $mollie->subscriptions->pageForCustomer('customerId');
|
||||
```
|
||||
|
||||
## Terminals
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/terminals-api/get-terminal)
|
||||
|
||||
### Terminal Management
|
||||
|
||||
```php
|
||||
// Get a terminal
|
||||
$terminal = $mollie->terminals->get('terminalId');
|
||||
|
||||
// List terminals
|
||||
$terminals = $mollie->terminals->page();
|
||||
```
|
||||
|
||||
## Terminal Pairing Codes
|
||||
|
||||
Official Documentation:
|
||||
[Request pairing code](https://docs.mollie.com/reference/terminals-request-pairing-code),
|
||||
[Get pairing code](https://docs.mollie.com/reference/terminals-get-pairing-code),
|
||||
[List pairing codes](https://docs.mollie.com/reference/terminals-list-pairing-codes),
|
||||
[Revoke pairing code](https://docs.mollie.com/reference/terminals-revoke-pairing-code)
|
||||
|
||||
### Terminal Pairing Code Management
|
||||
|
||||
```php
|
||||
// Request a pairing code, including QR code details
|
||||
$pairingCode = $mollie->terminalPairingCodes->request('profileId', includeQrCode: true);
|
||||
|
||||
// Get a pairing code, including QR code details
|
||||
$pairingCode = $mollie->terminalPairingCodes->get('pairingCodeId', includeQrCode: true);
|
||||
|
||||
// List pairing codes
|
||||
$pairingCodes = $mollie->terminalPairingCodes->page(limit: 50, profileId: 'profileId');
|
||||
|
||||
// Use iterator
|
||||
foreach ($mollie->terminalPairingCodes->iterator(profileId: 'profileId') as $pairingCode) {
|
||||
echo $pairingCode->id;
|
||||
}
|
||||
|
||||
// Revoke a pairing code
|
||||
$pairingCode = $mollie->terminalPairingCodes->revoke('pairingCodeId');
|
||||
|
||||
// Check pairing code status using helper methods
|
||||
if ($pairingCode->isActive()) {
|
||||
echo "Pairing code is active\n";
|
||||
} elseif ($pairingCode->isRevoked()) {
|
||||
echo "Pairing code was revoked at: {$pairingCode->revokedAt}\n";
|
||||
}
|
||||
```
|
||||
|
||||
## Wallets
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/wallets-api/request-apple-pay-payment-session)
|
||||
|
||||
### Wallet Management
|
||||
|
||||
```php
|
||||
// Request an Apple Pay payment session
|
||||
$session = $mollie->wallets->requestApplePayPaymentSession([
|
||||
'domainName' => 'example.com',
|
||||
'validationUrl' => 'https://apple-pay-gateway.apple.com/paymentservices/startSession'
|
||||
]);
|
||||
```
|
||||
|
||||
## Webhooks
|
||||
|
||||
[Official Documentation](https://docs.mollie.com/reference/v2/webhooks-api/create-webhook)
|
||||
|
||||
### Webhook Management
|
||||
|
||||
```php
|
||||
use Mollie\Api\Types\WebhookEventType;
|
||||
|
||||
// Create a webhook
|
||||
$webhook = $mollie->webhooks->create([
|
||||
'url' => 'https://example.com/webhook',
|
||||
'description' => 'Payment notifications',
|
||||
'events' => [
|
||||
WebhookEventType::PAYMENT_LINK_PAID,
|
||||
WebhookEventType::PROFILE_VERIFIED
|
||||
],
|
||||
'secret' => 'my-secret-key-123'
|
||||
]);
|
||||
|
||||
// Get a webhook
|
||||
$webhook = $mollie->webhooks->get('wh_4KgGJJSZpH');
|
||||
|
||||
// Update a webhook
|
||||
$webhook = $mollie->webhooks->update('wh_4KgGJJSZpH', [
|
||||
'url' => 'https://updated-example.com/webhook',
|
||||
'description' => 'Updated description'
|
||||
]);
|
||||
|
||||
// Delete a webhook
|
||||
$mollie->webhooks->delete('wh_4KgGJJSZpH');
|
||||
|
||||
// Test a webhook
|
||||
$mollie->webhooks->test('wh_4KgGJJSZpH');
|
||||
|
||||
// List webhooks
|
||||
$webhooks = $mollie->webhooks->page();
|
||||
|
||||
// Using convenience methods on webhook resource
|
||||
$webhook = $mollie->webhooks->get('wh_4KgGJJSZpH');
|
||||
$webhook->update(['description' => 'New description']);
|
||||
$webhook->delete();
|
||||
$webhook->test();
|
||||
```
|
||||
|
||||
### Webhook Events
|
||||
|
||||
```php
|
||||
// Get a webhook event
|
||||
$webhookEvent = $mollie->webhookEvents->get('whev_abc123');
|
||||
|
||||
// Check event status using helper methods
|
||||
if ($webhookEvent->wasDelivered()) {
|
||||
echo "Webhook was successfully delivered\n";
|
||||
} elseif ($webhookEvent->failed()) {
|
||||
echo "Webhook delivery failed: {$webhookEvent->error}\n";
|
||||
} elseif ($webhookEvent->hasRetryPending()) {
|
||||
echo "Retry pending at: {$webhookEvent->nextRetryAt}\n";
|
||||
}
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Pagination
|
||||
|
||||
Most list methods support pagination:
|
||||
|
||||
```php
|
||||
// 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;
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
Handle errors using `ApiException`:
|
||||
|
||||
```php
|
||||
try {
|
||||
$payment = $mollie->payments->get('tr_xxx');
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: {$e->getMessage()}";
|
||||
}
|
||||
```
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
# Exceptions
|
||||
|
||||
This document describes the exceptions that can be thrown by the Mollie API PHP client.
|
||||
|
||||
## Exception Hierarchy
|
||||
|
||||
### `MollieException`
|
||||
|
||||
The abstract base class for **all** exceptions in the Mollie API PHP client.
|
||||
|
||||
### `RequestException`
|
||||
|
||||
The `RequestException` serves as the base for all request-related exceptions.
|
||||
|
||||
### `ApiException`
|
||||
|
||||
Extends `RequestException` and serves as the base for all API-related exceptions. This is the parent class for all specific HTTP status code exceptions. This exception is also thrown when the Mollie API returns an error response that doesn't match any of the more specific exceptions below.
|
||||
|
||||
Properties and methods:
|
||||
- `getDocumentationUrl()`: Returns the URL to the documentation for this error, if available
|
||||
- `getDashboardUrl()`: Returns the URL to the dashboard for this error, if available
|
||||
- `getRaisedAt()`: Returns the timestamp when the exception was raised
|
||||
- `getPlainMessage()`: Returns the plain exception message without timestamp and metadata
|
||||
|
||||
## HTTP Status Code Exceptions
|
||||
|
||||
The following exceptions all extend `ApiException` and are thrown based on specific HTTP status codes returned by the API:
|
||||
|
||||
### `UnauthorizedException` (401)
|
||||
|
||||
Thrown when authentication fails. This typically happens when using an invalid API key.
|
||||
|
||||
### `ForbiddenException` (403)
|
||||
|
||||
Thrown when the request is understood but refused due to permission issues.
|
||||
|
||||
### `NotFoundException` (404)
|
||||
|
||||
Thrown when the requested resource does not exist.
|
||||
|
||||
### `MethodNotAllowedException` (405)
|
||||
|
||||
Thrown when the HTTP method used is not allowed for the requested endpoint.
|
||||
|
||||
### `RequestTimeoutException` (408)
|
||||
|
||||
Thrown when the request times out.
|
||||
|
||||
### `ValidationException` (422)
|
||||
|
||||
Thrown when the request data fails validation. This typically happens when required fields are missing or have invalid values.
|
||||
|
||||
### `TooManyRequestsException` (429)
|
||||
|
||||
Thrown when rate limiting is applied because too many requests were made in a short period.
|
||||
|
||||
### `ServiceUnavailableException` (503)
|
||||
|
||||
Thrown when the Mollie API service is temporarily unavailable.
|
||||
|
||||
## Network Exceptions
|
||||
|
||||
### `NetworkRequestException`
|
||||
|
||||
Thrown when a network error occurs during the request.
|
||||
|
||||
### `RetryableNetworkRequestException`
|
||||
|
||||
Thrown when a network error occurs that might be resolved by retrying the request.
|
||||
|
||||
## Other Exceptions
|
||||
|
||||
### `ClientException`
|
||||
|
||||
Base exception for client-related errors.
|
||||
|
||||
### `EmbeddedResourcesNotParseableException`
|
||||
|
||||
Thrown when embedded resources cannot be parsed.
|
||||
|
||||
### `IncompatiblePlatformException`
|
||||
|
||||
Thrown when the platform is incompatible with the Mollie API client.
|
||||
|
||||
### `InvalidAuthenticationException`
|
||||
|
||||
Thrown when the authentication method is invalid.
|
||||
|
||||
### `JsonParseException`
|
||||
|
||||
Thrown when JSON parsing fails.
|
||||
|
||||
### `LogicException`
|
||||
|
||||
Thrown when there is a logical error in the client code.
|
||||
|
||||
### `MissingAuthenticationException`
|
||||
|
||||
Thrown when no authentication method is provided.
|
||||
|
||||
### `ServerException`
|
||||
|
||||
Thrown when a server error occurs.
|
||||
|
||||
### `UnrecognizedClientException`
|
||||
|
||||
Thrown when the client is not recognized by the Mollie API.
|
||||
|
||||
## Handling Exceptions
|
||||
|
||||
Here's an example of how to handle exceptions:
|
||||
|
||||
```php
|
||||
try {
|
||||
$payment = $mollie->payments->get("tr_xxx");
|
||||
} catch (Mollie\Api\Exceptions\UnauthorizedException $e) {
|
||||
// Invalid API key
|
||||
echo "Invalid API key: " . $e->getMessage();
|
||||
} catch (Mollie\Api\Exceptions\NotFoundException $e) {
|
||||
// Payment not found
|
||||
echo "Payment not found: " . $e->getMessage();
|
||||
} catch (Mollie\Api\Exceptions\MollieException $e) {
|
||||
// Other Mollie error
|
||||
echo "Mollie error: " . $e->getMessage();
|
||||
}
|
||||
```
|
||||
|
||||
You can also catch all Mollie exceptions at once:
|
||||
|
||||
```php
|
||||
try {
|
||||
$payment = $mollie->payments->get("tr_xxx");
|
||||
} catch (Mollie\Api\Exceptions\MollieException $e) {
|
||||
// Any Mollie error
|
||||
echo "Mollie error: " . $e->getMessage();
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,46 @@
|
||||
# HTTP Adapters
|
||||
|
||||
## Overview
|
||||
|
||||
An HTTP adapter is a component that manages the communication between your application and an API. It abstracts the details of making HTTP requests and handling responses, allowing you to use different HTTP clients (like Guzzle, cURL, or custom clients) interchangeably without changing the way you interact with the API.
|
||||
|
||||
## MollieHttpAdapterPicker
|
||||
|
||||
The `MollieHttpAdapterPicker` is responsible for selecting the appropriate HTTP adapter based on the environment or the provided HTTP client. If no client is specified in the `MollieApiClient` constructor, it picks a default adapter.
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **No Client Specified**: If no client is provided, it checks if Guzzle is available and picks the appropriate version of the Guzzle adapter.
|
||||
2. **Custom Client Provided**: If a custom client is provided and it implements the `HttpAdapterContract`, it is used directly. If it's a Guzzle client, it is wrapped in a `GuzzleMollieHttpAdapter`.
|
||||
3. **Unrecognized Client**: Throws an `UnrecognizedClientException` if the client is not recognized.
|
||||
|
||||
## Creating a Custom Adapter
|
||||
|
||||
To create a custom HTTP adapter:
|
||||
1. Implement HttpAdapterContract.
|
||||
2. Use HasDefaultFactories Trait to simplify adapter implementation.
|
||||
|
||||
```php
|
||||
use Mollie\Api\Contracts\HttpAdapterContract;
|
||||
use Mollie\Api\Traits\HasDefaultFactories;
|
||||
|
||||
class MyCustomHttpAdapter implements HttpAdapterContract {
|
||||
use HasDefaultFactories;
|
||||
|
||||
public function sendRequest(PendingRequest $pendingRequest): Response {
|
||||
// Implementation for sending HTTP request
|
||||
}
|
||||
|
||||
public function version(): ?string {
|
||||
return 'my-custom-adapter/1.0';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Available Adapters
|
||||
|
||||
Out of the box, the Mollie API client provides several adapters:
|
||||
|
||||
- **GuzzleMollieHttpAdapter**: Wraps a Guzzle HTTP client for sending requests.
|
||||
- **CurlMollieHttpAdapter**: Uses cURL for sending HTTP requests. This is the default if Guzzle is not available.
|
||||
- **PSR18MollieHttpAdapter**: [PSR-18](https://www.php-fig.org/psr/psr-18/) compatible HTTP adapter
|
||||
@@ -0,0 +1,60 @@
|
||||
# Idempotency
|
||||
|
||||
## Overview
|
||||
|
||||
Idempotency ensures that multiple identical requests to an API result in the same outcome without creating duplicate resources or effects. This is crucial for operations that involve financial transactions to prevent unintended charges or state changes.
|
||||
|
||||
Mollie API supports idempotent requests for critical operations such as creating payments or refunds. This is automatically managed by the API client using the `ApplyIdempotencyKey` middleware.
|
||||
|
||||
For more detailed information, refer to the [Mollie API Idempotency Documentation](https://docs.mollie.com/reference/api-idempotency).
|
||||
|
||||
> [!Note]
|
||||
> This package automatically handles idempotency for you. The information below allows you to override the default idempotency behavior.
|
||||
|
||||
## Automatic Idempotency Key Handling
|
||||
|
||||
The Mollie API client automatically handles idempotency for mutating requests (POST, PATCH, DELETE) through the `ApplyIdempotencyKey` middleware. This middleware checks if the request is a mutating type and applies an idempotency key if one is not already provided.
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Check Request Type**: The middleware checks if the request method is POST, PATCH, or DELETE.
|
||||
2. **Apply Idempotency Key**: If the request is mutating, the middleware will:
|
||||
- Use a custom idempotency key if provided.
|
||||
- Otherwise, generate a key using the configured `IdempotencyKeyGenerator` if available.
|
||||
- If no generator is set and no key is provided, no idempotency key is applied.
|
||||
|
||||
### Customizing Idempotency Key
|
||||
|
||||
You can customize how idempotency keys are generated or applied in several ways:
|
||||
|
||||
- **Provide a Custom Key**: Manually set an idempotency key for a specific request.
|
||||
- **Use a Custom Generator**: Implement the `IdempotencyKeyGeneratorContract` to provide a custom method of generating idempotency keys.
|
||||
|
||||
#### Example: Setting a Custom Key
|
||||
|
||||
```php
|
||||
$mollie->setIdempotencyKey('your_custom_key_here');
|
||||
```
|
||||
|
||||
#### Example: Using a Custom Key Generator
|
||||
|
||||
Implement your key generator:
|
||||
|
||||
```php
|
||||
class MyCustomKeyGenerator implements IdempotencyKeyGeneratorContract {
|
||||
public function generate(): string {
|
||||
return 'custom_' . bin2hex(random_bytes(10));
|
||||
}
|
||||
}
|
||||
|
||||
$mollie->setIdempotencyKeyGenerator(new MyCustomKeyGenerator());
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Unique Keys**: Ensure that each idempotency key is unique to each operation. Typically, UUIDs are used for this purpose.
|
||||
- **Handling Errors**: Handle errors gracefully, especially when an API call with an idempotency key fails. Check the error message to understand whether you should retry the request with the same key or a new key.
|
||||
|
||||
## Conclusionz
|
||||
|
||||
Using idempotency keys in your API requests to Mollie can significantly enhance the reliability of your payment processing system, ensuring that payments are not unintentionally duplicated and that your application behaves predictably even in the face of network and service interruptions.
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
##### Multicurrency #####
|
||||
Since API v2.0 it is now possible to create non-EUR payments for your customers.
|
||||
A full list of available currencies can be found [in our documentation](https://docs.mollie.com/docs/multicurrency).
|
||||
|
||||
```php
|
||||
$payment = $mollie->payments->create([
|
||||
"amount" => [
|
||||
"currency" => "USD",
|
||||
"value" => "10.00"
|
||||
],
|
||||
//...
|
||||
]);
|
||||
```
|
||||
_After creation, the `settlementAmount` will contain the EUR amount that will be settled on your account._
|
||||
|
||||
##### Create fully integrated iDEAL payments #####
|
||||
To fully integrate iDEAL payments on your website, follow these additional steps:
|
||||
|
||||
1. Retrieve the list of issuers (banks) that support iDEAL.
|
||||
|
||||
```php
|
||||
$method = $mollie->methods->get(\Mollie\Api\Types\PaymentMethod::Ideal, ["include" => "issuers"]);
|
||||
```
|
||||
|
||||
Use the `$method->issuers` list to let the customer pick their preferred issuer.
|
||||
|
||||
_`$method->issuers` will be a list of objects. Use the property `$id` of this object in the
|
||||
API call, and the property `$name` for displaying the issuer to your customer._
|
||||
|
||||
2. Create a payment with the selected issuer:
|
||||
|
||||
```php
|
||||
$payment = $mollie->payments->create([
|
||||
"amount" => [
|
||||
"currency" => "EUR",
|
||||
"value" => "10.00"
|
||||
],
|
||||
"description" => "My first API payment",
|
||||
"redirectUrl" => "https://webshop.example.org/order/12345/",
|
||||
"webhookUrl" => "https://webshop.example.org/mollie-webhook/",
|
||||
"method" => \Mollie\Api\Types\PaymentMethod::Ideal,
|
||||
"issuer" => $selectedIssuerId, // e.g. "ideal_INGBNL2A"
|
||||
]);
|
||||
```
|
||||
|
||||
_The `_links` property of the `$payment` object will contain an object `checkout` with a `href` property, which is a URL that points directly to the online banking environment of the selected issuer.
|
||||
A short way of retrieving this URL can be achieved by using the `$payment->getCheckoutUrl()`._
|
||||
|
||||
For a more in-depth example, see [Example - iDEAL payment](./recipes/payments/create-ideal-payment.md).
|
||||
|
||||
#### Retrieving Payments ####
|
||||
**[Retrieve Payment Documentation](https://docs.mollie.com/reference/v2/payments-api/get-payment)**
|
||||
|
||||
We can use the `$payment->id` to retrieve a payment and check if the payment `isPaid`.
|
||||
|
||||
```php
|
||||
$payment = $mollie->payments->get($payment->id);
|
||||
|
||||
if ($payment->isPaid())
|
||||
{
|
||||
echo "Payment received.";
|
||||
}
|
||||
```
|
||||
|
||||
Or retrieve a collection of payments.
|
||||
|
||||
```php
|
||||
$payments = $mollie->payments->page();
|
||||
```
|
||||
|
||||
For an extensive example of listing payments with the details and status, see [Example - List Payments](./recipes/payments/list-payments.md).
|
||||
|
||||
#### Refunding payments ####
|
||||
**[Refund Payment Documentation](https://docs.mollie.com/reference/v2/refunds-api/create-payment-refund)**
|
||||
|
||||
Our API provides support for refunding payments. It's important to note that there is no confirmation step, and all refunds are immediate and final. Refunds are available for all payment methods except for paysafecard and gift cards.
|
||||
|
||||
```php
|
||||
$payment = $mollie->payments->get($payment->id);
|
||||
|
||||
// Refund € 2 of this payment
|
||||
$refund = $payment->refund([
|
||||
"amount" => [
|
||||
"currency" => "EUR",
|
||||
"value" => "2.00"
|
||||
]
|
||||
]);
|
||||
```
|
||||
|
||||
#### Payment webhook ####
|
||||
When the payment status changes, the `webhookUrl` you specified during payment creation will be called. You can use the `id` from the POST parameters to check the status and take appropriate actions.
|
||||
For more details, refer to [Example - Webhook](./recipes/payments/handle-webhook.md).
|
||||
|
||||
For a working example, see [Example - Refund payment](./recipes/payments/refund-payment.md).
|
||||
@@ -0,0 +1,33 @@
|
||||
# Mollie API PHP Recipes
|
||||
|
||||
This directory contains recipes for common use cases with the Mollie API PHP client. Each recipe provides a practical example of how to use the API client for a specific task.
|
||||
|
||||
## Structure
|
||||
|
||||
The recipes are organized by resource type:
|
||||
- `payments/` - Payment-related operations (create, update, refund, etc.)
|
||||
- `customers/` - Customer management
|
||||
- `mandates/` - Mandate operations
|
||||
- `subscriptions/` - Subscription handling
|
||||
- `captures/` - Payment capture operations
|
||||
- `chargebacks/` - Chargeback handling
|
||||
- `refunds/` - Refund operations
|
||||
- `connect-balance-transfers/` - Connect balance transfer operations
|
||||
- `webhooks/` - Webhook management and events
|
||||
- `money/` - `Money` value object recipes (custom factories via Macroable)
|
||||
|
||||
Each recipe includes:
|
||||
- Complete code example
|
||||
- Example response fields
|
||||
- Additional notes and considerations
|
||||
|
||||
## Getting Started
|
||||
|
||||
Before using any recipe, make sure you have properly initialized the API client:
|
||||
|
||||
```php
|
||||
use Mollie\Api\MollieApiClient;
|
||||
|
||||
$mollie = new MollieApiClient;
|
||||
$mollie->setApiKey('test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM');
|
||||
```
|
||||
@@ -0,0 +1,82 @@
|
||||
# List Account Capabilities
|
||||
|
||||
How to retrieve the capabilities of a Mollie account using OAuth.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\ListCapabilitiesRequest;
|
||||
use Mollie\Api\Http\Requests\GetCapabilityRequest;
|
||||
use Mollie\Api\Types\CapabilityStatus;
|
||||
|
||||
try {
|
||||
// Initialize the Mollie client with your OAuth access token
|
||||
$mollie = new \Mollie\Api\MollieApiClient();
|
||||
$mollie->setAccessToken('access_xxx');
|
||||
|
||||
// List all capabilities
|
||||
$capabilities = $mollie->send(
|
||||
new ListCapabilitiesRequest()
|
||||
);
|
||||
|
||||
foreach ($capabilities as $capability) {
|
||||
$status = $capability->status instanceof CapabilityStatus
|
||||
? $capability->status->value
|
||||
: $capability->status;
|
||||
|
||||
echo "Capability: {$capability->name}\n";
|
||||
echo "- Status: {$status}\n";
|
||||
|
||||
if ($capability->statusReason !== null) {
|
||||
echo "- Status reason: {$capability->statusReason}\n";
|
||||
}
|
||||
|
||||
echo "\n";
|
||||
}
|
||||
|
||||
// Get a specific capability
|
||||
$capability = $mollie->send(
|
||||
new GetCapabilityRequest(
|
||||
name: 'payments'
|
||||
)
|
||||
);
|
||||
|
||||
$status = $capability->status instanceof CapabilityStatus
|
||||
? $capability->status->value
|
||||
: $capability->status;
|
||||
|
||||
echo "Payment capability status: {$status}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$capability->name; // "payments"
|
||||
$capability->requirements; // Requirements that still need attention
|
||||
$capability->status; // CapabilityStatus case, or an unknown raw string
|
||||
$capability->statusReason; // Status reason, or null when no reason applies
|
||||
```
|
||||
|
||||
## Available Capabilities
|
||||
|
||||
- `payments` - Accept payments from your customers
|
||||
- `refunds` - Refund payments to your customers
|
||||
- `settlements` - Receive settlements in your bank account
|
||||
- `chargebacks` - Handle chargebacks from your customers
|
||||
- `onboarding` - Complete onboarding to activate your account
|
||||
- `organizations` - Create and manage organizations
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- You need an OAuth access token to access capabilities
|
||||
- The status indicates whether a capability is available for use:
|
||||
- `unrequested`: The capability has not been requested
|
||||
- `enabled`: The capability is enabled and ready to use
|
||||
- `pending`: The capability is being reviewed or requires additional information
|
||||
- `disabled`: The capability is disabled or not available
|
||||
- Some capabilities may require additional verification or documentation
|
||||
- Capabilities vary by country and account type
|
||||
- Check capabilities before using certain features to ensure they are available
|
||||
Vendored
+151
@@ -0,0 +1,151 @@
|
||||
# Create a Connect Balance Transfer
|
||||
|
||||
How to create a balance transfer between two connected Mollie balances using the API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Data\TransferParty;
|
||||
use Mollie\Api\Http\Requests\CreateConnectBalanceTransferRequest;
|
||||
use Mollie\Api\Types\ConnectBalanceTransferCategory;
|
||||
|
||||
try {
|
||||
// Initialize the Mollie client with your OAuth access token
|
||||
$mollie = new \Mollie\Api\MollieApiClient();
|
||||
$mollie->setAccessToken('access_xxx');
|
||||
|
||||
// Create a balance transfer
|
||||
$balanceTransfer = $mollie->send(
|
||||
new CreateConnectBalanceTransferRequest(
|
||||
amount: new Money(
|
||||
currency: 'EUR',
|
||||
value: '100.00'
|
||||
),
|
||||
description: 'Transfer from balance A to balance B',
|
||||
source: new TransferParty(
|
||||
id: 'org_12345678',
|
||||
description: 'Payment from Organization A'
|
||||
),
|
||||
destination: new TransferParty(
|
||||
id: 'org_87654321',
|
||||
description: 'Payment to Organization B'
|
||||
),
|
||||
category: ConnectBalanceTransferCategory::ManualCorrection
|
||||
)
|
||||
);
|
||||
|
||||
echo "Balance transfer created: {$balanceTransfer->id}\n";
|
||||
echo "Amount: {$balanceTransfer->amount->currency} {$balanceTransfer->amount->value}\n";
|
||||
echo "Status: Transfer initiated\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Using Endpoint Collections (Legacy Style)
|
||||
|
||||
```php
|
||||
try {
|
||||
// Create a balance transfer using endpoint collections
|
||||
$balanceTransfer = $mollie->connectBalanceTransfers->create([
|
||||
'amount' => [
|
||||
'currency' => 'EUR',
|
||||
'value' => '100.00'
|
||||
],
|
||||
'description' => 'Transfer from balance A to balance B',
|
||||
'source' => [
|
||||
'type' => 'organization',
|
||||
'id' => 'org_12345678',
|
||||
'description' => 'Payment from Organization A'
|
||||
],
|
||||
'destination' => [
|
||||
'type' => 'organization',
|
||||
'id' => 'org_87654321',
|
||||
'description' => 'Payment to Organization B'
|
||||
],
|
||||
'category' => 'manual_correction'
|
||||
]);
|
||||
|
||||
echo "Balance transfer created: {$balanceTransfer->id}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$balanceTransfer->id; // "cbt_4KgGJJSZpH"
|
||||
$balanceTransfer->resource; // "connect-balance-transfer"
|
||||
$balanceTransfer->amount->currency; // "EUR"
|
||||
$balanceTransfer->amount->value; // "100.00"
|
||||
$balanceTransfer->description; // "Transfer from balance A to balance B"
|
||||
$balanceTransfer->status; // "created", "failed", "succeeded"
|
||||
$balanceTransfer->statusReason; // Object with status reason (if applicable)
|
||||
$balanceTransfer->category; // "manual_correction", "purchase", "refund", etc.
|
||||
$balanceTransfer->source->type; // "organization"
|
||||
$balanceTransfer->source->id; // "org_12345678"
|
||||
$balanceTransfer->source->description; // "Payment from Organization A"
|
||||
$balanceTransfer->destination->type; // "organization"
|
||||
$balanceTransfer->destination->id; // "org_87654321"
|
||||
$balanceTransfer->destination->description; // "Payment to Organization B"
|
||||
$balanceTransfer->executedAt; // "2023-12-25T10:31:00+00:00" (null if not executed)
|
||||
$balanceTransfer->mode; // "live" or "test"
|
||||
$balanceTransfer->createdAt; // "2023-12-25T10:30:54+00:00"
|
||||
```
|
||||
|
||||
## Transfer Status
|
||||
|
||||
The transfer status indicates the current state of the transfer:
|
||||
|
||||
```php
|
||||
// Check transfer status
|
||||
if ($balanceTransfer->status === 'succeeded') {
|
||||
echo "Transfer completed successfully\n";
|
||||
echo "Executed at: {$balanceTransfer->executedAt}\n";
|
||||
} elseif ($balanceTransfer->status === 'failed') {
|
||||
echo "Transfer failed\n";
|
||||
if ($balanceTransfer->statusReason) {
|
||||
echo "Reason: " . json_encode($balanceTransfer->statusReason) . "\n";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Transfer Categories
|
||||
|
||||
Different transfer categories may have different fees:
|
||||
|
||||
- `invoice_collection` - Collecting invoice payments
|
||||
- `purchase` - Purchase-related transfers
|
||||
- `chargeback` - Chargeback transfers
|
||||
- `refund` - Refund transfers
|
||||
- `service_penalty` - Service penalty fees
|
||||
- `discount_compensation` - Discount compensations
|
||||
- `manual_correction` - Manual corrections
|
||||
- `other_fee` - Other fees
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- **OAuth Required**: You need an OAuth access token to create balance transfers. API keys are not supported for this endpoint.
|
||||
- **Sub-merchant consent**: You must have a documented consent from your sub-merchants authorizing balance movements.
|
||||
- **Balance Ownership**: You can only transfer funds between balances that belong to organizations connected through your OAuth app.
|
||||
- **Transfer Speed**: Balance transfers are processed immediately. The funds are moved instantly between the balances.
|
||||
- **Status Tracking**: Monitor the `status` field to track transfer completion. Check `executedAt` for the exact completion time.
|
||||
- **Currency Requirements**:
|
||||
- Both balances must use the same currency
|
||||
- The transfer amount must match the balance currency
|
||||
- **Balance Validation**:
|
||||
- The source balance must have sufficient available funds
|
||||
- Both balances must be active and operational
|
||||
- **Use Cases**:
|
||||
- Moving funds between merchant balances in a marketplace
|
||||
- Redistributing funds across different connected accounts
|
||||
- Managing liquidity between multiple balances
|
||||
- **Permissions**: Your OAuth app must have the appropriate scopes to access and transfer between the balances
|
||||
- **Idempotency**: Consider using idempotency keys when creating transfers to prevent duplicate transfers in case of network issues
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [List Connect Balance Transfers](list-balance-transfers.md)
|
||||
- [Get Connect Balance Transfer](get-balance-transfer.md)
|
||||
Vendored
+105
@@ -0,0 +1,105 @@
|
||||
# Get a Connect Balance Transfer
|
||||
|
||||
How to retrieve details of a specific connect balance transfer using the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetConnectBalanceTransferRequest;
|
||||
|
||||
try {
|
||||
// Initialize the Mollie client with your OAuth access token
|
||||
$mollie = new \Mollie\Api\MollieApiClient();
|
||||
$mollie->setAccessToken('access_xxx');
|
||||
|
||||
// Get a specific balance transfer
|
||||
$balanceTransfer = $mollie->send(
|
||||
new GetConnectBalanceTransferRequest(
|
||||
id: 'cbt_4KgGJJSZpH'
|
||||
)
|
||||
);
|
||||
|
||||
echo "Balance Transfer {$balanceTransfer->id}:\n";
|
||||
echo "- Amount: {$balanceTransfer->amount->currency} {$balanceTransfer->amount->value}\n";
|
||||
echo "- Description: {$balanceTransfer->description}\n";
|
||||
echo "- From: {$balanceTransfer->source->balanceId}\n";
|
||||
echo "- To: {$balanceTransfer->destination->balanceId}\n";
|
||||
echo "- Created: {$balanceTransfer->createdAt}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Using Endpoint Collections (Legacy Style)
|
||||
|
||||
```php
|
||||
try {
|
||||
// Get a balance transfer using endpoint collections
|
||||
$balanceTransfer = $mollie->connectBalanceTransfers->get('cbt_4KgGJJSZpH');
|
||||
|
||||
echo "Transfer amount: {$balanceTransfer->amount->value}\n";
|
||||
echo "Transfer description: {$balanceTransfer->description}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$balanceTransfer->id; // "cbt_4KgGJJSZpH"
|
||||
$balanceTransfer->resource; // "connect-balance-transfer"
|
||||
$balanceTransfer->amount->currency; // "EUR"
|
||||
$balanceTransfer->amount->value; // "100.00"
|
||||
$balanceTransfer->description; // "Transfer from balance A to balance B"
|
||||
$balanceTransfer->status; // "created", "failed", "succeeded"
|
||||
$balanceTransfer->statusReason; // Object with status reason (if applicable)
|
||||
$balanceTransfer->category; // "manual_correction", "purchase", "refund", etc.
|
||||
$balanceTransfer->source->type; // "organization"
|
||||
$balanceTransfer->source->id; // "org_12345678"
|
||||
$balanceTransfer->source->description; // "Payment from Organization A"
|
||||
$balanceTransfer->destination->type; // "organization"
|
||||
$balanceTransfer->destination->id; // "org_87654321"
|
||||
$balanceTransfer->destination->description; // "Payment to Organization B"
|
||||
$balanceTransfer->executedAt; // "2023-12-25T10:31:00+00:00" (null if not executed)
|
||||
$balanceTransfer->mode; // "live" or "test"
|
||||
$balanceTransfer->createdAt; // "2023-12-25T10:30:54+00:00"
|
||||
$balanceTransfer->_links; // Object containing relevant URLs
|
||||
```
|
||||
|
||||
## Transfer Party Details
|
||||
|
||||
Access the transfer party information:
|
||||
|
||||
```php
|
||||
// Source party details
|
||||
echo "Source Organization:\n";
|
||||
echo "- Type: {$balanceTransfer->source->type}\n"; // "organization"
|
||||
echo "- ID: {$balanceTransfer->source->id}\n"; // Organization token
|
||||
echo "- Description: {$balanceTransfer->source->description}\n";
|
||||
|
||||
// Destination party details
|
||||
echo "Destination Organization:\n";
|
||||
echo "- Type: {$balanceTransfer->destination->type}\n";
|
||||
echo "- ID: {$balanceTransfer->destination->id}\n";
|
||||
echo "- Description: {$balanceTransfer->destination->description}\n";
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- **OAuth Required**: You need an OAuth access token to retrieve balance transfer details
|
||||
- **Access Control**: You can only retrieve transfers involving balances accessible through your OAuth app
|
||||
- **Transfer Tracking**: Use the transfer ID to track and audit balance movements
|
||||
- **Embedded Data**: The response may include embedded balance details for both source and destination balances
|
||||
- **Links**: The `_links` object contains URLs to related resources:
|
||||
- `self`: Link to this balance transfer
|
||||
- `documentation`: Link to API documentation
|
||||
- **Audit Trail**: Store transfer IDs in your system for reconciliation and reporting purposes
|
||||
- **Error Handling**:
|
||||
- Returns 404 if the transfer ID doesn't exist
|
||||
- Returns 403 if you don't have permission to access this transfer
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [Create Connect Balance Transfer](create-balance-transfer.md)
|
||||
- [List Connect Balance Transfers](list-balance-transfers.md)
|
||||
Vendored
+177
@@ -0,0 +1,177 @@
|
||||
# List Connect Balance Transfers
|
||||
|
||||
How to retrieve a list of all connect balance transfers using the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\ListConnectBalanceTransfersRequest;
|
||||
|
||||
try {
|
||||
// Initialize the Mollie client with your OAuth access token
|
||||
$mollie = new \Mollie\Api\MollieApiClient();
|
||||
$mollie->setAccessToken('access_xxx');
|
||||
|
||||
// List all balance transfers
|
||||
$balanceTransfers = $mollie->send(
|
||||
new ListConnectBalanceTransfersRequest()
|
||||
);
|
||||
|
||||
foreach ($balanceTransfers as $transfer) {
|
||||
echo "Transfer {$transfer->id}:\n";
|
||||
echo "- Amount: {$transfer->amount->currency} {$transfer->amount->value}\n";
|
||||
echo "- Description: {$transfer->description}\n";
|
||||
echo "- From: {$transfer->source->balanceId}\n";
|
||||
echo "- To: {$transfer->destination->balanceId}\n";
|
||||
echo "- Created: {$transfer->createdAt}\n\n";
|
||||
}
|
||||
|
||||
// Get the next page if available
|
||||
if ($balanceTransfers->hasNext()) {
|
||||
$nextPage = $balanceTransfers->next();
|
||||
// Process next page...
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## With Pagination Parameters
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\ListConnectBalanceTransfersRequest;
|
||||
|
||||
try {
|
||||
// List balance transfers with pagination
|
||||
$balanceTransfers = $mollie->send(
|
||||
new ListConnectBalanceTransfersRequest(
|
||||
from: 'cbt_8KhHNOSdpL', // Start from this ID
|
||||
limit: 50, // Limit to 50 results
|
||||
sort: 'createdAt' // Sort by creation date
|
||||
)
|
||||
);
|
||||
|
||||
foreach ($balanceTransfers as $transfer) {
|
||||
// Process each transfer...
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Using Iterator for All Transfers
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\ListConnectBalanceTransfersRequest;
|
||||
|
||||
try {
|
||||
// Use iterator to automatically handle pagination
|
||||
$request = new ListConnectBalanceTransfersRequest();
|
||||
|
||||
$allTransfers = $mollie->send($request->useIterator());
|
||||
|
||||
foreach ($allTransfers as $transfer) {
|
||||
echo "Transfer {$transfer->id}: ";
|
||||
echo "{$transfer->amount->currency} {$transfer->amount->value}\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Using Endpoint Collections (Legacy Style)
|
||||
|
||||
```php
|
||||
try {
|
||||
// List balance transfers using endpoint collections
|
||||
$balanceTransfers = $mollie->connectBalanceTransfers->page();
|
||||
|
||||
foreach ($balanceTransfers as $transfer) {
|
||||
echo "Transfer: {$transfer->description}\n";
|
||||
echo "Amount: {$transfer->amount->value}\n\n";
|
||||
}
|
||||
|
||||
// Use iterator for automatic pagination
|
||||
foreach ($mollie->connectBalanceTransfers->iterator() as $transfer) {
|
||||
// Process each transfer across all pages...
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
// Collection properties
|
||||
$balanceTransfers->count; // Number of transfers in current page
|
||||
$balanceTransfers->_links; // Pagination links
|
||||
|
||||
// Individual transfer properties
|
||||
$transfer->id; // "cbt_4KgGJJSZpH"
|
||||
$transfer->resource; // "connect-balance-transfer"
|
||||
$transfer->amount->currency; // "EUR"
|
||||
$transfer->amount->value; // "100.00"
|
||||
$transfer->description; // "Transfer from balance A to balance B"
|
||||
$transfer->status; // "created", "failed", "succeeded"
|
||||
$transfer->category; // "manual_correction", "purchase", "refund", etc.
|
||||
$transfer->source->type; // "organization"
|
||||
$transfer->source->id; // "org_12345678"
|
||||
$transfer->source->description; // "Payment from Organization A"
|
||||
$transfer->destination->type; // "organization"
|
||||
$transfer->destination->id; // "org_87654321"
|
||||
$transfer->destination->description; // "Payment to Organization B"
|
||||
$transfer->executedAt; // "2023-12-25T10:31:00+00:00" (null if not executed)
|
||||
$transfer->mode; // "live" or "test"
|
||||
$transfer->createdAt; // "2023-12-25T10:30:54+00:00"
|
||||
```
|
||||
|
||||
## Pagination Methods
|
||||
|
||||
```php
|
||||
// Check if there's a next page
|
||||
if ($balanceTransfers->hasNext()) {
|
||||
$nextPage = $balanceTransfers->next();
|
||||
}
|
||||
|
||||
// Check if there's a previous page
|
||||
if ($balanceTransfers->hasPrevious()) {
|
||||
$previousPage = $balanceTransfers->previous();
|
||||
}
|
||||
|
||||
// Get auto-iterator for all transfers
|
||||
$iterator = $balanceTransfers->getAutoIterator();
|
||||
foreach ($iterator as $transfer) {
|
||||
// Processes all transfers across all pages automatically
|
||||
}
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- **OAuth Required**: You need an OAuth access token to list balance transfers
|
||||
- **Access Scope**: The list includes only transfers involving balances accessible through your OAuth app
|
||||
- **Pagination**:
|
||||
- Results are paginated with a default limit
|
||||
- Use `from` parameter to start from a specific transfer ID
|
||||
- Use `limit` to control the number of results per page (max 250)
|
||||
- **Sorting**:
|
||||
- Transfers are returned in descending order by creation date (newest first)
|
||||
- Use the `sort` parameter to customize ordering
|
||||
- **Filtering**: Currently, there are no filter parameters available. All accessible transfers are returned.
|
||||
- **Performance**:
|
||||
- Use the iterator for processing large numbers of transfers
|
||||
- The iterator automatically handles pagination
|
||||
- Set appropriate limits to balance between API calls and memory usage
|
||||
- **Iteration Direction**:
|
||||
- By default, iteration goes forward (newest to oldest)
|
||||
- Set `iterateBackwards: true` to reverse the direction
|
||||
- **Use Cases**:
|
||||
- Financial reporting and reconciliation
|
||||
- Audit trails for balance movements
|
||||
- Analyzing transfer patterns
|
||||
- Monitoring platform activity
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [Create Connect Balance Transfer](create-balance-transfer.md)
|
||||
- [Get Connect Balance Transfer](get-balance-transfer.md)
|
||||
@@ -0,0 +1,142 @@
|
||||
# Customer Payments
|
||||
|
||||
How to create and manage payments for customers using the Mollie API.
|
||||
|
||||
## First Payment (For Recurring)
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\CreateCustomerPaymentRequest;
|
||||
use Mollie\Api\Types\PaymentStatus;
|
||||
use Mollie\Api\Types\SequenceType;
|
||||
|
||||
try {
|
||||
// Create the first payment for a customer
|
||||
$payment = $mollie->send(
|
||||
new CreateCustomerPaymentRequest(
|
||||
customerId: 'cst_8wmqcHMN4U',
|
||||
description: 'First payment - Order #12345',
|
||||
amount: Money::euro('29.95'), // Using convenience method
|
||||
redirectUrl: 'https://example.com/payments/return?order_id=12345',
|
||||
webhookUrl: 'https://example.com/payments/webhook',
|
||||
metadata: [
|
||||
'order_id' => '12345'
|
||||
],
|
||||
sequenceType: SequenceType::First->value // This creates a mandate for future payments
|
||||
)
|
||||
);
|
||||
|
||||
// Redirect the customer to complete the payment
|
||||
header('Location: ' . $payment->getCheckoutUrl(), true, 303);
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Recurring Payment
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\CreateCustomerPaymentRequest;
|
||||
use Mollie\Api\Types\SequenceType;
|
||||
|
||||
try {
|
||||
// Create a recurring payment using the mandate
|
||||
$payment = $mollie->send(
|
||||
new CreateCustomerPaymentRequest(
|
||||
customerId: 'cst_8wmqcHMN4U',
|
||||
description: 'Recurring payment - Order #12346',
|
||||
amount: Money::euro('29.95'), // Using convenience method
|
||||
webhookUrl: 'https://example.com/payments/webhook',
|
||||
metadata: [
|
||||
'order_id' => '12346'
|
||||
],
|
||||
sequenceType: SequenceType::Recurring->value // This uses the mandate created by the first payment
|
||||
)
|
||||
);
|
||||
|
||||
// The payment will be either pending or paid immediately
|
||||
$status = $payment->status instanceof PaymentStatus
|
||||
? $payment->status->value
|
||||
: $payment->status;
|
||||
|
||||
echo "Payment status: {$status}\n";
|
||||
echo "Used mandate: " . ($payment->mandateId ?? 'not assigned') . "\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## List Customer Payments
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaginatedCustomerPaymentsRequest;
|
||||
use Mollie\Api\Resources\PaymentCollection;
|
||||
use Mollie\Api\Types\PaymentStatus;
|
||||
|
||||
try {
|
||||
// Get all payments for a customer
|
||||
/** @var PaymentCollection */
|
||||
$payments = $mollie->send(
|
||||
new GetPaginatedCustomerPaymentsRequest(
|
||||
customerId: 'cst_8wmqcHMN4U'
|
||||
)
|
||||
);
|
||||
|
||||
foreach ($payments as $payment) {
|
||||
$status = $payment->status instanceof PaymentStatus
|
||||
? $payment->status->value
|
||||
: $payment->status;
|
||||
|
||||
echo "Payment {$payment->id}:\n";
|
||||
echo "- Description: {$payment->description}\n";
|
||||
echo "- Amount: {$payment->amount->currency} {$payment->amount->value}\n";
|
||||
echo "- Status: {$status}\n";
|
||||
|
||||
if ($payment->hasRefunds()) {
|
||||
echo "- Has been (partially) refunded\n";
|
||||
}
|
||||
|
||||
if ($payment->hasChargebacks()) {
|
||||
echo "- Has been charged back\n";
|
||||
}
|
||||
|
||||
echo "\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Payment Response
|
||||
|
||||
```php
|
||||
$payment->id; // "tr_7UhSN1zuXS"
|
||||
$payment->customerId; // "cst_8wmqcHMN4U"
|
||||
$payment->mode; // "live" or "test"
|
||||
$payment->description; // "Order #12345"
|
||||
$payment->metadata; // Object containing custom metadata
|
||||
$payment->status; // PaymentStatus case, or an unknown raw string
|
||||
$payment->isCancelable; // Whether the payment can be canceled, or null
|
||||
$payment->sequenceType; // SequenceType case, unknown raw string, or null
|
||||
$payment->redirectUrl; // URL to redirect the customer to
|
||||
$payment->webhookUrl; // URL for webhook notifications
|
||||
$payment->createdAt; // "2024-02-24T12:13:14+00:00"
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- First create a customer before creating customer payments
|
||||
- The first payment creates a mandate for future recurring payments
|
||||
- Sequence types:
|
||||
- `first`: Creates a mandate for future payments
|
||||
- `recurring`: Uses an existing mandate
|
||||
- Recurring payments:
|
||||
- Don't need a `redirectUrl` as they use the stored mandate
|
||||
- Will be executed immediately without customer interaction
|
||||
- May still be pending depending on the payment method
|
||||
- The mandate status determines if recurring payments can be created
|
||||
- Store the payment ID and status in your database
|
||||
- Always implement proper webhook handling
|
||||
- Available payment methods may differ for first and recurring payments
|
||||
- Some payment methods don't support recurring payments
|
||||
@@ -0,0 +1,125 @@
|
||||
# Manage Customers
|
||||
|
||||
How to create, update, and delete customers using the Mollie API.
|
||||
|
||||
## Create a Customer
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\CreateCustomerRequest;
|
||||
|
||||
try {
|
||||
// Create a new customer
|
||||
$customer = $mollie->send(
|
||||
new CreateCustomerRequest(
|
||||
name: 'Luke Skywalker',
|
||||
email: 'luke@example.com',
|
||||
locale: 'en_US',
|
||||
metadata: [
|
||||
'isJedi' => true
|
||||
]
|
||||
)
|
||||
);
|
||||
|
||||
echo "New customer created: {$customer->id}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Update a Customer
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetCustomerRequest;
|
||||
use Mollie\Api\Http\Requests\UpdateCustomerRequest;
|
||||
|
||||
try {
|
||||
// First retrieve the customer you want to update
|
||||
$customer = $mollie->send(
|
||||
new GetCustomerRequest(
|
||||
id: 'cst_8wmqcHMN4U'
|
||||
)
|
||||
);
|
||||
|
||||
// Update specific customer fields
|
||||
$customer = $mollie->send(
|
||||
new UpdateCustomerRequest(
|
||||
id: $customer->id,
|
||||
name: 'Luke Sky',
|
||||
email: 'luke@example.com',
|
||||
locale: 'en_US',
|
||||
metadata: [
|
||||
'isJedi' => true
|
||||
]
|
||||
// Fields we don't specify will keep their current values
|
||||
)
|
||||
);
|
||||
|
||||
echo "Customer updated: {$customer->name}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Delete a Customer
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\DeleteCustomerRequest;
|
||||
|
||||
try {
|
||||
// Delete a customer
|
||||
$mollie->send(
|
||||
new DeleteCustomerRequest(
|
||||
id: 'cst_8wmqcHMN4U'
|
||||
)
|
||||
);
|
||||
|
||||
echo "Customer deleted\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$customer->id; // "cst_8wmqcHMN4U"
|
||||
$customer->name; // "Luke Skywalker"
|
||||
$customer->email; // "luke@example.com"
|
||||
$customer->locale; // "en_US"
|
||||
$customer->metadata; // Object containing custom metadata
|
||||
$customer->mode; // "live" or "test"
|
||||
$customer->createdAt; // "2024-02-24T12:13:14+00:00"
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Customers are used to store recurring payment details
|
||||
- Each customer can have multiple mandates for different payment methods
|
||||
- The customer ID is required for:
|
||||
- Creating recurring payments
|
||||
- Creating subscriptions
|
||||
- Retrieving payment history
|
||||
- Customer data should be kept in sync with your own database
|
||||
- Available locales:
|
||||
- `en_US` English (US)
|
||||
- `en_GB` English (UK)
|
||||
- `nl_NL` Dutch (Netherlands)
|
||||
- `nl_BE` Dutch (Belgium)
|
||||
- `fr_FR` French (France)
|
||||
- `fr_BE` French (Belgium)
|
||||
- `de_DE` German (Germany)
|
||||
- `de_AT` German (Austria)
|
||||
- `de_CH` German (Switzerland)
|
||||
- `es_ES` Spanish (Spain)
|
||||
- `ca_ES` Catalan (Spain)
|
||||
- `pt_PT` Portuguese (Portugal)
|
||||
- `it_IT` Italian (Italy)
|
||||
- `nb_NO` Norwegian (Norway)
|
||||
- `sv_SE` Swedish (Sweden)
|
||||
- `fi_FI` Finnish (Finland)
|
||||
- `da_DK` Danish (Denmark)
|
||||
- `is_IS` Icelandic (Iceland)
|
||||
- `hu_HU` Hungarian (Hungary)
|
||||
- `pl_PL` Polish (Poland)
|
||||
- `lv_LV` Latvian (Latvia)
|
||||
- `lt_LT` Lithuanian (Lithuania)
|
||||
@@ -0,0 +1,102 @@
|
||||
# List Mollie Invoices
|
||||
|
||||
How to retrieve your Mollie invoices using the API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaginatedInvoiceRequest;
|
||||
use Mollie\Api\Types\InvoiceStatus;
|
||||
|
||||
try {
|
||||
// Initialize with OAuth (required for invoices)
|
||||
$mollie = new \Mollie\Api\MollieApiClient();
|
||||
$mollie->setAccessToken('access_xxx');
|
||||
|
||||
// Get all invoices
|
||||
$response = $mollie->send(
|
||||
new GetPaginatedInvoiceRequest()
|
||||
);
|
||||
|
||||
foreach ($response as $invoice) {
|
||||
$status = $invoice->status instanceof InvoiceStatus
|
||||
? $invoice->status->value
|
||||
: ($invoice->status ?? 'not available');
|
||||
|
||||
echo "Invoice {$invoice->reference}:\n";
|
||||
echo "- Status: {$status}\n";
|
||||
echo "- Issued: " . ($invoice->issuedAt ?? 'not issued') . "\n";
|
||||
echo "- Paid: " . ($invoice->paidAt ?? 'not paid') . "\n";
|
||||
echo "- Due: " . ($invoice->dueAt ?? 'not available') . "\n\n";
|
||||
|
||||
echo "Lines:\n";
|
||||
if ($invoice->lines !== null) {
|
||||
foreach ($invoice->lines as $line) {
|
||||
echo "- {$line->description}\n";
|
||||
echo " Period: {$line->period}\n";
|
||||
echo " Count: {$line->count}\n";
|
||||
echo " VAT: {$line->vatPercentage}%\n";
|
||||
echo " Amount: {$line->amount->currency} {$line->amount->value}\n\n";
|
||||
}
|
||||
}
|
||||
|
||||
echo "Totals:\n";
|
||||
foreach ([
|
||||
'Net' => $invoice->netAmount,
|
||||
'VAT' => $invoice->vatAmount,
|
||||
'Gross' => $invoice->grossAmount,
|
||||
] as $label => $amount) {
|
||||
if ($amount !== null) {
|
||||
echo "- {$label}: {$amount->currency} {$amount->value}\n";
|
||||
}
|
||||
}
|
||||
echo "\n";
|
||||
|
||||
if (isset($invoice->_links->pdf->href)) {
|
||||
echo "PDF: {$invoice->_links->pdf->href}\n";
|
||||
}
|
||||
|
||||
echo "\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$invoice->id; // "inv_xBEbP9rvAq"
|
||||
$invoice->reference; // "2024.10000"
|
||||
$invoice->vatNumber; // "NL123456789B01"
|
||||
$invoice->status; // InvoiceStatus case, unknown raw string, or null
|
||||
$invoice->issuedAt; // Issue date, or null when omitted
|
||||
$invoice->paidAt; // Payment date, or null when unpaid
|
||||
$invoice->dueAt; // Due date, or null when omitted
|
||||
$invoice->netAmount; // Money object excluding VAT, or null
|
||||
$invoice->vatAmount; // VAT Money object, or null
|
||||
$invoice->grossAmount; // Money object including VAT, or null
|
||||
$invoice->lines; // Array of invoice lines, or null
|
||||
$invoice->_links->pdf->href; // URL to download PDF invoice
|
||||
```
|
||||
|
||||
## Invoice Line Details
|
||||
|
||||
```php
|
||||
$line->period; // "2024-01"
|
||||
$line->description; // "iDEAL transaction fees"
|
||||
$line->count; // 1337
|
||||
$line->vatPercentage; // "21.00"
|
||||
$line->amount; // Object containing line amount
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- OAuth access token is required to access invoices
|
||||
- Invoices are generated monthly for your Mollie account
|
||||
- Each invoice line represents a different type of fee:
|
||||
- Transaction fees per payment method
|
||||
- Refund fees
|
||||
- Chargeback fees
|
||||
- Other service fees
|
||||
- The PDF invoice is available through the `_links.pdf.href` URL
|
||||
@@ -0,0 +1,115 @@
|
||||
# Manage Customer Mandates
|
||||
|
||||
How to create, list, and revoke mandates for recurring payments using the Mollie API.
|
||||
|
||||
## Create a Mandate
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\CreateMandateRequest;
|
||||
use Mollie\Api\Types\MandateMethod;
|
||||
|
||||
try {
|
||||
// Create a SEPA Direct Debit mandate
|
||||
$mandate = $mollie->send(
|
||||
new CreateMandateRequest(
|
||||
customerId: 'cst_8wmqcHMN4U',
|
||||
method: MandateMethod::Directdebit->value,
|
||||
consumerName: 'B. A. Example',
|
||||
consumerAccount: 'NL34ABNA0243341423'
|
||||
)
|
||||
);
|
||||
|
||||
echo "New mandate created: {$mandate->id}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## List Mandates
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaginatedMandateRequest;
|
||||
use Mollie\Api\Types\MandateQuery;
|
||||
use Mollie\Api\Types\MandateStatus;
|
||||
|
||||
try {
|
||||
// List all mandates for a customer
|
||||
$response = $mollie->send(
|
||||
new GetPaginatedMandateRequest(
|
||||
customerId: 'cst_8wmqcHMN4U',
|
||||
scopes: [MandateQuery::SCOPE_CUSTOMER_NOT_PRESENT]
|
||||
)
|
||||
);
|
||||
|
||||
foreach ($response as $mandate) {
|
||||
$status = $mandate->status instanceof MandateStatus
|
||||
? $mandate->status->value
|
||||
: ($mandate->status ?? 'not available');
|
||||
|
||||
echo "Mandate {$mandate->id}:\n";
|
||||
echo "- Method: " . ($mandate->method ?? 'not available') . "\n";
|
||||
echo "- Status: {$status}\n";
|
||||
|
||||
if (isset($mandate->details->consumerName)) {
|
||||
echo "- Consumer: {$mandate->details->consumerName}\n";
|
||||
}
|
||||
|
||||
if (isset($mandate->details->consumerAccount)) {
|
||||
echo "- Account: {$mandate->details->consumerAccount}\n";
|
||||
}
|
||||
|
||||
echo "\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Revoke a Mandate
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\RevokeMandateRequest;
|
||||
|
||||
try {
|
||||
// Revoke a specific mandate
|
||||
$mollie->send(
|
||||
new RevokeMandateRequest(
|
||||
customerId: 'cst_8wmqcHMN4U',
|
||||
mandateId: 'mdt_h3gAaD5zP'
|
||||
)
|
||||
);
|
||||
|
||||
echo "Mandate revoked\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$mandate->id; // "mdt_h3gAaD5zP"
|
||||
$mandate->status; // MandateStatus case, unknown raw string, or null
|
||||
$mandate->method; // Payment method string, or null
|
||||
$mandate->details; // Mandate details object, or null
|
||||
$mandate->customerId; // "cst_8wmqcHMN4U"
|
||||
$mandate->createdAt; // "2024-02-24T12:13:14+00:00"
|
||||
$mandate->signatureDate; // "2024-02-24" (optional)
|
||||
$mandate->mandateReference; // "YOUR-COMPANY-MD13804" (optional)
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Mandates are used for recurring payments
|
||||
- A customer can have multiple mandates
|
||||
- Only valid mandates can be used for payments
|
||||
- Available mandate methods:
|
||||
- `directdebit`: SEPA Direct Debit
|
||||
- `creditcard`: Credit card
|
||||
- Mandate status:
|
||||
- `valid`: The mandate is valid and can be used for payments
|
||||
- `pending`: The mandate is pending and cannot be used yet
|
||||
- `invalid`: The mandate is invalid and cannot be used
|
||||
- Mandates can be filtered by scope when listing:
|
||||
- `MandateQuery::SCOPE_CUSTOMER_PRESENT`
|
||||
- `MandateQuery::SCOPE_CUSTOMER_NOT_PRESENT`
|
||||
@@ -0,0 +1,42 @@
|
||||
# Custom Money factory via Macroable
|
||||
|
||||
How to add your own factory methods to `Money` without subclassing.
|
||||
|
||||
## Why
|
||||
|
||||
`Money` is a `readonly class` in v4, which means you can no longer subclass it with a non-readonly child. Instead, register a **macro** — a closure invoked as a static (or instance) method on `Money`.
|
||||
|
||||
This is how loyalty points, internal credits, or domain-specific shortcuts can live next to the SDK without inheritance.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
|
||||
// Register once during application bootstrap
|
||||
Money::macro('loyaltyPoints', static function (int $points): Money {
|
||||
// 100 points = €1.00
|
||||
return Money::of('EUR')->minorUnits($points);
|
||||
});
|
||||
|
||||
Money::macro('xau', static function (string $value): Money {
|
||||
return new Money(currency: 'XAU', value: $value);
|
||||
});
|
||||
|
||||
// Use anywhere
|
||||
$amount = Money::loyaltyPoints(2500); // €25.00
|
||||
$gold = Money::xau('1.00000'); // 1 troy ounce
|
||||
```
|
||||
|
||||
## Constraints
|
||||
|
||||
- `Money` is `readonly` — macros must **return new instances**, never mutate state.
|
||||
- Calling an undefined static or instance method on `Money` throws `BadMethodCallException` with a clear message (instead of PHP's default fatal error). Catch `Exception`, not `Error`.
|
||||
- Use `Money::hasMacro('loyaltyPoints')` to check before registering twice in tests.
|
||||
- `Money::flushMacros()` clears every registered macro for the class — useful in `tearDown`.
|
||||
|
||||
## Why not subclass?
|
||||
|
||||
In v3 you could `class TaxedMoney extends Money { public string $tax; }`. In v4 the parent is `readonly class`, so the child must also be declared `readonly`, and constructor promotion means the child has to repeat all parent fields. Macros are simpler for the common case of "just add another factory."
|
||||
|
||||
If you need genuinely new state (extra properties), declare your own `readonly final class` rather than extending `Money`.
|
||||
@@ -0,0 +1,120 @@
|
||||
# Create a Client Link
|
||||
|
||||
How to create a client link to onboard new merchants to Mollie through your app.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Owner;
|
||||
use Mollie\Api\Resources\ClientLink;
|
||||
use Mollie\Api\Http\Data\OwnerAddress;
|
||||
use Mollie\Api\Http\Requests\CreateClientLinkRequest;
|
||||
use Mollie\Api\Types\ApprovalPrompt;
|
||||
|
||||
try {
|
||||
// Create a client link for a new merchant
|
||||
/** @var ClientLink $clientLink */
|
||||
$clientLink = $mollie->send(
|
||||
new CreateClientLinkRequest(
|
||||
owner: new Owner(
|
||||
email: 'merchant@example.com',
|
||||
givenName: 'John',
|
||||
familyName: 'Doe',
|
||||
locale: 'en_US'
|
||||
),
|
||||
name: 'Example Store',
|
||||
address: new OwnerAddress(
|
||||
country: 'NL',
|
||||
streetAndNumber: 'Keizersgracht 313',
|
||||
postalCode: '1016 EE',
|
||||
city: 'Amsterdam'
|
||||
),
|
||||
registrationNumber: '30204462',
|
||||
vatNumber: 'NL123456789B01'
|
||||
)
|
||||
);
|
||||
|
||||
// Generate the redirect URL for the merchant
|
||||
$redirectUrl = $clientLink->getRedirectUrl(
|
||||
client_id: 'app_j9Pakf56Ajta6Y65AkdTtAv',
|
||||
state: bin2hex(random_bytes(8)), // Random state to prevent CSRF
|
||||
scopes: [
|
||||
'onboarding.read',
|
||||
'onboarding.write'
|
||||
],
|
||||
approval_prompt: ApprovalPrompt::Force->value // Always show login screen
|
||||
);
|
||||
|
||||
// Redirect the merchant to complete their onboarding
|
||||
header('Location: ' . $redirectUrl, true, 303);
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$clientLink->id; // "csr_wJPGBj7sFr"
|
||||
$clientLink->resource; // "client-link"
|
||||
$clientLink->_links; // \stdClass with the clientLink href
|
||||
```
|
||||
|
||||
`ClientLink` declares only `id` and `_links` (plus `resource` from the base
|
||||
resource). There is no `status`, `createdAt` or `expiresAt` on this resource;
|
||||
build the onboarding URL with `getRedirectUrl()` and track onboarding state
|
||||
through the Onboarding API.
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Client links are used to onboard new merchants to Mollie through your app
|
||||
- The link expires after 24 hours, though the resource does not expose an expiry field
|
||||
- `getRedirectUrl()` takes `client_id`, `state`, `scopes` and `approval_prompt`; `approval_prompt` accepts only `auto` or `force` and throws otherwise
|
||||
- Required merchant information:
|
||||
- Owner details (name, email, locale)
|
||||
- Organization details (name, address)
|
||||
- Registration number (Chamber of Commerce number)
|
||||
- VAT number (if applicable)
|
||||
- The `state` parameter should be:
|
||||
- Random and unique
|
||||
- Stored in your session
|
||||
- Verified when the merchant returns to prevent CSRF attacks
|
||||
- Available scopes (see [Permissions](https://docs.mollie.com/docs/permissions)):
|
||||
- `balances.read`: View the merchant's balances information
|
||||
- `balance-transfers.read`: View the merchant's balance transfers
|
||||
- `balance-transfers.write`: Create balance transfers for the merchant
|
||||
- `customers.read`: View the merchant's customers
|
||||
- `customers.write`: Manage the merchant's customers
|
||||
- `external-accounts.read`: View the merchant's external accounts
|
||||
- `external-accounts.write`: Manage the merchant's external accounts
|
||||
- `invoices.read`: View the merchant's invoices
|
||||
- `mandates.read`: View the merchant's mandates
|
||||
- `mandates.write`: Manage the merchant's mandates
|
||||
- `onboarding.read`: View the merchant's onboarding status
|
||||
- `onboarding.write`: Submit onboarding data for the merchant
|
||||
- `orders.read`: View the merchant's orders
|
||||
- `orders.write`: Manage the merchant's orders
|
||||
- `organizations.read`: View the merchant's organizational details
|
||||
- `organizations.write`: Change the merchant's organizational details
|
||||
- `payment-links.read`: View the merchant's payment links
|
||||
- `payment-links.write`: Create payment links for the merchant
|
||||
- `payments.read`: View the merchant's payments, chargebacks and payment methods
|
||||
- `payments.write`: Create payments for the merchant (added to the merchant's balance)
|
||||
- `persons.read`: View the merchant's persons and stakeholders
|
||||
- `persons.write`: Manage the merchant's persons and stakeholders
|
||||
- `profiles.read`: View the merchant's website profiles
|
||||
- `profiles.write`: Manage the merchant's website profiles
|
||||
- `refunds.read`: View the merchant's refunds
|
||||
- `refunds.write`: Create or cancel refunds
|
||||
- `settlements.read`: View the merchant's settlements
|
||||
- `shipments.read`: View the merchant's order shipments
|
||||
- `shipments.write`: Manage the merchant's order shipments
|
||||
- `subscriptions.read`: View the merchant's subscriptions
|
||||
- `subscriptions.write`: Manage the merchant's subscriptions
|
||||
- `terminals.read`: View the merchant's point-of-sale terminals
|
||||
- `terminals.write`: Manage the merchant's point-of-sale terminals
|
||||
- The merchant will need to:
|
||||
1. Create a Mollie account or log in
|
||||
2. Connect their account to your app
|
||||
3. Complete the onboarding process
|
||||
- You can track the onboarding status through the OAuth APIs
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
# Manage Payment Links
|
||||
|
||||
How to create and list payment links using the Mollie API.
|
||||
|
||||
## Create a Payment Link
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\CreatePaymentLinkRequest;
|
||||
|
||||
try {
|
||||
// Create a payment link. The request takes typed arguments, not an array.
|
||||
$paymentLink = $mollie->send(
|
||||
new CreatePaymentLinkRequest(
|
||||
description: 'Bicycle tires',
|
||||
amount: Money::euro('10.00'),
|
||||
webhookUrl: 'https://example.com/webhook', // optional
|
||||
expiresAt: '2026-01-01T12:00:00' // optional
|
||||
)
|
||||
);
|
||||
|
||||
// getCheckoutUrl() reads $_links->paymentLink and returns null when that
|
||||
// link is absent, so check before redirecting.
|
||||
$checkoutUrl = $paymentLink->getCheckoutUrl();
|
||||
|
||||
if ($checkoutUrl === null) {
|
||||
throw new \RuntimeException("Payment link {$paymentLink->id} has no checkout URL.");
|
||||
}
|
||||
|
||||
header('Location: ' . $checkoutUrl, true, 303);
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## List Payment Links
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaginatedPaymentLinksRequest;
|
||||
|
||||
try {
|
||||
// List all payment links
|
||||
$response = $mollie->send(new GetPaginatedPaymentLinksRequest);
|
||||
|
||||
foreach ($response as $paymentLink) {
|
||||
// PaymentLink has no status field. Derive the state from paidAt,
|
||||
// expiresAt and archived instead.
|
||||
$amount = $paymentLink->amount;
|
||||
|
||||
echo "Payment Link {$paymentLink->id}:\n";
|
||||
echo "- Description: {$paymentLink->description}\n";
|
||||
echo '- Amount: '.($amount === null ? 'open amount' : "{$amount->currency} {$amount->value}")."\n";
|
||||
echo '- Paid: '.($paymentLink->isPaid() ? 'yes' : 'no')."\n";
|
||||
echo '- Archived: '.($paymentLink->archived ? 'yes' : 'no')."\n";
|
||||
echo '- Created: '.($paymentLink->createdAt ?? 'unknown')."\n";
|
||||
echo '- URL: '.($paymentLink->getCheckoutUrl() ?? 'not available')."\n\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$paymentLink->id; // "pl_4Y0eZitmBnQ6IDoMqZQKh"
|
||||
$paymentLink->description; // "Bicycle tires"
|
||||
$paymentLink->amount; // Mollie\Api\Http\Data\Money (null for an open amount)
|
||||
$paymentLink->archived; // false
|
||||
$paymentLink->createdAt; // "2024-02-24T12:13:14.0Z" (or null)
|
||||
$paymentLink->paidAt; // "2024-02-24T12:15:16.0Z" (or null)
|
||||
$paymentLink->expiresAt; // "2026-01-01T00:00:00.0Z" (or null)
|
||||
$paymentLink->webhookUrl; // "https://example.com/webhook" (or null)
|
||||
$paymentLink->isPaid(); // true once paidAt is set
|
||||
```
|
||||
|
||||
There is no `$paymentLink->status`. Use `isPaid()`, `expiresAt` and `archived`
|
||||
to determine the state of a payment link.
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Payment links are shareable URLs to accept payments
|
||||
- Omit `amount` to create an open-amount link; `amount` is then `null` on the response
|
||||
- They never expire unless you specify an `expiresAt` date
|
||||
- The webhook will be called when the payment status changes
|
||||
- Payment links can be shared via email, chat, or QR code
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
# Create a Capturable Payment
|
||||
|
||||
How to create a payment that can be captured manually with the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\CreatePaymentRequest;
|
||||
use Mollie\Api\Types\PaymentMethod;
|
||||
use Mollie\Api\Types\PaymentStatus;
|
||||
|
||||
try {
|
||||
// Generate a unique order ID
|
||||
$orderId = time();
|
||||
|
||||
// Create the payment
|
||||
$payment = $mollie->send(
|
||||
new CreatePaymentRequest(
|
||||
description: "Order #{$orderId}",
|
||||
amount: Money::euro('10.00'), // Using convenience method
|
||||
redirectUrl: "https://example.com/return.php?order_id={$orderId}",
|
||||
cancelUrl: "https://example.com/cancel.php",
|
||||
webhookUrl: "https://example.com/webhook.php",
|
||||
metadata: ['order_id' => $orderId],
|
||||
method: PaymentMethod::Creditcard,
|
||||
captureMode: 'manual'
|
||||
)
|
||||
);
|
||||
|
||||
// PaymentStatus case for known values, raw string for anything newer.
|
||||
// Store the string: an enum case cannot be written to the database and
|
||||
// interpolating one throws.
|
||||
$status = $payment->status instanceof PaymentStatus
|
||||
? $payment->status->value
|
||||
: $payment->status;
|
||||
|
||||
// Store the order in the database
|
||||
database_write($orderId, $status);
|
||||
|
||||
// Redirect to checkout
|
||||
header('Location: ' . $payment->getCheckoutUrl(), true, 303);
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo 'API call failed: ' . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$payment->id; // "tr_7UhSN1zuXS"
|
||||
$payment->status; // PaymentStatus::Open, or the raw string for an unknown value
|
||||
$payment->amount->currency; // "EUR"
|
||||
$payment->amount->value; // "10.00"
|
||||
$payment->description; // "Order #1234"
|
||||
$payment->metadata->order_id; // "1234"
|
||||
$payment->method; // PaymentMethod::Creditcard, a raw string, or null
|
||||
$payment->captureMode; // "manual" (or null)
|
||||
$payment->getCheckoutUrl(); // "https://www.mollie.com/checkout/select-method/7UhSN1zuXS"
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- `status` is `PaymentStatus|string` and `method` is `PaymentMethod|string|null`; the string side keeps values a newer API returns from breaking your integration
|
||||
- Manual capturing is currently only supported for credit card payments, Billie, Riverty, and Klarna
|
||||
- For Klarna payments, submitting more data like order lines and addresses is required
|
||||
- After the payment is authorized, you'll need to capture it manually to actually charge the customer
|
||||
- The payment will remain in the 'authorized' status until you either capture or cancel it
|
||||
- Make sure to implement the webhook handler to process payment status updates
|
||||
@@ -0,0 +1,54 @@
|
||||
# Create a Payment Capture
|
||||
|
||||
How to capture a payment that was created with manual capture using the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Resources\Capture;
|
||||
use Mollie\Api\Http\Requests\CreatePaymentCaptureRequest;
|
||||
|
||||
try {
|
||||
// Create a capture for the payment
|
||||
/** @var Capture */
|
||||
$capture = $mollie->send(
|
||||
new CreatePaymentCaptureRequest(
|
||||
paymentId: 'tr_WDqYK6vllg',
|
||||
description: 'Order #12345',
|
||||
amount: Money::euro('5.00')
|
||||
)
|
||||
);
|
||||
|
||||
echo "New capture created: {$capture->id}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$capture->id; // "cpt_4qqhO89gsT"
|
||||
$capture->paymentId; // "tr_WDqYK6vllg"
|
||||
$capture->amount; // Money, or null when the API omits it
|
||||
$capture->amount?->currency; // "EUR"
|
||||
$capture->amount?->value; // "5.00"
|
||||
$capture->description; // "Order #12345" (or null)
|
||||
$capture->status; // "pending", "succeeded", "failed" (or null)
|
||||
$capture->createdAt; // "2024-02-24T12:13:14+00:00" (or null)
|
||||
```
|
||||
|
||||
`Capture::$amount` is nullable per the API contract, so guard it (or use `?->`)
|
||||
before reading `currency` or `value`. `status` is a plain nullable string here,
|
||||
not a backed enum.
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- The payment must have been created with `captureMode: 'manual'`
|
||||
- The capture amount can be equal to or lower than the payment amount
|
||||
- You can create multiple partial captures for a single payment
|
||||
- The capture will be processed asynchronously
|
||||
- The payment status will change to `paid` once the capture is successful
|
||||
- Make sure to handle the webhook to process capture status updates
|
||||
- Captures are only available for certain payment methods (e.g., credit cards)
|
||||
@@ -0,0 +1,65 @@
|
||||
# Create an iDEAL Payment
|
||||
|
||||
How to prepare a new iDEAL payment with the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\CreatePaymentRequest;
|
||||
use Mollie\Api\Types\PaymentMethod;
|
||||
use Mollie\Api\Types\PaymentStatus;
|
||||
|
||||
try {
|
||||
// Generate a unique order ID
|
||||
$orderId = time();
|
||||
|
||||
// Create the payment
|
||||
$payment = $mollie->send(
|
||||
new CreatePaymentRequest(
|
||||
description: "Order #{$orderId}",
|
||||
amount: Money::euro('27.50'), // Using convenience method
|
||||
redirectUrl: "https://example.com/return.php?order_id={$orderId}",
|
||||
cancelUrl: "https://example.com/cancel.php",
|
||||
webhookUrl: "https://example.com/webhook.php",
|
||||
metadata: ['order_id' => $orderId],
|
||||
method: PaymentMethod::Ideal
|
||||
)
|
||||
);
|
||||
|
||||
// PaymentStatus case for known values, raw string for anything newer.
|
||||
// Store the string: an enum case cannot be written to the database and
|
||||
// interpolating one throws.
|
||||
$status = $payment->status instanceof PaymentStatus
|
||||
? $payment->status->value
|
||||
: $payment->status;
|
||||
|
||||
// Store the order in the database
|
||||
database_write($orderId, $status);
|
||||
|
||||
// Redirect to checkout
|
||||
header('Location: ' . $payment->getCheckoutUrl(), true, 303);
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo 'API call failed: ' . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$payment->id; // "tr_7UhSN1zuXS"
|
||||
$payment->status; // PaymentStatus::Open, or the raw string for an unknown value
|
||||
$payment->amount->currency; // "EUR"
|
||||
$payment->amount->value; // "27.50"
|
||||
$payment->description; // "Order #1234"
|
||||
$payment->metadata->order_id; // "1234"
|
||||
$payment->method; // PaymentMethod::Ideal, a raw string, or null
|
||||
$payment->getCheckoutUrl(); // "https://www.mollie.com/checkout/select-method/7UhSN1zuXS"
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- `status` is `PaymentStatus|string` and `method` is `PaymentMethod|string|null`; normalise with an `instanceof` check before printing or persisting
|
||||
- The iDEAL payment method is only available for payments in EUR
|
||||
- The bank selection is now handled by iDEAL
|
||||
- The webhook will be called when the payment status changes, so make sure to implement the webhook handler to process status updates
|
||||
@@ -0,0 +1,74 @@
|
||||
# Create a Payment with OAuth
|
||||
|
||||
How to create a payment using OAuth authentication with the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\CreatePaymentRequest;
|
||||
use Mollie\Api\Http\Requests\GetPaginatedProfilesRequest;
|
||||
|
||||
try {
|
||||
// Initialize the Mollie client with your OAuth access token
|
||||
$mollie = new \Mollie\Api\MollieApiClient();
|
||||
$mollie->setAccessToken('access_xxx');
|
||||
|
||||
// Get the first available profile since OAuth tokens don't belong to a specific profile
|
||||
$profiles = $mollie->send(new GetPaginatedProfilesRequest);
|
||||
|
||||
$profile = $profiles[0]; // Select the correct profile for this merchant
|
||||
|
||||
// Generate a unique order ID
|
||||
$orderId = time();
|
||||
|
||||
// Create the payment
|
||||
$payment = $mollie->send(
|
||||
new CreatePaymentRequest(
|
||||
profileId: $profile->id, // Required when using OAuth
|
||||
description: "Order #{$orderId}",
|
||||
amount: new Money(currency: 'EUR', value: '10.00'),
|
||||
redirectUrl: 'https://example.com/return.php?order_id=' . $orderId,
|
||||
cancelUrl: 'https://example.com/cancel.php',
|
||||
webhookUrl: 'https://example.com/webhook.php',
|
||||
metadata: ['order_id' => $orderId]
|
||||
)
|
||||
);
|
||||
|
||||
// Redirect the customer to complete the payment
|
||||
header('Location: ' . $payment->getCheckoutUrl(), true, 303);
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$payment->id; // "tr_7UhSN1zuXS"
|
||||
$payment->status; // PaymentStatus::Open, or the raw string for an unknown value
|
||||
$payment->amount->currency; // "EUR"
|
||||
$payment->amount->value; // "10.00"
|
||||
$payment->description; // "Order #1234"
|
||||
$payment->metadata; // Object containing order_id
|
||||
$payment->profileId; // "pfl_v9hTwCvYqw"
|
||||
$payment->createdAt; // "2024-02-24T12:13:14+00:00" (or null)
|
||||
```
|
||||
|
||||
`status` is `PaymentStatus|string`, so normalise it before printing or storing it:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Types\PaymentStatus;
|
||||
|
||||
$status = $payment->status instanceof PaymentStatus
|
||||
? $payment->status->value
|
||||
: $payment->status;
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- OAuth access tokens don't belong to a specific profile, so you need to specify the `profileId` parameter
|
||||
- Get the profile ID by listing the available profiles with `GetPaginatedProfilesRequest`
|
||||
- OAuth tokens are required for certain features like routing payments
|
||||
- Make sure to handle the webhook to process payment status updates
|
||||
- Store your OAuth tokens securely and refresh them when needed
|
||||
@@ -0,0 +1,63 @@
|
||||
# Create a Payment
|
||||
|
||||
How to prepare a new payment with the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\CreatePaymentRequest;
|
||||
|
||||
try {
|
||||
// Return type is Payment, inferred via send()'s @template — no @var needed
|
||||
$payment = $mollie->send(
|
||||
new CreatePaymentRequest(
|
||||
description: "Order #{$orderId}",
|
||||
amount: Money::euro('10.00'),
|
||||
// or: amount: Money::of('EUR')->minorUnits(1000),
|
||||
redirectUrl: 'https://example.org/return',
|
||||
cancelUrl: 'https://example.org/cancel',
|
||||
webhookUrl: 'https://example.org/webhook',
|
||||
metadata: ['order_id' => $orderId]
|
||||
)
|
||||
);
|
||||
|
||||
// Get the checkout URL to redirect the customer to
|
||||
$checkoutUrl = $payment->getCheckoutUrl();
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$payment->id; // "tr_7UhSN1zuXS"
|
||||
$payment->status; // PaymentStatus::Open (enum) | "open" string fallback for unknown values
|
||||
$payment->amount; // Mollie\Api\Http\Data\Money (readonly value object)
|
||||
$payment->amount->currency; // "EUR"
|
||||
$payment->amount->value; // "10.00"
|
||||
$payment->description; // "Order #1234"
|
||||
$payment->metadata->order_id; // "1234"
|
||||
$payment->getCheckoutUrl(); // "https://www.mollie.com/checkout/select-method/7UhSN1zuXS"
|
||||
```
|
||||
|
||||
Compare statuses against the enum cases (recommended) or string values:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Types\PaymentStatus;
|
||||
|
||||
if ($payment->status === PaymentStatus::Paid) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Always use strings for the amount value to ensure correct decimal precision
|
||||
- The payment `status` will be `open` when initially created
|
||||
- Store the payment `id` in your database for reference
|
||||
- Use `webhookUrl` to get notified of payment status changes
|
||||
- The `redirectUrl` is where your customer will be redirected after the payment
|
||||
- You can store any custom data in the `metadata` object
|
||||
- The checkout URL from `getCheckoutUrl()` is where you should redirect your customer to complete the payment
|
||||
@@ -0,0 +1,101 @@
|
||||
# Create a Routed Payment
|
||||
|
||||
How to create a payment with routing rules using the Mollie API. Routed payments allow you to split payments between connected accounts.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\DataCollection;
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Data\PaymentRoute;
|
||||
use Mollie\Api\Http\Requests\CreatePaymentRequest;
|
||||
use Mollie\Api\Types\PaymentStatus;
|
||||
|
||||
try {
|
||||
// Initialize the Mollie client with your OAuth access token
|
||||
$mollie = new \Mollie\Api\MollieApiClient();
|
||||
$mollie->setAccessToken('access_xxx');
|
||||
|
||||
// Generate a unique order ID
|
||||
$orderId = time();
|
||||
|
||||
// Create the payment with routing rules
|
||||
$payment = $mollie->send(
|
||||
new CreatePaymentRequest(
|
||||
profileId: 'pfl_v9hTwCvYqw',
|
||||
description: "Order #{$orderId}",
|
||||
amount: new Money(currency: 'EUR', value: '10.00'),
|
||||
redirectUrl: 'https://example.com/return.php?order_id=' . $orderId,
|
||||
cancelUrl: 'https://example.com/cancel.php',
|
||||
webhookUrl: 'https://example.com/webhook.php',
|
||||
routing: DataCollection::collect([
|
||||
new PaymentRoute(
|
||||
amount: new Money(currency: 'EUR', value: '7.50'),
|
||||
organizationId: 'org_23456'
|
||||
),
|
||||
])
|
||||
)
|
||||
);
|
||||
|
||||
// Redirect the customer to complete the payment
|
||||
header('Location: ' . $payment->getCheckoutUrl(), true, 303);
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
### With a Future Release Date
|
||||
|
||||
You can also specify when the routed funds should become available on the connected account's balance. `delayUntil` takes a `Date` or any `DateTimeInterface`, not a raw string:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Date;
|
||||
|
||||
$payment = $mollie->send(
|
||||
new CreatePaymentRequest(
|
||||
profileId: 'pfl_v9hTwCvYqw',
|
||||
description: "Order #{$orderId}",
|
||||
amount: new Money(currency: 'EUR', value: '10.00'),
|
||||
redirectUrl: 'https://example.com/return.php?order_id=' . $orderId,
|
||||
cancelUrl: 'https://example.com/cancel.php',
|
||||
webhookUrl: 'https://example.com/webhook.php',
|
||||
routing: DataCollection::collect([
|
||||
new PaymentRoute(
|
||||
amount: new Money(currency: 'EUR', value: '7.50'),
|
||||
organizationId: 'org_23456',
|
||||
delayUntil: new Date('2025-01-01')
|
||||
),
|
||||
])
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$payment->id; // "tr_7UhSN1zuXS"
|
||||
$payment->status; // PaymentStatus::Open, or the raw string for an unknown value
|
||||
$payment->amount->currency; // "EUR"
|
||||
$payment->amount->value; // "10.00"
|
||||
$payment->description; // "Order #1234"
|
||||
$payment->routing; // array of routing rules (or null)
|
||||
$payment->createdAt; // "2024-02-24T12:13:14+00:00"
|
||||
```
|
||||
|
||||
`status` is `PaymentStatus|string`, so normalise it before printing or storing it:
|
||||
|
||||
```php
|
||||
$status = $payment->status instanceof PaymentStatus
|
||||
? $payment->status->value
|
||||
: $payment->status;
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Pass routes as a `DataCollection` of `Mollie\Api\Http\Data\PaymentRoute` objects; each route names the destination organization through `organizationId`
|
||||
- Split payments (routing) must be enabled on your account first. Contact Mollie support to enable this feature
|
||||
- You need an OAuth access token to create routed payments
|
||||
- The sum of routed amounts cannot exceed the payment amount
|
||||
- `delayUntil` must be in the future; pass a `Date` (which formats as 'YYYY-MM-DD') or a `DateTimeInterface`
|
||||
- Routing rules are only available for certain payment methods
|
||||
- Make sure to handle the webhook to process payment status updates
|
||||
@@ -0,0 +1,97 @@
|
||||
# Handle Payment Webhooks
|
||||
|
||||
How to handle payment status updates via webhooks from the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaymentRequest;
|
||||
|
||||
try {
|
||||
// Retrieve the payment's current state
|
||||
$payment = $mollie->send(
|
||||
new GetPaymentRequest(
|
||||
id: $_POST['id']
|
||||
)
|
||||
);
|
||||
$orderId = $payment->metadata->order_id;
|
||||
|
||||
|
||||
|
||||
// First handle status changes
|
||||
if ($payment->status !== $previousPaymentStatus) {
|
||||
// Update your order administration with the new status
|
||||
updateOrder($orderId, $payment->status);
|
||||
|
||||
// Handle the status change
|
||||
if ($payment->isPaid()) {
|
||||
// The payment is paid
|
||||
// Start the process of delivering the product to the customer
|
||||
startDeliveryProcess($orderId);
|
||||
} elseif ($payment->isFailed()) {
|
||||
// The payment has failed
|
||||
// Notify the customer
|
||||
notifyCustomerOfFailure($orderId);
|
||||
} elseif ($payment->isExpired()) {
|
||||
// The payment is expired
|
||||
// Notify the customer
|
||||
notifyCustomerOfExpiration($orderId);
|
||||
} elseif ($payment->isCanceled()) {
|
||||
// The payment is canceled
|
||||
// Notify the customer
|
||||
notifyCustomerOfCancellation($orderId);
|
||||
}
|
||||
}
|
||||
|
||||
// Then handle refunds and chargebacks (these don't change the payment status)
|
||||
if ($payment->hasRefunds()) {
|
||||
// The payment has possibly been (partially) refunded
|
||||
// Note: the payment status remains "paid"
|
||||
processPotentialRefund($orderId);
|
||||
}
|
||||
|
||||
if ($payment->hasChargebacks()) {
|
||||
// The payment has possibly been (partially) charged back
|
||||
// Note: the payment status remains "paid"
|
||||
processPotentialChargeback($orderId);
|
||||
}
|
||||
|
||||
// Always return 200 OK to Mollie
|
||||
http_response_code(200);
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
// Handle the error
|
||||
logError($e->getMessage());
|
||||
http_response_code(500);
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$payment->id; // "tr_7UhSN1zuXS"
|
||||
$payment->status; // PaymentStatus::Paid
|
||||
$payment->amount->currency; // "EUR"
|
||||
$payment->amount->value; // "10.00"
|
||||
$payment->description; // "Order #1234"
|
||||
$payment->metadata; // Object containing order_id
|
||||
$payment->createdAt; // "2024-02-24T12:13:14+00:00"
|
||||
$payment->paidAt; // "2024-02-24T12:15:00+00:00"
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Handle webhooks in the correct order:
|
||||
1. First check for payment status changes
|
||||
2. Then handle refunds and chargebacks (these don't change the payment status).
|
||||
- When completing a payment, the webhook may be called _after_ the customer has already been redirected to the payment's `redirectUrl`.
|
||||
- A payment can have multiple partial refunds and multiple partial chargebacks.
|
||||
- Always respond with a 200 OK status code, even when the payment status is not successful
|
||||
- Process the webhook quickly (within 2 seconds) to avoid timeouts
|
||||
- Use the payment status helper methods (`$payment->isPaid()`, `$payment->isFailed()`, etc.) for reliable status checks
|
||||
- Store the payment status in your database to track the order status
|
||||
- The webhook may be called multiple times for the same payment as Mollie will retry the webhook call.
|
||||
- Webhooks are sent asynchronously, so there might be a delay
|
||||
- Test your webhook implementation thoroughly with different payment scenarios, including:
|
||||
- Status changes (paid, failed, expired, etc.)
|
||||
- Refunds (full and partial)
|
||||
- Chargebacks
|
||||
@@ -0,0 +1,67 @@
|
||||
# List Payment Methods
|
||||
|
||||
How to retrieve all available payment methods with the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\GetAllMethodsRequest;
|
||||
|
||||
try {
|
||||
$methods = $mollie->send(
|
||||
new GetAllMethodsRequest(
|
||||
includeIssuers: false,
|
||||
includePricing: false,
|
||||
locale: 'nl_NL',
|
||||
amount: new Money(currency: 'EUR', value: '100.00')
|
||||
)
|
||||
);
|
||||
|
||||
foreach ($methods as $method) {
|
||||
// Method::$image is ?stdClass — guard it before reading the sizes.
|
||||
$image = $method->image;
|
||||
|
||||
echo '<div style="line-height:40px; vertical-align:top">';
|
||||
|
||||
if ($image !== null) {
|
||||
echo '<img src="' . htmlspecialchars($image->size1x) . '" srcset="' . htmlspecialchars($image->size2x) . ' 2x"> ';
|
||||
}
|
||||
|
||||
echo htmlspecialchars($method->description) . ' (' . htmlspecialchars($method->id) . ')';
|
||||
echo '</div>';
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$method->id; // "ideal"
|
||||
$method->description; // "iDEAL"
|
||||
$method->image; // stdClass with size1x/size2x/svg, or null
|
||||
$method->minimumAmount; // Mollie\Api\Http\Data\Money, or null
|
||||
$method->maximumAmount; // Mollie\Api\Http\Data\Money, or null
|
||||
```
|
||||
|
||||
`image`, `minimumAmount` and `maximumAmount` are all nullable, so read them
|
||||
through a local variable rather than chaining off the property:
|
||||
|
||||
```php
|
||||
$minimum = $method->minimumAmount;
|
||||
$maximum = $method->maximumAmount;
|
||||
|
||||
echo 'Minimum: '.($minimum === null ? 'no minimum' : "{$minimum->currency} {$minimum->value}")."\n";
|
||||
echo 'Maximum: '.($maximum === null ? 'no maximum' : "{$maximum->currency} {$maximum->value}")."\n";
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Use `sequenceType` to filter methods available for recurring payments
|
||||
- The `locale` parameter affects translations of method names and descriptions
|
||||
- The `amount` parameter filters methods available for that specific amount
|
||||
- The `billingCountry` parameter filters methods available in that country
|
||||
- Most methods include image URLs for regular (1x) and retina (2x) displays, but `image` can be `null`
|
||||
- Methods may have minimum and maximum amount constraints; both are `null` when unconstrained
|
||||
@@ -0,0 +1,65 @@
|
||||
# List Payments
|
||||
|
||||
How to retrieve a list of payments from the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaginatedPaymentsRequest;
|
||||
use Mollie\Api\Types\PaymentStatus;
|
||||
|
||||
try {
|
||||
// Use the lazy iterator to walk every page transparently — no manual next() loop
|
||||
foreach ($mollie->payments->iterator() as $payment) {
|
||||
// ->value alone breaks the moment Mollie returns a status this
|
||||
// release has no case for, because the property is then a raw string.
|
||||
$status = $payment->status instanceof PaymentStatus
|
||||
? $payment->status->value
|
||||
: $payment->status;
|
||||
|
||||
echo "Payment {$payment->id}:\n";
|
||||
echo "- Description: {$payment->description}\n";
|
||||
echo "- Amount: {$payment->amount->currency} {$payment->amount->value}\n";
|
||||
echo "- Status: {$status}\n";
|
||||
|
||||
if ($payment->hasRefunds()) {
|
||||
echo "- Has been (partially) refunded\n";
|
||||
}
|
||||
|
||||
if ($payment->hasChargebacks()) {
|
||||
echo "- Has been charged back\n";
|
||||
}
|
||||
|
||||
if ($payment->canBeRefunded() && $payment->amountRemaining->currency === 'EUR' && floatval($payment->amountRemaining->value) >= 2.00) {
|
||||
echo "- Can be refunded\n";
|
||||
}
|
||||
|
||||
echo "\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$payment->id; // "tr_7UhSN1zuXS"
|
||||
$payment->status; // PaymentStatus::Paid, or the raw string for an unknown value
|
||||
$payment->amount->currency; // "EUR"
|
||||
$payment->amount->value; // "10.00"
|
||||
$payment->description; // "Order #1234"
|
||||
$payment->metadata; // Object containing any custom metadata
|
||||
$payment->createdAt; // "2024-02-24T12:13:14+00:00" (or null)
|
||||
$payment->paidAt; // "2024-02-24T12:15:00+00:00" (or null)
|
||||
$payment->method; // PaymentMethod::Ideal, a raw string, or null
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Payments are returned in descending order by creation date (newest first)
|
||||
- `iterator()` lazily fetches each page on demand — only one page is held in memory at a time
|
||||
- For manual page control, send a `GetPaginatedPaymentsRequest` and call `->next()` on the returned cursor collection
|
||||
- `status` is `PaymentStatus|string`. Check it with helpers like `isPaid()` and `isCanceled()`, or with `Utility::equals($payment->status, PaymentStatus::Paid)`; reading `->value` unconditionally fails on a forward-compatible string
|
||||
- Use `hasRefunds()` and `hasChargebacks()` to check if a payment has been refunded or charged back
|
||||
- Use `canBeRefunded()` to check if a payment can still be refunded
|
||||
@@ -0,0 +1,77 @@
|
||||
# Refund a Payment
|
||||
|
||||
How to refund a payment using the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\GetPaymentRequest;
|
||||
use Mollie\Api\Http\Requests\CreatePaymentRefundRequest;
|
||||
use Mollie\Api\Types\RefundStatus;
|
||||
|
||||
try {
|
||||
// Retrieve the payment you want to refund
|
||||
$payment = $mollie->send(
|
||||
new GetPaymentRequest(
|
||||
id: 'tr_WDqYK6vllg'
|
||||
)
|
||||
);
|
||||
|
||||
// Check if the payment can be refunded
|
||||
if ($payment->canBeRefunded() && $payment->amountRemaining->currency === 'EUR' && floatval($payment->amountRemaining->value) >= 2.00) {
|
||||
// Refund € 2,00 of the payment
|
||||
// Note: Using named parameters to avoid PHP 8+ deprecation warnings
|
||||
// Alternative: Use factory method CreatePaymentRefundRequest::for($paymentId, Money::euro('2.00'), 'Description')
|
||||
$refund = $mollie->send(
|
||||
new CreatePaymentRefundRequest(
|
||||
paymentId: $payment->id,
|
||||
amount: Money::euro('2.00'),
|
||||
description: 'Order cancelled by customer'
|
||||
)
|
||||
);
|
||||
|
||||
echo "{$refund->amount->currency} {$refund->amount->value} of payment {$payment->id} refunded.\n";
|
||||
} else {
|
||||
echo "Payment {$payment->id} cannot be refunded.\n";
|
||||
}
|
||||
|
||||
// List all refunds for this payment
|
||||
foreach ($payment->refunds() as $refund) {
|
||||
// status is RefundStatus|string|null: an enum case when this release
|
||||
// knows the value, the raw string when Mollie ships a new one.
|
||||
// Interpolating the property directly throws on an enum case.
|
||||
$status = $refund->status instanceof RefundStatus
|
||||
? $refund->status->value
|
||||
: $refund->status ?? 'unknown';
|
||||
|
||||
echo "Refund {$refund->id}:\n";
|
||||
echo '- Description: '.($refund->description ?? 'no description')."\n";
|
||||
echo "- Amount: {$refund->amount->currency} {$refund->amount->value}\n";
|
||||
echo "- Status: {$status}\n\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$refund->id; // "re_4qqhO89gsT"
|
||||
$refund->amount->currency; // "EUR"
|
||||
$refund->amount->value; // "2.00"
|
||||
$refund->status; // RefundStatus case, raw string, or null
|
||||
$refund->description; // "Order cancelled by customer" (or null)
|
||||
$refund->createdAt; // "2024-02-24T12:13:14+00:00"
|
||||
$refund->paymentId; // "tr_WDqYK6vllg"
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Not all payments can be refunded. Use `canBeRefunded()` to check if a payment can be refunded
|
||||
- You can do partial refunds by specifying a lower amount than the payment amount
|
||||
- Refunds are not instant. Check the refund status to see if it was successful
|
||||
- The payment must be in the `paid` status to be refundable
|
||||
- Some payment methods may have additional requirements or limitations for refunds
|
||||
- `RefundStatus` covers `Queued`, `Pending`, `Processing`, `Refunded`, `Failed` and `Canceled`. Compare with `isPending()`, `isProcessing()`, `isFailed()` or `Utility::equals()` so an unrecognised string from a newer API version still behaves predictably
|
||||
@@ -0,0 +1,86 @@
|
||||
# Retrieve Payment Captures
|
||||
|
||||
How to retrieve and list captures for a payment using the Mollie API.
|
||||
|
||||
## Get a Single Capture
|
||||
|
||||
```php
|
||||
use Mollie\Api\Resources\Capture;
|
||||
use Mollie\Api\Http\Requests\GetPaymentCaptureRequest;
|
||||
|
||||
try {
|
||||
// Retrieve a specific capture
|
||||
/** @var Capture $capture */
|
||||
$capture = $mollie->send(
|
||||
new GetPaymentCaptureRequest(
|
||||
paymentId: 'tr_WDqYK6vllg',
|
||||
captureId: 'cpt_4qqhO89gsT'
|
||||
)
|
||||
);
|
||||
|
||||
// Capture::$amount is nullable per the API contract, so guard the deref.
|
||||
$amount = $capture->amount;
|
||||
|
||||
echo $amount === null
|
||||
? "Capture {$capture->id} has no amount\n"
|
||||
: "Captured {$amount->currency} {$amount->value}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## List All Captures
|
||||
|
||||
```php
|
||||
use Mollie\Api\Resources\Capture;
|
||||
use Mollie\Api\Resources\LazyCollection;
|
||||
use Mollie\Api\Http\Requests\GetPaginatedPaymentCapturesRequest;
|
||||
|
||||
try {
|
||||
// List all captures for a payment
|
||||
/** @var LazyCollection $captures */
|
||||
$captures = $mollie->send(
|
||||
(new GetPaginatedPaymentCapturesRequest(
|
||||
paymentId: 'tr_WDqYK6vllg'
|
||||
))->useIterator()
|
||||
);
|
||||
|
||||
/** @var Capture $capture */
|
||||
foreach ($captures as $capture) {
|
||||
$amount = $capture->amount;
|
||||
|
||||
echo "Capture {$capture->id}:\n";
|
||||
echo '- Amount: '.($amount === null ? 'not available' : "{$amount->currency} {$amount->value}")."\n";
|
||||
echo '- Status: '.($capture->status ?? 'unknown')."\n";
|
||||
echo '- Created: '.($capture->createdAt ?? 'unknown')."\n\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$capture->id; // "cpt_4qqhO89gsT"
|
||||
$capture->paymentId; // "tr_WDqYK6vllg"
|
||||
$capture->amount; // Money, or null when the API omits it
|
||||
$capture->amount?->currency; // "EUR"
|
||||
$capture->amount?->value; // "5.00"
|
||||
$capture->description; // "Order #12345" (or null)
|
||||
$capture->status; // "pending", "succeeded", "failed" (or null)
|
||||
$capture->createdAt; // "2024-02-24T12:13:14+00:00" (or null)
|
||||
```
|
||||
|
||||
`Capture::$amount` is nullable per the API contract, so guard it (or use `?->`)
|
||||
before reading `currency` or `value`. `status` is a plain nullable string here,
|
||||
not a backed enum.
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- You can only retrieve captures for payments created with `captureMode: 'manual'`
|
||||
- A payment can have multiple captures if partial captures were used
|
||||
- The captures list is paginated, use `next()` to get the next page
|
||||
- The capture status indicates whether the capture was successful
|
||||
- The payment status will change to `paid` once all captures are successful
|
||||
- Make sure to handle the webhook to process capture status updates
|
||||
@@ -0,0 +1,74 @@
|
||||
# Update a Payment
|
||||
|
||||
How to update an existing payment using the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaymentRequest;
|
||||
use Mollie\Api\Http\Requests\UpdatePaymentRequest;
|
||||
|
||||
try {
|
||||
// First retrieve the payment you want to update
|
||||
$payment = $mollie->send(
|
||||
new GetPaymentRequest(
|
||||
id: 'tr_7UhSN1zuXS'
|
||||
)
|
||||
);
|
||||
|
||||
// Update specific payment fields
|
||||
$newOrderId = 98765;
|
||||
$payment = $mollie->send(
|
||||
new UpdatePaymentRequest(
|
||||
id: $payment->id,
|
||||
description: "Order #{$newOrderId}",
|
||||
redirectUrl: 'https://example.com/return.php?order_id=' . $newOrderId,
|
||||
metadata: ['order_id' => $newOrderId]
|
||||
// Fields we don't specify will keep their current values:
|
||||
// - webhookUrl
|
||||
// - cancelUrl
|
||||
// - etc.
|
||||
)
|
||||
);
|
||||
|
||||
// Redirect the customer to complete the payment
|
||||
header('Location: ' . $payment->getCheckoutUrl(), true, 303);
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$payment->id; // "tr_7UhSN1zuXS"
|
||||
$payment->status; // PaymentStatus::Open, or the raw string for an unknown value
|
||||
$payment->description; // "Order #98765"
|
||||
$payment->redirectUrl; // "https://example.com/return.php?order_id=98765" (or null)
|
||||
$payment->webhookUrl; // "https://example.com/webhook.php" (or null)
|
||||
$payment->metadata; // Object containing order_id
|
||||
$payment->createdAt; // "2024-02-24T12:13:14+00:00" (or null)
|
||||
```
|
||||
|
||||
`status` is `PaymentStatus|string`, so normalise it before printing or storing it:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Types\PaymentStatus;
|
||||
|
||||
$status = $payment->status instanceof PaymentStatus
|
||||
? $payment->status->value
|
||||
: $payment->status;
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Only certain fields can be updated, including:
|
||||
- description
|
||||
- redirectUrl
|
||||
- cancelUrl
|
||||
- webhookUrl
|
||||
- metadata
|
||||
- You cannot update the amount or currency of a payment
|
||||
- The payment must be in a state that allows updates (e.g., you cannot update a completed payment)
|
||||
- Make sure to handle the webhook to process payment status updates
|
||||
- `Payment` has no `updatedAt` property; the response returns the updated resource, so re-read the fields you changed
|
||||
@@ -0,0 +1,116 @@
|
||||
# Manage Profiles
|
||||
|
||||
How to create, update, list, and delete profiles using the Mollie API.
|
||||
|
||||
## Create a Profile
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\CreateProfileRequest;
|
||||
|
||||
try {
|
||||
// Create a new profile
|
||||
$profile = $mollie->send(
|
||||
new CreateProfileRequest(
|
||||
name: 'My Website Name',
|
||||
website: 'https://www.mywebsite.com',
|
||||
email: 'info@mywebsite.com',
|
||||
phone: '+31208202070',
|
||||
businessCategory: 'MARKETPLACES'
|
||||
)
|
||||
);
|
||||
|
||||
echo "Profile created: {$profile->name}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## List Profiles
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaginatedProfilesRequest;
|
||||
use Mollie\Api\Types\ProfileStatus;
|
||||
|
||||
try {
|
||||
// List all profiles
|
||||
$response = $mollie->send(new GetPaginatedProfilesRequest);
|
||||
|
||||
foreach ($response as $profile) {
|
||||
$status = $profile->status instanceof ProfileStatus
|
||||
? $profile->status->value
|
||||
: ($profile->status ?? 'not available');
|
||||
|
||||
echo "Profile {$profile->id}:\n";
|
||||
echo "- Name: {$profile->name}\n";
|
||||
echo "- Website: " . ($profile->website ?? 'not set') . "\n";
|
||||
echo "- Mode: {$profile->mode}\n";
|
||||
echo "- Status: {$status}\n\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Update a Profile
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\UpdateProfileRequest;
|
||||
|
||||
try {
|
||||
// Update an existing profile
|
||||
$profile = $mollie->send(
|
||||
new UpdateProfileRequest(
|
||||
id: 'pfl_v9hTwCvYqw',
|
||||
name: 'Updated Website Name',
|
||||
website: 'https://www.updated-website.com',
|
||||
email: 'info@updated-website.com',
|
||||
phone: '+31208202071',
|
||||
businessCategory: 'MARKETPLACES'
|
||||
)
|
||||
);
|
||||
|
||||
echo "Profile updated: {$profile->name}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Delete a Profile
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\DeleteProfileRequest;
|
||||
|
||||
try {
|
||||
// Delete a profile
|
||||
$mollie->send(
|
||||
new DeleteProfileRequest(
|
||||
id: 'pfl_v9hTwCvYqw'
|
||||
)
|
||||
);
|
||||
|
||||
echo "Profile deleted\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$profile->id; // "pfl_v9hTwCvYqw"
|
||||
$profile->mode; // "live" or "test"
|
||||
$profile->name; // "My Website Name"
|
||||
$profile->website; // "https://www.mywebsite.com"
|
||||
$profile->email; // "info@mywebsite.com"
|
||||
$profile->phone; // "+31208202070"
|
||||
$profile->businessCategory; // "MARKETPLACES"
|
||||
$profile->status; // ProfileStatus case, unknown raw string, or null
|
||||
$profile->review; // Review object, or null when omitted
|
||||
$profile->createdAt; // Creation date, or null when omitted
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- OAuth access token is required to manage profiles
|
||||
- A profile represents your business or website
|
||||
- Business categories define the type of products/services you offer
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
# Manage Sales Invoices
|
||||
|
||||
How to list and manage sales invoices using the Mollie API.
|
||||
|
||||
## List Sales Invoices
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaginatedSalesInvoicesRequest;
|
||||
use Mollie\Api\Types\SalesInvoiceStatus;
|
||||
|
||||
try {
|
||||
// List all sales invoices
|
||||
$response = $mollie->send(new GetPaginatedSalesInvoicesRequest);
|
||||
|
||||
foreach ($response as $invoice) {
|
||||
$status = $invoice->status instanceof SalesInvoiceStatus
|
||||
? $invoice->status->value
|
||||
: $invoice->status;
|
||||
|
||||
echo "Invoice {$invoice->id}:\n";
|
||||
echo "- Number: " . ($invoice->invoiceNumber ?? 'draft') . "\n";
|
||||
echo "- Status: {$status}\n";
|
||||
echo "- Issued: " . ($invoice->issuedAt ?? 'not issued') . "\n";
|
||||
echo "- Amount due: {$invoice->amountDue->currency} {$invoice->amountDue->value}\n";
|
||||
if (isset($invoice->_links->pdfLink->href)) {
|
||||
echo "- PDF: {$invoice->_links->pdfLink->href}\n";
|
||||
}
|
||||
|
||||
echo "\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$invoice->id; // "invoice_4Y0eZitmBnQ6IDoMqZQKh"
|
||||
$invoice->invoiceNumber; // Invoice number, or null while still a draft
|
||||
$invoice->status; // SalesInvoiceStatus case, or an unknown raw string
|
||||
$invoice->issuedAt; // Issue date, or null when not issued yet
|
||||
$invoice->dueAt; // Due date, or null when not due yet
|
||||
$invoice->amountDue; // Money object containing the outstanding amount
|
||||
$invoice->subtotalAmount; // Money object containing the subtotal
|
||||
$invoice->totalVatAmount; // Money object containing the VAT total
|
||||
$invoice->totalAmount; // Money object containing the invoice total
|
||||
$invoice->lines; // Array of invoice lines, or null when omitted
|
||||
$invoice->_links->pdfLink->href; // URL to download the PDF invoice
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- OAuth access token is required to access sales invoices
|
||||
- Sales invoices are generated for your Mollie account
|
||||
- Each invoice line represents a different type of fee
|
||||
- The PDF invoice is available through the `_links.pdfLink.href` URL
|
||||
@@ -0,0 +1,87 @@
|
||||
# Manage Sessions
|
||||
|
||||
How to create and manage sessions using the Mollie API.
|
||||
|
||||
## Create a Session
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\DataCollection;
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Data\OrderLine;
|
||||
use Mollie\Api\Http\Requests\CreateSessionRequest;
|
||||
|
||||
try {
|
||||
// Create a new session. The request takes typed arguments, not an array.
|
||||
$session = $mollie->send(
|
||||
new CreateSessionRequest(
|
||||
amount: Money::euro('10.00'),
|
||||
description: 'Order #12345',
|
||||
redirectUrl: 'https://example.com/shipping',
|
||||
lines: DataCollection::collect([
|
||||
new OrderLine(
|
||||
description: 'Bicycle tire',
|
||||
quantity: 1,
|
||||
unitPrice: Money::euro('10.00'),
|
||||
totalAmount: Money::euro('10.00')
|
||||
),
|
||||
]),
|
||||
cancelUrl: 'https://example.com/cancel',
|
||||
paymentWebhook: 'https://example.com/webhook'
|
||||
)
|
||||
);
|
||||
|
||||
// getRedirectUrl() reads $_links->redirect and returns null when the API
|
||||
// did not send that link, so check before redirecting.
|
||||
$redirectUrl = $session->getRedirectUrl();
|
||||
|
||||
if ($redirectUrl === null) {
|
||||
throw new \RuntimeException("Session {$session->id} has no redirect link.");
|
||||
}
|
||||
|
||||
header('Location: ' . $redirectUrl, true, 303);
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$session->id; // "ses_abc123"
|
||||
$session->status; // SessionStatus case or raw string
|
||||
$session->amount; // Mollie\Api\Http\Data\Money
|
||||
$session->description; // "Order #12345"
|
||||
$session->redirectUrl; // "https://example.com/shipping"
|
||||
$session->cancelUrl; // "https://example.com/cancel" (or null)
|
||||
$session->clientAccessToken; // token for the client-side checkout
|
||||
$session->lines; // array of order lines (or null)
|
||||
$session->metadata; // your own data (or null)
|
||||
$session->payment; // \stdClass with payment settings, e.g. webhookUrl (or null)
|
||||
$session->_links; // \stdClass with HAL links, e.g. redirect
|
||||
```
|
||||
|
||||
`status` is a `SessionStatus` case (`Open`, `Expired`, `Completed`) when the SDK
|
||||
recognises the value and the raw string otherwise. Read it through the helpers
|
||||
rather than interpolating it:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Types\SessionStatus;
|
||||
|
||||
if ($session->isOpen()) {
|
||||
// still awaiting the customer
|
||||
}
|
||||
|
||||
$status = $session->status instanceof SessionStatus
|
||||
? $session->status->value
|
||||
: $session->status;
|
||||
|
||||
echo "Session status: {$status}\n";
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Sessions are used for payment methods that require additional steps
|
||||
- `amount`, `description`, `redirectUrl` and `lines` are required; `lines` takes a `DataCollection` of `OrderLine` objects
|
||||
- Pass `paymentWebhook` to receive status updates; the SDK nests it as `payment.webhookUrl`
|
||||
- `getRedirectUrl()` is nullable, so guard it before issuing a redirect
|
||||
- Use `isOpen()`, `isExpired()` and `isCompleted()` to branch on the session status
|
||||
@@ -0,0 +1,84 @@
|
||||
# List Settlements
|
||||
|
||||
How to list settlements using the Mollie API.
|
||||
|
||||
## List Settlements
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaginatedSettlementsRequest;
|
||||
use Mollie\Api\Types\SettlementStatus;
|
||||
|
||||
try {
|
||||
// List all settlements
|
||||
$response = $mollie->send(new GetPaginatedSettlementsRequest);
|
||||
|
||||
foreach ($response as $settlement) {
|
||||
$status = $settlement->status instanceof SettlementStatus
|
||||
? $settlement->status->value
|
||||
: ($settlement->status ?? 'not available');
|
||||
|
||||
echo "Settlement {$settlement->reference}:\n";
|
||||
echo "- Created: " . ($settlement->createdAt ?? 'not available') . "\n";
|
||||
echo "- Status: {$status}\n";
|
||||
|
||||
if ($settlement->amount !== null) {
|
||||
echo "- Amount: {$settlement->amount->currency} {$settlement->amount->value}\n";
|
||||
}
|
||||
|
||||
echo "\n";
|
||||
|
||||
if ($settlement->periods === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Show settlement periods
|
||||
foreach ($settlement->periods as $year => $months) {
|
||||
foreach ($months as $month => $data) {
|
||||
echo "Period {$year}-{$month}:\n";
|
||||
|
||||
// Show revenue
|
||||
foreach ($data->revenue as $revenue) {
|
||||
echo "Revenue: {$revenue->description}\n";
|
||||
echo "- Count: {$revenue->count}\n";
|
||||
echo "- Net: {$revenue->amountNet->currency} {$revenue->amountNet->value}\n";
|
||||
if (($vat = $revenue->amountVat ?? null) !== null) {
|
||||
echo "- VAT: {$vat->currency} {$vat->value}\n";
|
||||
}
|
||||
echo "- Gross: {$revenue->amountGross->currency} {$revenue->amountGross->value}\n\n";
|
||||
}
|
||||
|
||||
// Show costs
|
||||
foreach ($data->costs as $cost) {
|
||||
echo "Cost: {$cost->description}\n";
|
||||
echo "- Count: {$cost->count}\n";
|
||||
echo "- Net: {$cost->amountNet->currency} {$cost->amountNet->value}\n";
|
||||
if (($vat = $cost->amountVat ?? null) !== null) {
|
||||
echo "- VAT: {$vat->currency} {$vat->value}\n";
|
||||
}
|
||||
echo "- Gross: {$cost->amountGross->currency} {$cost->amountGross->value}\n\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$settlement->id; // "stl_abc123"
|
||||
$settlement->reference; // "1234567.1804.03"
|
||||
$settlement->createdAt; // Creation date, or null when omitted
|
||||
$settlement->settledAt; // Settlement date, or null while unsettled
|
||||
$settlement->status; // SettlementStatus case, unknown raw string, or null
|
||||
$settlement->amount; // Money object, or null when omitted
|
||||
$settlement->periods; // Settlement periods object, or null when omitted
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- OAuth access token is required to access settlements
|
||||
- Settlements contain revenue and costs grouped by period
|
||||
- Each period shows transaction fees, refunds, and chargebacks
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
# Manage Subscriptions
|
||||
|
||||
How to create and manage subscriptions using the Mollie API.
|
||||
|
||||
## Create a Subscription
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\CreateSubscriptionRequest;
|
||||
use Mollie\Api\Types\SubscriptionStatus;
|
||||
|
||||
try {
|
||||
// Create a subscription for a customer
|
||||
$subscription = $mollie->send(
|
||||
new CreateSubscriptionRequest(
|
||||
customerId: 'cst_8wmqcHMN4U',
|
||||
amount: Money::euro('10.00'),
|
||||
interval: '1 month',
|
||||
description: 'Monthly subscription',
|
||||
webhookUrl: 'https://example.com/webhook',
|
||||
metadata: ['subscription_id' => time()]
|
||||
)
|
||||
);
|
||||
|
||||
// A SubscriptionStatus case for values this release knows, the raw string
|
||||
// for anything Mollie adds later. Never interpolate the property itself:
|
||||
// a backed enum has no string conversion and throws.
|
||||
$status = $subscription->status instanceof SubscriptionStatus
|
||||
? $subscription->status->value
|
||||
: $subscription->status ?? 'unknown';
|
||||
|
||||
echo "Subscription status: {$status}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## List Subscriptions
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaginatedSubscriptionsRequest;
|
||||
use Mollie\Api\Types\SubscriptionStatus;
|
||||
|
||||
try {
|
||||
// List all subscriptions for a customer
|
||||
$response = $mollie->send(
|
||||
new GetPaginatedSubscriptionsRequest(
|
||||
customerId: 'cst_8wmqcHMN4U'
|
||||
)
|
||||
);
|
||||
|
||||
foreach ($response as $subscription) {
|
||||
$status = $subscription->status instanceof SubscriptionStatus
|
||||
? $subscription->status->value
|
||||
: $subscription->status ?? 'unknown';
|
||||
|
||||
echo "Subscription {$subscription->id}:\n";
|
||||
echo "- Status: {$status}\n";
|
||||
echo "- Amount: {$subscription->amount->currency} {$subscription->amount->value}\n";
|
||||
echo '- Times: '.($subscription->times ?? 'unlimited')."\n";
|
||||
echo "- Interval: {$subscription->interval}\n";
|
||||
echo '- Next payment: '.($subscription->nextPaymentDate ?? 'not scheduled')."\n\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Cancel a Subscription
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\CancelSubscriptionRequest;
|
||||
|
||||
try {
|
||||
// Cancel a subscription
|
||||
$mollie->send(
|
||||
new CancelSubscriptionRequest(
|
||||
customerId: 'cst_8wmqcHMN4U',
|
||||
subscriptionId: 'sub_rVKGtNd6s3'
|
||||
)
|
||||
);
|
||||
|
||||
echo "Subscription canceled\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$subscription->id; // "sub_rVKGtNd6s3"
|
||||
$subscription->customerId; // "cst_8wmqcHMN4U"
|
||||
$subscription->mode; // "live" or "test"
|
||||
$subscription->createdAt; // "2024-02-24T12:13:14+00:00"
|
||||
$subscription->status; // SubscriptionStatus case, raw string, or null
|
||||
$subscription->amount; // Mollie\Api\Http\Data\Money
|
||||
$subscription->times; // 12 (or null when the subscription is unlimited)
|
||||
$subscription->timesRemaining; // 4 (or null when the subscription is unlimited)
|
||||
$subscription->interval; // "1 month"
|
||||
$subscription->startDate; // "2024-02-24" (or null)
|
||||
$subscription->nextPaymentDate; // "2024-03-24" (null once the subscription ended)
|
||||
$subscription->description; // "Monthly subscription"
|
||||
$subscription->method; // null or payment method
|
||||
$subscription->webhookUrl; // "https://example.com/webhook"
|
||||
$subscription->metadata; // Object containing custom metadata
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- The customer must have a valid mandate for recurring payments
|
||||
- Subscriptions can be created with various intervals (e.g., "1 month", "3 months")
|
||||
- The webhook is called for every subscription payment
|
||||
- `status` is a `SubscriptionStatus` case when the SDK recognises the value and the raw string otherwise, so compare with `isActive()`, `isPending()`, `isCanceled()`, `isSuspended()`, `isCompleted()` or `Utility::equals()` instead of `===`:
|
||||
- `SubscriptionStatus::Pending`: Waiting for a valid mandate
|
||||
- `SubscriptionStatus::Active`: The subscription is active
|
||||
- `SubscriptionStatus::Canceled`: The subscription is canceled
|
||||
- `SubscriptionStatus::Suspended`: The subscription is suspended
|
||||
- `SubscriptionStatus::Completed`: The subscription has ended
|
||||
@@ -0,0 +1,107 @@
|
||||
# Create a Webhook
|
||||
|
||||
How to create webhooks to receive notifications about events using the Mollie API.
|
||||
|
||||
## The Code
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\CreateWebhookRequest;
|
||||
use Mollie\Api\Types\WebhookStatus;
|
||||
use Mollie\Api\Webhooks\WebhookEventType;
|
||||
|
||||
try {
|
||||
// Create a webhook using the direct request (new style)
|
||||
$webhook = $mollie->send(
|
||||
new CreateWebhookRequest(
|
||||
url: 'https://example.com/webhook',
|
||||
name: 'Payment notifications',
|
||||
eventTypes: WebhookEventType::PAYMENT_LINK_PAID
|
||||
)
|
||||
);
|
||||
|
||||
$status = $webhook->status instanceof WebhookStatus
|
||||
? $webhook->status->value
|
||||
: $webhook->status;
|
||||
|
||||
echo "Webhook created: {$webhook->id}\n";
|
||||
echo "URL: {$webhook->url}\n";
|
||||
echo "Name: {$webhook->name}\n";
|
||||
echo "Event Types: " . implode(', ', $webhook->eventTypes) . "\n";
|
||||
echo "Status: {$status}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Using Endpoint Collections (Legacy Style)
|
||||
|
||||
```php
|
||||
use Mollie\Api\Webhooks\WebhookEventType;
|
||||
|
||||
try {
|
||||
// Create a webhook using endpoint collections
|
||||
$webhook = $mollie->webhooks->create([
|
||||
'url' => 'https://example.com/webhook',
|
||||
'name' => 'Payment notifications',
|
||||
'eventTypes' => WebhookEventType::PAYMENT_LINK_PAID
|
||||
]);
|
||||
|
||||
echo "Webhook created: {$webhook->id}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$webhook->resource; // "webhook"
|
||||
$webhook->id; // "wh_4KgGJJSZpH"
|
||||
$webhook->url; // "https://example.com/webhook"
|
||||
$webhook->profileId; // Profile ID, or null when no profile applies
|
||||
$webhook->createdAt; // "2023-12-25T10:30:54+00:00"
|
||||
$webhook->name; // "Payment notifications"
|
||||
$webhook->eventTypes; // Array of subscribed event type strings
|
||||
$webhook->status; // WebhookStatus case, or an unknown raw string
|
||||
$webhook->_links; // Object containing webhook links
|
||||
```
|
||||
|
||||
## Available Event Types
|
||||
|
||||
Use the `WebhookEventType` constants for the event types supported by your integration. Check the Mollie documentation for the latest availability.
|
||||
|
||||
```php
|
||||
use Mollie\Api\Webhooks\WebhookEventType;
|
||||
|
||||
WebhookEventType::PAYMENT_LINK_PAID; // "payment-link.paid"
|
||||
WebhookEventType::SALES_INVOICE_PAID; // "sales-invoice.paid"
|
||||
WebhookEventType::PROFILE_VERIFIED; // "profile.verified"
|
||||
|
||||
// Get all available event types
|
||||
$allEventTypes = WebhookEventType::getAll();
|
||||
// Returns their raw string values
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- **Webhook URL Requirements**:
|
||||
- There are no security requirements for test mode. However, in order to receive live mode events, the URL needs to be secured with an up-to-date HTTPS connection.
|
||||
- Must respond with HTTP 200 status code
|
||||
- Cannot be `localhost` URLs (use ngrok for local testing)
|
||||
|
||||
- **Event Types**:
|
||||
- Check out [the Mollie documentation](https://docs.mollie.com/reference/webhooks-new#event-types) to see what events are supported.
|
||||
- Additional event types will be added in future updates
|
||||
- Subscribe only to events you need to reduce noise
|
||||
|
||||
- **Webhook URL Best Practices**:
|
||||
- Use HTTPS for security
|
||||
- Implement proper authentication/authorization
|
||||
- Handle webhooks idempotently (same webhook may be sent multiple times)
|
||||
- Log webhook payloads for debugging
|
||||
- Return 200 OK as quickly as possible
|
||||
|
||||
- **Testing**:
|
||||
- Use ngrok or similar tools for local development
|
||||
- Test webhook handling with the webhook test endpoint
|
||||
- Verify signature validation works correctly
|
||||
@@ -0,0 +1,215 @@
|
||||
# Manage Webhooks
|
||||
|
||||
How to retrieve, update, delete, test, and list webhooks using the Mollie API.
|
||||
|
||||
## Get a Webhook
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetWebhookRequest;
|
||||
use Mollie\Api\Types\WebhookStatus;
|
||||
|
||||
try {
|
||||
// Get a specific webhook using direct request
|
||||
$webhook = $mollie->send(
|
||||
new GetWebhookRequest(
|
||||
id: 'wh_4KgGJJSZpH'
|
||||
)
|
||||
);
|
||||
|
||||
$status = $webhook->status instanceof WebhookStatus
|
||||
? $webhook->status->value
|
||||
: $webhook->status;
|
||||
|
||||
echo "Webhook {$webhook->id}:\n";
|
||||
echo "- URL: {$webhook->url}\n";
|
||||
echo "- Name: {$webhook->name}\n";
|
||||
echo "- Event Types: " . implode(', ', $webhook->eventTypes) . "\n";
|
||||
echo "- Status: {$status}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Update a Webhook
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\UpdateWebhookRequest;
|
||||
use Mollie\Api\Webhooks\WebhookEventType;
|
||||
|
||||
try {
|
||||
// Update webhook properties
|
||||
$webhook = $mollie->send(
|
||||
new UpdateWebhookRequest(
|
||||
id: 'wh_4KgGJJSZpH',
|
||||
url: 'https://updated-example.com/webhook',
|
||||
name: 'Updated webhook name',
|
||||
eventTypes: WebhookEventType::PAYMENT_LINK_PAID
|
||||
)
|
||||
);
|
||||
|
||||
echo "Webhook updated successfully\n";
|
||||
echo "New URL: {$webhook->url}\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Delete a Webhook
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\DeleteWebhookRequest;
|
||||
|
||||
try {
|
||||
// Delete a webhook
|
||||
$mollie->send(
|
||||
new DeleteWebhookRequest(
|
||||
id: 'wh_4KgGJJSZpH'
|
||||
)
|
||||
);
|
||||
|
||||
echo "Webhook deleted successfully\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Test a Webhook
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\TestWebhookRequest;
|
||||
|
||||
try {
|
||||
// Test webhook delivery
|
||||
$result = $mollie->send(
|
||||
new TestWebhookRequest(
|
||||
id: 'wh_4KgGJJSZpH'
|
||||
)
|
||||
);
|
||||
|
||||
echo "Webhook test initiated\n";
|
||||
echo "Test status: Success\n";
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "Webhook test failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## List All Webhooks
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaginatedWebhooksRequest;
|
||||
use Mollie\Api\Types\WebhookStatus;
|
||||
|
||||
try {
|
||||
// List all webhooks with pagination
|
||||
$webhooks = $mollie->send(
|
||||
new GetPaginatedWebhooksRequest()
|
||||
);
|
||||
|
||||
foreach ($webhooks as $webhook) {
|
||||
$status = $webhook->status instanceof WebhookStatus
|
||||
? $webhook->status->value
|
||||
: $webhook->status;
|
||||
|
||||
echo "Webhook {$webhook->id}:\n";
|
||||
echo "- URL: {$webhook->url}\n";
|
||||
echo "- Name: {$webhook->name}\n";
|
||||
echo "- Event Types: " . implode(', ', $webhook->eventTypes) . "\n";
|
||||
echo "- Status: {$status}\n";
|
||||
echo "- Created: {$webhook->createdAt}\n\n";
|
||||
}
|
||||
|
||||
// Handle pagination if needed
|
||||
if ($webhooks->hasNext()) {
|
||||
$nextPage = $webhooks->next();
|
||||
// Process next page...
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Using Endpoint Collections (Legacy Style)
|
||||
|
||||
```php
|
||||
try {
|
||||
// Get a webhook
|
||||
$webhook = $mollie->webhooks->get('wh_4KgGJJSZpH');
|
||||
|
||||
// Update a webhook
|
||||
$webhook = $mollie->webhooks->update('wh_4KgGJJSZpH', [
|
||||
'url' => 'https://updated-example.com/webhook',
|
||||
'name' => 'Updated name'
|
||||
]);
|
||||
|
||||
// Delete a webhook
|
||||
$mollie->webhooks->delete('wh_4KgGJJSZpH');
|
||||
|
||||
// Test a webhook
|
||||
$mollie->webhooks->test('wh_4KgGJJSZpH');
|
||||
|
||||
// List webhooks
|
||||
$webhooks = $mollie->webhooks->page();
|
||||
|
||||
// Use convenience methods on webhook resource
|
||||
$webhook = $mollie->webhooks->get('wh_4KgGJJSZpH');
|
||||
|
||||
// Update using convenience method
|
||||
$webhook->update([
|
||||
'name' => 'New name'
|
||||
]);
|
||||
|
||||
// Delete using convenience method
|
||||
$webhook->delete();
|
||||
|
||||
// Test using convenience method
|
||||
$webhook->test();
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$webhook->resource; // "webhook"
|
||||
$webhook->id; // "wh_4KgGJJSZpH"
|
||||
$webhook->url; // "https://example.com/webhook"
|
||||
$webhook->profileId; // Profile ID, or null when no profile applies
|
||||
$webhook->createdAt; // "2023-12-25T10:30:54+00:00"
|
||||
$webhook->name; // "Payment notifications"
|
||||
$webhook->eventTypes; // Array of subscribed event type strings
|
||||
$webhook->status; // WebhookStatus case, or an unknown raw string
|
||||
$webhook->_links; // Object containing webhook links
|
||||
```
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- **Webhook Updates**:
|
||||
- All parameters are optional when updating
|
||||
- Only specify fields you want to change
|
||||
|
||||
- **Webhook Testing**:
|
||||
- Tests webhook delivery by sending a test payload
|
||||
- Useful for verifying webhook URL accessibility
|
||||
- Check your webhook endpoint logs to confirm receipt
|
||||
- Test payloads may differ from actual event payloads
|
||||
|
||||
- **Webhook Deletion**:
|
||||
- Permanently removes the webhook
|
||||
- Cannot be undone
|
||||
- Stop receiving notifications for deleted webhooks immediately
|
||||
|
||||
- **Listing Webhooks**:
|
||||
- Returns all webhooks in your account
|
||||
- Results are paginated
|
||||
- Use `hasNext()` and `next()` for pagination
|
||||
|
||||
- **Convenience Methods**:
|
||||
- Webhook resources include convenience methods (`update()`, `delete()`, `test()`)
|
||||
- These methods operate on the current webhook instance
|
||||
- Simplify common operations without needing to specify the webhook ID again
|
||||
|
||||
- **Error Handling**:
|
||||
- Webhook operations may fail due to network issues
|
||||
- Handle `ApiException` to catch and respond to errors appropriately
|
||||
- Common errors include webhook not found (404) or validation errors (422)
|
||||
@@ -0,0 +1,92 @@
|
||||
# Webhook Signature Verification
|
||||
|
||||
This recipe shows you how to verify Mollie webhook signatures in your application using the `SignatureValidator` class.
|
||||
|
||||
## Basic Example
|
||||
|
||||
```php
|
||||
use Mollie\Api\Webhooks\SignatureValidator;
|
||||
use Mollie\Api\Exceptions\InvalidSignatureException;
|
||||
|
||||
$signingSecret = "foobar";
|
||||
|
||||
$request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
|
||||
$requestBody = (string)$request->getBody();
|
||||
$signature = $request->getHeader("X-Mollie-Signature");
|
||||
|
||||
try {
|
||||
$validator = new SignatureValidator($signingSecret);
|
||||
$isValid = $validator->validatePayload($requestBody, $signature);
|
||||
|
||||
if ($isValid) {
|
||||
// Process the verified webhook event
|
||||
} else {
|
||||
// Legacy webhook without signature
|
||||
}
|
||||
|
||||
return new \GuzzleHttp\Psr7\Response(200);
|
||||
} catch (InvalidSignatureException $e) {
|
||||
return new \GuzzleHttp\Psr7\Response(400);
|
||||
}
|
||||
```
|
||||
|
||||
For more information about webhooks and signature verification, see the [Webhooks Guide](../webhooks.md).
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Multiple Signing Secrets
|
||||
|
||||
During key rotation or migration periods, you can verify signatures against multiple secrets:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Webhooks\SignatureValidator;
|
||||
use Mollie\Api\Exceptions\InvalidSignatureException;
|
||||
|
||||
$signingSecrets = [
|
||||
"current_secret",
|
||||
"previous_secret"
|
||||
];
|
||||
|
||||
try {
|
||||
$validator = new SignatureValidator($signingSecrets);
|
||||
$isValid = $validator->validatePayload($requestBody, $signature);
|
||||
|
||||
if ($isValid) {
|
||||
processWebhook($webhookData);
|
||||
} else {
|
||||
// Handle legacy webhook
|
||||
// Make sure to validate the actual contents of $webhookData before processing
|
||||
processLegacyWebhook($webhookData);
|
||||
}
|
||||
|
||||
} catch (InvalidSignatureException $e) {
|
||||
http_response_code(400);
|
||||
echo 'Invalid signature';
|
||||
}
|
||||
```
|
||||
|
||||
### PSR-7 Request Validation
|
||||
|
||||
If you're using PSR-7 compatible requests:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Webhooks\SignatureValidator;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
|
||||
$signingSecret = "your_webhook_signing_secret";
|
||||
$validator = new SignatureValidator($signingSecret);
|
||||
|
||||
try {
|
||||
$isValid = $validator->validateRequest($request);
|
||||
|
||||
if ($isValid) {
|
||||
// Signature is valid
|
||||
} else {
|
||||
// Legacy webhook (no signature)
|
||||
}
|
||||
|
||||
return new Response(200, [], 'OK');
|
||||
} catch (InvalidSignatureException $e) {
|
||||
return new Response(400, [], 'Invalid signature');
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,184 @@
|
||||
# Webhook Events
|
||||
|
||||
How to retrieve and manage webhook events using the Mollie API.
|
||||
|
||||
## Get a Webhook Event
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetWebhookEventRequest;
|
||||
|
||||
try {
|
||||
// Get a specific webhook event
|
||||
$webhookEvent = $mollie->send(
|
||||
new GetWebhookEventRequest(
|
||||
id: 'whev_abc123'
|
||||
)
|
||||
);
|
||||
|
||||
echo "Webhook Event {$webhookEvent->id}:\n";
|
||||
echo "- Resource: {$webhookEvent->resource}\n";
|
||||
echo "- Event Type: {$webhookEvent->type}\n";
|
||||
echo "- Entity ID: {$webhookEvent->entityId}\n";
|
||||
echo "- Created: {$webhookEvent->createdAt}\n";
|
||||
|
||||
// getEntity() returns ?stdClass — null when the event carries no snapshot
|
||||
$entity = $webhookEvent->getEntity();
|
||||
|
||||
if ($entity !== null) {
|
||||
echo "- Entity Data Available: Yes\n";
|
||||
// The embedded entity is a raw stdClass, so get_class() would always
|
||||
// report "stdClass". Read its own `resource` field instead.
|
||||
echo "- Entity Type: {$entity->resource}\n";
|
||||
} else {
|
||||
echo "- Entity Data Available: No\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## Using Endpoint Collections (Legacy Style)
|
||||
|
||||
```php
|
||||
try {
|
||||
// Get a webhook event using endpoint collections
|
||||
$webhookEvent = $mollie->webhookEvents->get('whev_abc123');
|
||||
|
||||
echo "Event Type: {$webhookEvent->type}\n";
|
||||
echo "Entity ID: {$webhookEvent->entityId}\n";
|
||||
|
||||
// Access the embedded entity data
|
||||
if ($webhookEvent->hasEntity()) {
|
||||
$entity = $webhookEvent->getEntity();
|
||||
echo "Entity data is available\n";
|
||||
}
|
||||
} catch (\Mollie\Api\Exceptions\ApiException $e) {
|
||||
echo "API call failed: " . htmlspecialchars($e->getMessage());
|
||||
}
|
||||
```
|
||||
|
||||
## The Response
|
||||
|
||||
```php
|
||||
$webhookEvent->resource; // "event"
|
||||
$webhookEvent->id; // "whev_abc123"
|
||||
$webhookEvent->type; // "payment-link.paid"
|
||||
$webhookEvent->entityId; // "pl_4Y0eZitmBnQ5jsBYZIBw" (the payment link ID)
|
||||
$webhookEvent->createdAt; // "2023-12-25T10:30:54+00:00"
|
||||
$webhookEvent->_embedded; // stdClass holding the embedded entity, or null
|
||||
$webhookEvent->_links; // Object containing relevant URLs
|
||||
```
|
||||
|
||||
## Working with Embedded Entity Data
|
||||
|
||||
The webhook event contains the full payload of the triggered event in the `_embedded` property:
|
||||
|
||||
```php
|
||||
// Get the embedded entity — null when the event carries no snapshot
|
||||
$entity = $webhookEvent->getEntity();
|
||||
|
||||
if ($entity !== null) {
|
||||
// For payment-link.paid events this is the raw payment link payload. It is
|
||||
// a plain stdClass: no typed resource, no isPaid() helper, and no `status`
|
||||
// field — payment links do not have one. `amount` is absent on an
|
||||
// open-amount link, so read it defensively.
|
||||
$amount = $entity->amount ?? null;
|
||||
|
||||
echo "Payment Link ID: {$entity->id}\n";
|
||||
echo 'Amount: '.($amount === null ? 'open amount' : "{$amount->value} {$amount->currency}")."\n";
|
||||
echo 'Paid: '.(! empty($entity->paidAt) ? 'yes' : 'no')."\n";
|
||||
}
|
||||
|
||||
// Direct access to _embedded structure
|
||||
$embedded = $webhookEvent->_embedded;
|
||||
if (! empty($embedded->entity)) {
|
||||
$entity = $embedded->entity;
|
||||
echo "Entity ID: {$entity->id}\n";
|
||||
}
|
||||
```
|
||||
|
||||
## Helper Methods
|
||||
|
||||
The `WebhookEvent` resource includes convenient methods for working with entity data:
|
||||
|
||||
```php
|
||||
// Check if entity data is available
|
||||
if ($webhookEvent->hasEntity()) {
|
||||
echo "Entity data is embedded in this event\n";
|
||||
}
|
||||
|
||||
// Get the entity data — getEntity() returns ?stdClass, so guard for null
|
||||
$entity = $webhookEvent->getEntity();
|
||||
if ($entity !== null) {
|
||||
echo "Entity ID: {$entity->id}\n";
|
||||
echo "Entity Resource: {$entity->resource}\n";
|
||||
}
|
||||
```
|
||||
|
||||
## Event Types and Their Payloads
|
||||
|
||||
Currently, only payment link events are supported:
|
||||
|
||||
### Payment Link Events
|
||||
```php
|
||||
// payment-link.paid
|
||||
if ($webhookEvent->type === 'payment-link.paid') {
|
||||
$paymentLink = $webhookEvent->getEntity();
|
||||
|
||||
if ($paymentLink === null) {
|
||||
throw new \RuntimeException('Payment-link event has no embedded entity.');
|
||||
}
|
||||
|
||||
$amount = $paymentLink->amount ?? null;
|
||||
|
||||
echo "Payment Link: {$paymentLink->id}\n";
|
||||
echo 'Amount: '.($amount === null ? 'open amount' : "{$amount->value} {$amount->currency}")."\n";
|
||||
echo 'Paid: '.(! empty($paymentLink->paidAt) ? 'yes' : 'no')."\n";
|
||||
}
|
||||
```
|
||||
|
||||
The embedded entity is the raw JSON payload as `stdClass`, not a `PaymentLink`
|
||||
resource: there is no `isPaid()` helper, `amount` is a plain object rather than
|
||||
a `Money`, and there is no `status` field. For a fully typed `PaymentLink` —
|
||||
with `isPaid()` and a typed `Money` amount — process the delivery through
|
||||
`WebhookEventMapper` and call `asResource()`; see [Webhooks](../../webhooks.md).
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- **Event Structure**:
|
||||
- All webhook events have the `resource` property set to "event"
|
||||
- The `type` property indicates what kind of event occurred
|
||||
- The `entityId` references the ID of the object that triggered the event
|
||||
- The `_embedded.entity` contains the full object data at the time of the event
|
||||
|
||||
- **Entity Data**:
|
||||
- The embedded entity contains the complete state of the object when the event occurred
|
||||
- This is useful for getting the full context without making additional API calls
|
||||
- Entity data may be null for some event types
|
||||
- Payment links have no `status` field; derive the state from `paidAt`, `expiresAt` and `archived`
|
||||
- `amount` is absent on an open-amount payment link
|
||||
|
||||
- **Event Identification**:
|
||||
- Use the `id` property to uniquely identify webhook events
|
||||
- The `entityId` property tells you which object triggered the event
|
||||
- The `type` property tells you what kind of event occurred
|
||||
|
||||
- **Event Ordering**:
|
||||
- Webhook events are not guaranteed to be delivered in order
|
||||
- Use the `createdAt` timestamp to determine the actual order of events
|
||||
- Handle events idempotently in case duplicates are received
|
||||
|
||||
- **Processing Events**:
|
||||
- Always check if entity data is available using `hasEntity()`
|
||||
- `getEntity()` returns `null` when no entity is embedded, so guard the result
|
||||
- The entity data reflects the state at the time the event was created
|
||||
|
||||
- **Security**:
|
||||
- Always verify webhook signatures when processing events
|
||||
- The webhook event data shows what was sent, but verify authenticity
|
||||
- Consider webhook events as notifications, not the primary source of truth
|
||||
|
||||
- **Debugging**:
|
||||
- Use the webhook event ID to track specific events
|
||||
- The embedded entity data helps understand what triggered the event
|
||||
- Check the `_links` property for related URLs and actions
|
||||
@@ -0,0 +1,185 @@
|
||||
# Request Reference
|
||||
|
||||
This document provides a quick reference index of all available request classes in the Mollie PHP SDK. For detailed parameter information, see the PHPDoc comments in each request class. Request classes provide a type-safe way to interact with the Mollie API directly, offering better IDE support and type checking compared to using endpoint collections with arrays.
|
||||
|
||||
## Payments
|
||||
|
||||
- **CreatePaymentRequest** - Create a new payment
|
||||
- **GetPaymentRequest** - Retrieve a payment by ID
|
||||
- **UpdatePaymentRequest** - Update an existing payment
|
||||
- **CancelPaymentRequest** - Cancel a payment
|
||||
- **CreatePaymentRefundRequest** - Create a refund for a payment
|
||||
- **GetPaymentRefundRequest** - Retrieve a payment refund
|
||||
- **CancelPaymentRefundRequest** - Cancel a payment refund
|
||||
- **GetPaginatedPaymentsRequest** - List payments with pagination
|
||||
- **ReleasePaymentAuthorizationRequest** - Release payment authorization
|
||||
|
||||
## Customers
|
||||
|
||||
- **CreateCustomerRequest** - Create a new customer
|
||||
- **GetCustomerRequest** - Retrieve a customer by ID
|
||||
- **UpdateCustomerRequest** - Update an existing customer
|
||||
- **DeleteCustomerRequest** - Delete a customer
|
||||
- **GetPaginatedCustomerRequest** - List customers with pagination
|
||||
- **CreateCustomerPaymentRequest** - Create a payment for a customer
|
||||
- **GetPaginatedCustomerPaymentsRequest** - List customer payments with pagination
|
||||
|
||||
## Subscriptions
|
||||
|
||||
- **CreateSubscriptionRequest** - Create a subscription for a customer
|
||||
- **GetSubscriptionRequest** - Retrieve a subscription
|
||||
- **UpdateSubscriptionRequest** - Update a subscription
|
||||
- **CancelSubscriptionRequest** - Cancel a subscription
|
||||
- **GetPaginatedSubscriptionsRequest** - List subscriptions with pagination
|
||||
- **GetAllPaginatedSubscriptionsRequest** - List all subscriptions (across all customers)
|
||||
- **GetPaginatedSubscriptionPaymentsRequest** - List subscription payments with pagination
|
||||
|
||||
## Mandates
|
||||
|
||||
- **CreateMandateRequest** - Create a mandate for a customer
|
||||
- **GetMandateRequest** - Retrieve a mandate
|
||||
- **RevokeMandateRequest** - Revoke a mandate
|
||||
- **GetPaginatedMandateRequest** - List mandates with pagination
|
||||
|
||||
## Refunds
|
||||
|
||||
- **GetPaginatedRefundsRequest** - List refunds with pagination
|
||||
|
||||
## Webhooks
|
||||
|
||||
- **CreateWebhookRequest** - Create a webhook
|
||||
- **GetWebhookRequest** - Retrieve a webhook
|
||||
- **UpdateWebhookRequest** - Update a webhook
|
||||
- **DeleteWebhookRequest** - Delete a webhook
|
||||
- **TestWebhookRequest** - Test a webhook
|
||||
- **GetPaginatedWebhooksRequest** - List webhooks with pagination
|
||||
- **GetWebhookEventRequest** - Retrieve a webhook event
|
||||
|
||||
## Profiles
|
||||
|
||||
- **CreateProfileRequest** - Create a profile
|
||||
- **GetProfileRequest** - Retrieve a profile
|
||||
- **GetCurrentProfileRequest** - Retrieve the current profile
|
||||
- **UpdateProfileRequest** - Update a profile
|
||||
- **DeleteProfileRequest** - Delete a profile
|
||||
- **GetPaginatedProfilesRequest** - List profiles with pagination
|
||||
|
||||
## Methods
|
||||
|
||||
- **GetMethodRequest** - Retrieve a payment method
|
||||
- **GetAllMethodsRequest** - Retrieve all payment methods
|
||||
- **GetEnabledMethodsRequest** - Retrieve all enabled payment methods
|
||||
- **EnableMethodRequest** - Enable a payment method
|
||||
- **DisableMethodRequest** - Disable a payment method
|
||||
- **EnableMethodIssuerRequest** - Enable a method issuer
|
||||
- **DisableMethodIssuerRequest** - Disable a method issuer
|
||||
|
||||
## Balances
|
||||
|
||||
- **GetBalanceRequest** - Retrieve a balance
|
||||
- **GetPaginatedBalanceRequest** - List balances with pagination
|
||||
- **GetBalanceReportRequest** - Retrieve a balance report
|
||||
- **GetPaginatedBalanceTransactionRequest** - List balance transactions with pagination
|
||||
|
||||
## Settlements
|
||||
|
||||
- **GetSettlementRequest** - Retrieve a settlement
|
||||
- **GetPaginatedSettlementsRequest** - List settlements with pagination
|
||||
- **GetPaginatedSettlementPaymentsRequest** - List settlement payments with pagination
|
||||
- **GetPaginatedSettlementRefundsRequest** - List settlement refunds with pagination
|
||||
- **GetPaginatedSettlementCapturesRequest** - List settlement captures with pagination
|
||||
- **GetPaginatedSettlementChargebacksRequest** - List settlement chargebacks with pagination
|
||||
|
||||
## Payment Links
|
||||
|
||||
- **CreatePaymentLinkRequest** - Create a payment link
|
||||
- **GetPaymentLinkRequest** - Retrieve a payment link
|
||||
- **UpdatePaymentLinkRequest** - Update a payment link
|
||||
- **DeletePaymentLinkRequest** - Delete a payment link
|
||||
- **GetPaginatedPaymentLinksRequest** - List payment links with pagination
|
||||
- **GetPaginatedPaymentLinkPaymentsRequest** - List payment link payments with pagination
|
||||
|
||||
## Sessions
|
||||
|
||||
- **CreateSessionRequest** - Create a checkout session
|
||||
- **GetSessionRequest** - Retrieve a session
|
||||
- **UpdateSessionRequest** - Update a session
|
||||
- **CancelSessionRequest** - Cancel a session
|
||||
- **GetPaginatedSessionsRequest** - List sessions with pagination
|
||||
|
||||
## Invoices
|
||||
|
||||
- **GetInvoiceRequest** - Retrieve an invoice
|
||||
- **GetPaginatedInvoiceRequest** - List invoices with pagination
|
||||
|
||||
## Sales Invoices
|
||||
|
||||
- **CreateSalesInvoiceRequest** - Create a sales invoice
|
||||
- **GetSalesInvoiceRequest** - Retrieve a sales invoice
|
||||
- **UpdateSalesInvoiceRequest** - Update a sales invoice
|
||||
- **DeleteSalesInvoiceRequest** - Delete a sales invoice
|
||||
- **GetPaginatedSalesInvoicesRequest** - List sales invoices with pagination
|
||||
|
||||
## Payment Routes
|
||||
|
||||
- **CreateDelayedPaymentRouteRequest** - Create a delayed payment route
|
||||
- **ListPaymentRoutesRequest** - List payment routes
|
||||
- **UpdatePaymentRouteRequest** - Update a payment route
|
||||
|
||||
## Payment Captures
|
||||
|
||||
- **CreatePaymentCaptureRequest** - Create a payment capture
|
||||
- **GetPaymentCaptureRequest** - Retrieve a payment capture
|
||||
- **GetPaginatedPaymentCapturesRequest** - List payment captures with pagination
|
||||
|
||||
## Payment Chargebacks
|
||||
|
||||
- **GetPaymentChargebackRequest** - Retrieve a payment chargeback
|
||||
- **GetPaginatedPaymentChargebacksRequest** - List payment chargebacks with pagination
|
||||
- **GetPaginatedChargebacksRequest** - List all chargebacks with pagination
|
||||
|
||||
## Other Resources
|
||||
|
||||
- **GetClientRequest** - Retrieve a client
|
||||
- **GetPaginatedClientRequest** - List clients with pagination
|
||||
- **CreateClientLinkRequest** - Create a client link
|
||||
- **GetCapabilityRequest** - Retrieve a capability
|
||||
- **ListCapabilitiesRequest** - List capabilities
|
||||
- **GetPermissionRequest** - Retrieve a permission
|
||||
- **ListPermissionsRequest** - List permissions
|
||||
- **GetTerminalRequest** - Retrieve a terminal
|
||||
- **GetPaginatedTerminalsRequest** - List terminals with pagination
|
||||
- **GetOrganizationRequest** - Retrieve an organization
|
||||
- **GetOnboardingStatusRequest** - Get onboarding status
|
||||
- **GetOrganizationPartnerStatusRequest** - Get organization partner status
|
||||
- **CreateConnectBalanceTransferRequest** - Create a Connect balance transfer
|
||||
- **GetConnectBalanceTransferRequest** - Retrieve a Connect balance transfer
|
||||
- **ListConnectBalanceTransfersRequest** - List Connect balance transfers
|
||||
- **ApplePayPaymentSessionRequest** - Request Apple Pay payment session
|
||||
|
||||
## Using Request Classes
|
||||
|
||||
All request classes are located in the `Mollie\Api\Http\Requests` namespace.
|
||||
|
||||
**Example:**
|
||||
```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/redirect',
|
||||
webhookUrl: 'https://example.com/webhook'
|
||||
);
|
||||
|
||||
$payment = $mollie->send($request);
|
||||
```
|
||||
|
||||
For detailed parameter information, use your IDE's autocomplete features, or refer to the [Official API documentation](https://docs.mollie.com/reference/overview).
|
||||
|
||||
## See Also
|
||||
|
||||
- [Requests Documentation](requests.md) - General information about using requests
|
||||
- [Endpoint Collections](endpoint-collections.md) - Alternative way to interact with the API
|
||||
- [Mollie API Reference](https://docs.mollie.com/reference/overview) - Official API documentation
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
# Requests
|
||||
|
||||
## Overview
|
||||
|
||||
The Mollie API client uses request classes to communicate with the Mollie API. Each request class handles specific API endpoints and operations. The response is casted into a dedicated `Mollie\Api\Resources\*` class.
|
||||
|
||||
For a complete list of available request classes, see the [Request Reference](request-reference.md).
|
||||
|
||||
## Sending a Request
|
||||
|
||||
To send a request using the Mollie API client, you typically need to:
|
||||
|
||||
1. **Create an instance of the client**:
|
||||
```php
|
||||
use Mollie\Api\MollieApiClient;
|
||||
|
||||
$mollie = new MollieApiClient();
|
||||
$mollie->setApiKey('test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM');
|
||||
```
|
||||
|
||||
2. **Create and configure the request**:
|
||||
Depending on the operation, you might need to create an instance of a specific request class and configure it with necessary parameters.
|
||||
|
||||
3. **Send the request**:
|
||||
Use the client to send the request and handle the response.
|
||||
|
||||
## Best Practices: Using Named Parameters (PHP 8.0+)
|
||||
|
||||
**Recommended**: Use named parameters for cleaner, more readable code. This approach makes it clear what each parameter represents and avoids issues with optional parameters:
|
||||
|
||||
```php
|
||||
use Mollie\Api\MollieApiClient;
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\CreatePaymentRequest;
|
||||
|
||||
$mollie = new MollieApiClient();
|
||||
$mollie->setApiKey('test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
|
||||
|
||||
// Recommended: Use named parameters (PHP 8.0+)
|
||||
$createPaymentRequest = new CreatePaymentRequest(
|
||||
description: 'Test payment',
|
||||
amount: Money::euro('10.00'), // Using convenience method
|
||||
redirectUrl: 'https://example.org/redirect',
|
||||
webhookUrl: 'https://example.org/webhook',
|
||||
locale: 'en_US',
|
||||
metadata: ['order_id' => '123']
|
||||
);
|
||||
|
||||
// In v4 the return type is inferred from the request class — no @var needed
|
||||
$payment = $mollie->send($createPaymentRequest);
|
||||
// $payment is Mollie\Api\Resources\Payment
|
||||
```
|
||||
|
||||
## Adding unsupported properties
|
||||
If the SDK is not up to date with the API, you can manually add a property to a request via the `query()` or `payload()` methods.
|
||||
|
||||
```php
|
||||
$someRequestUsingPayload = new SomePayloadRequest(...);
|
||||
$someRequestUsingPayload->payload()->add('foo', 'bar');
|
||||
|
||||
$someRequestUsingQueryParams = new SomeQueryRequest(...);
|
||||
$someRequestUsingQueryParams->query()->add('foo', 'bar');
|
||||
```
|
||||
|
||||
## Parameter Ordering Notes
|
||||
|
||||
For legacy reasons, some request classes have optional parameters before required parameters in their constructors. This can trigger PHP 8+ deprecation warnings when using positional arguments. To avoid this:
|
||||
|
||||
1. **Use named parameters** (recommended for PHP 8.0+):
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\CreatePaymentRefundRequest;
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
|
||||
// Using named parameters avoids deprecation warnings
|
||||
$request = new CreatePaymentRefundRequest(
|
||||
paymentId: $paymentId,
|
||||
amount: Money::euro('10.00'),
|
||||
description: 'Refund description'
|
||||
);
|
||||
```
|
||||
|
||||
2. **Use factory methods** where available:
|
||||
```php
|
||||
// CreatePaymentRefundRequest has a factory method with correct parameter order
|
||||
$request = CreatePaymentRefundRequest::for(
|
||||
$paymentId,
|
||||
Money::euro('10.00'),
|
||||
'Refund description'
|
||||
);
|
||||
```
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
# Responses
|
||||
|
||||
Whether you interact with the endpoints using the traditional method (`$mollie->payments->...`) or the new `Request` classes, you can always inspect the raw `Response`.
|
||||
|
||||
## Resource Hydration
|
||||
By default, all responses from are automatically hydrated into the corresponding `Resource` or `ResourceCollection` objects. You can still access the raw response using the `->getResponse()` method.
|
||||
|
||||
For example, when retrieving a payment you'll receive a Payment resource object, on which you can still access the raw Response class.
|
||||
|
||||
```php
|
||||
/**
|
||||
* Legacy approach
|
||||
*
|
||||
* @var Mollie\Api\Resources\Payment $payment
|
||||
*/
|
||||
$payment = $mollie->payments->get('tr_*********');
|
||||
|
||||
/**
|
||||
* New approach
|
||||
*
|
||||
* @var Mollie\Api\Resources\Payment $payment
|
||||
*/
|
||||
$payment = $mollie->send(new GetPaymentRequest('tr_*********'));
|
||||
|
||||
$response = $payment->getResponse();
|
||||
```
|
||||
|
||||
`getResponse()` returns `?Response`. Resources produced by an API call always
|
||||
carry a non-null `Response`. Resources hydrated from a signed webhook snapshot
|
||||
return `null` (there was no HTTP call). Null-check before chaining, or use
|
||||
`getOrigin()` for origin-agnostic metadata — see [`docs/webhooks.md`](webhooks.md).
|
||||
|
||||
## Resource Wrappers
|
||||
Sometimes it's useful to hydrate a class of your own with the information returned by the API. A wrapper can expose a subset of the resource's properties or cast them into your own objects, while retaining access to the underlying `Resource` it wraps.
|
||||
|
||||
### Define a Wrapper
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Resources\Payment;
|
||||
use Mollie\Api\Resources\ResourceWrapper;
|
||||
|
||||
class PaymentWrapper extends ResourceWrapper
|
||||
{
|
||||
public function __construct(
|
||||
public Money $amount,
|
||||
public ?\DateTimeImmutable $createdAt,
|
||||
) {
|
||||
}
|
||||
|
||||
public static function fromResource($resource): self
|
||||
{
|
||||
/** @var Payment $resource */
|
||||
return (new self(
|
||||
amount: $resource->amount,
|
||||
createdAt: $resource->createdAt === null
|
||||
? null
|
||||
: new \DateTimeImmutable($resource->createdAt),
|
||||
))->setWrapped($resource);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
Call `wrapInto()` on the request. `send()` then returns your wrapper, and PHPStan infers its type without a `@var` annotation:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\GetPaymentRequest;
|
||||
|
||||
$paymentWrapper = $mollie->send(
|
||||
(new GetPaymentRequest('tr_*********'))->wrapInto(PaymentWrapper::class)
|
||||
);
|
||||
// $paymentWrapper is PaymentWrapper
|
||||
```
|
||||
|
||||
PHPStan currently honors both the `@phpstan-self-out` and `@psalm-this-out` annotations, and the committed fixture guards their combined inference contract. This repository does not run Psalm, so Psalm behavior is not verified here. PhpStorm does not infer the narrowed type.
|
||||
|
||||
To hydrate into a different SDK resource class first, call `hydrateInto()` before `wrapInto()`:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\Requests\DynamicGetRequest;
|
||||
use Mollie\Api\Http\Requests\GetPaginatedPaymentRefundsRequest;
|
||||
use Mollie\Api\Resources\RefundCollection;
|
||||
|
||||
// Payment::$_links is ?stdClass, and a payment only carries a `refunds` link
|
||||
// when the API includes one — a payment with no refunds has neither. Guard
|
||||
// both hops in one isset(), the same way Payment::refunds() does internally.
|
||||
if (! isset($payment->_links->refunds->href)) {
|
||||
// Fall back to the paginated endpoint, which routes by payment id. Keep
|
||||
// the same hydrateInto()/wrapInto() chain as the linked branch so both
|
||||
// branches hand back a RefundsWrapper, not a bare RefundCollection.
|
||||
$refunds = $mollie->send(
|
||||
(new GetPaginatedPaymentRefundsRequest(paymentId: $payment->id))
|
||||
->hydrateInto(RefundCollection::class)
|
||||
->wrapInto(RefundsWrapper::class)
|
||||
);
|
||||
} else {
|
||||
$refunds = $mollie->send(
|
||||
(new DynamicGetRequest($payment->_links->refunds->href))
|
||||
->hydrateInto(RefundCollection::class)
|
||||
->wrapInto(RefundsWrapper::class)
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
`RefundsWrapper` is an application wrapper implementing `IsWrapper`, for example by extending `ResourceWrapper` as above. Call request-specific setters first, then `hydrateInto()`, then `wrapInto()` last. Reversing the two named helpers makes static analysis report the hydration target while runtime still returns the wrapper.
|
||||
|
||||
`setHydratableResource(new WrapperResource(PaymentWrapper::class))` still works, but it keeps the request's original generic type, so `send()` cannot infer the wrapper.
|
||||
|
||||
The original `Payment` resource properties and methods can be accessed through the wrapper class.
|
||||
|
||||
```php
|
||||
// access property
|
||||
$paymentWrapper->status;
|
||||
|
||||
// access method
|
||||
$paymentWrapper->isPaid();
|
||||
```
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
# Retry strategies
|
||||
|
||||
The Mollie PHP client automatically retries requests that fail with retryable network errors. You can customize how many retries are performed and how long to wait between attempts by providing a retry strategy.
|
||||
|
||||
## Default behavior
|
||||
|
||||
- Strategy: `LinearRetryStrategy`
|
||||
- Default max retries: `5` (in addition to the initial attempt)
|
||||
- Default delay: linear backoff with a 1000ms increase per attempt
|
||||
- Attempt 1 (first retry): 1000ms
|
||||
- Attempt 2: 2000ms
|
||||
- Attempt 3: 3000ms
|
||||
- … up to the configured maximum
|
||||
|
||||
If all retries are exhausted, the last `Mollie\Api\Exceptions\RetryableNetworkRequestException` is thrown. Fatal middleware hooks, if configured, run once after retries are exhausted.
|
||||
|
||||
## Changing the defaults
|
||||
|
||||
To change the retry behavior, provide your own strategy instance to the client:
|
||||
|
||||
```php
|
||||
use Mollie\Api\MollieApiClient;
|
||||
use Mollie\Api\Http\Retry\LinearRetryStrategy;
|
||||
|
||||
$client = new MollieApiClient();
|
||||
|
||||
// Example: 2 retries with no delay (useful in tests)
|
||||
$client->setRetryStrategy(new LinearRetryStrategy(2, 0));
|
||||
|
||||
// Example: 3 retries with 500ms linear increase (0.5s, 1.0s, 1.5s)
|
||||
$client->setRetryStrategy(new LinearRetryStrategy(3, 500));
|
||||
```
|
||||
|
||||
To effectively disable retries, set the max retries to `0`:
|
||||
|
||||
```php
|
||||
$client->setRetryStrategy(new LinearRetryStrategy(0, 0));
|
||||
```
|
||||
|
||||
## Exponential backoff with 429 / Retry-After
|
||||
|
||||
`ExponentialRetryStrategy` does exponential backoff with optional jitter, and additionally retries `TooManyRequestsException` (HTTP 429). A numeric `Retry-After` is honoured when it fits within `maxDelayMs`. With jitter enabled, the strategy adds up to 10% (capped at 1000ms) so throttled clients do not retry simultaneously. It never retries early: if `Retry-After` exceeds `maxDelayMs`, the exception is thrown immediately.
|
||||
|
||||
```php
|
||||
use Mollie\Api\Http\ExponentialRetryStrategy;
|
||||
|
||||
$client->setRetryStrategy(new ExponentialRetryStrategy(
|
||||
maxRetries: 5,
|
||||
baseDelayMs: 500,
|
||||
multiplier: 2.0,
|
||||
maxDelayMs: 30_000,
|
||||
jitter: true,
|
||||
));
|
||||
```
|
||||
|
||||
Use this strategy when you want graceful handling of 429 rate limits — the linear strategy only retries network errors.
|
||||
|
||||
### Inspecting rate-limit headers
|
||||
|
||||
Every response exposes Mollie's `RateLimit` and `RateLimit-Policy` values:
|
||||
|
||||
```php
|
||||
$rateLimit = $response->rateLimit();
|
||||
|
||||
$rateLimit?->policy;
|
||||
$rateLimit?->remaining;
|
||||
$rateLimit?->restoreSeconds;
|
||||
$rateLimit?->burst;
|
||||
$rateLimit?->quota;
|
||||
$rateLimit?->windowSeconds;
|
||||
```
|
||||
|
||||
Missing headers or parameters produce `null` values. API exceptions retain their response, so the same data is available on a 429 through `$exception->getResponse()->rateLimit()`.
|
||||
|
||||
## Creating your own strategy
|
||||
|
||||
Custom strategies implement the `Mollie\Api\Contracts\RetryStrategyContract` interface:
|
||||
|
||||
```php
|
||||
namespace Mollie\Api\Contracts;
|
||||
|
||||
use Throwable;
|
||||
|
||||
interface RetryStrategyContract
|
||||
{
|
||||
// Maximum number of retries after the initial attempt
|
||||
public function maxRetries(): int;
|
||||
|
||||
// Whether this exception should be retried
|
||||
public function shouldRetry(Throwable $exception): bool;
|
||||
|
||||
// Delay in milliseconds before performing the given retry attempt
|
||||
// $attempt starts at 1 for the first retry
|
||||
public function delayBeforeAttemptMs(int $attempt, ?Throwable $exception = null): int;
|
||||
}
|
||||
```
|
||||
|
||||
### Example: Fixed delay strategy
|
||||
|
||||
```php
|
||||
use Mollie\Api\Contracts\RetryStrategyContract;
|
||||
use Mollie\Api\Exceptions\RetryableNetworkRequestException;
|
||||
use Throwable;
|
||||
|
||||
class FixedDelayRetryStrategy implements RetryStrategyContract
|
||||
{
|
||||
public function __construct(
|
||||
private int $maxRetries = 3,
|
||||
private int $delayMs = 1000,
|
||||
) {}
|
||||
|
||||
public function maxRetries(): int
|
||||
{
|
||||
return max(0, $this->maxRetries);
|
||||
}
|
||||
|
||||
public function shouldRetry(Throwable $exception): bool
|
||||
{
|
||||
return $exception instanceof RetryableNetworkRequestException;
|
||||
}
|
||||
|
||||
public function delayBeforeAttemptMs(int $attempt, ?Throwable $exception = null): int
|
||||
{
|
||||
// Same delay for every retry
|
||||
return max(0, $this->delayMs);
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
$client->setRetryStrategy(new FixedDelayRetryStrategy(3, 250));
|
||||
```
|
||||
|
||||
You can implement any retry timing and retryability rules you prefer (e.g., exponential backoff with jitter, capped delays, retrying 429 responses, etc.) as long as you adhere to the contract.
|
||||
|
||||
## When retries happen
|
||||
|
||||
Retries are performed only when the configured retry strategy returns `true` from `shouldRetry()`. The default `LinearRetryStrategy` retries `Mollie\Api\Exceptions\RetryableNetworkRequestException` only, matching the v3 default behavior. `ExponentialRetryStrategy` also retries `TooManyRequestsException` for HTTP 429 responses when `Retry-After` is absent or fits within `maxDelayMs`.
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
# Testing with Mollie API Client
|
||||
|
||||
## Test Mode Configuration
|
||||
|
||||
### Key Concepts
|
||||
- Test mode is automatically determined by API key prefix (`test_` or `live_`)
|
||||
- Explicit `testmode` parameter available for OAuth scenarios
|
||||
- Configure at global client level or per individual request
|
||||
|
||||
### Global Configuration
|
||||
```php
|
||||
use Mollie\Api\MollieApiClient;
|
||||
|
||||
$mollie = new MollieApiClient();
|
||||
$mollie->setApiKey("test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM");
|
||||
$mollie->test(true); // Applies to all subsequent requests
|
||||
```
|
||||
|
||||
### Per-Request Configuration
|
||||
```php
|
||||
// Payment request with test mode
|
||||
$createPaymentRequest = new CreatePaymentRequest(/* ... */);
|
||||
$mollie->send($createPaymentRequest->test(true));
|
||||
|
||||
// Endpoint collection example
|
||||
$customer = $mollie->customers->get('cust_12345678', testmode: true);
|
||||
```
|
||||
|
||||
## API Mocking
|
||||
|
||||
### Typed Mock Responses
|
||||
|
||||
The fastest path is the typed `MockResponse` factories — they merge a fixture base with the typed overrides you pass:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Fake\MockResponse;
|
||||
use Mollie\Api\Http\Data\Money;
|
||||
use Mollie\Api\Http\Requests\GetPaymentRequest;
|
||||
use Mollie\Api\MollieApiClient;
|
||||
use Mollie\Api\Types\PaymentStatus;
|
||||
|
||||
$client = MollieApiClient::fake([
|
||||
GetPaymentRequest::class => MockResponse::payment(
|
||||
id: 'tr_xxxxxxxxxxxx',
|
||||
status: PaymentStatus::Paid,
|
||||
amount: new Money(currency: 'EUR', value: '20.00'),
|
||||
description: 'Test',
|
||||
),
|
||||
]);
|
||||
|
||||
$payment = $client->send(new GetPaymentRequest('tr_xxxxxxxxxxxx'));
|
||||
|
||||
$client->assertSent(GetPaymentRequest::class);
|
||||
```
|
||||
|
||||
Available typed factories: `payment`, `customer`, `subscription`, `mandate`, `refund`, `chargeback`, `method`, `paymentLink`, `invoice`, `capture`. Each accepts a `$overrides` array for fields not covered by named arguments.
|
||||
|
||||
### Basic Usage
|
||||
API responses can be simulated without network calls by using the `MollieApiClient::fake()` method. Each Request/Response pair passed to the fake method is consumed after a matching request.
|
||||
|
||||
> [!NOTE]
|
||||
> To keep pairs available for reuse after they've been matched, use the `retainRequests` parameter: `MollieApiClient::fake([...], retainRequests: true)`
|
||||
|
||||
```php
|
||||
use Mollie\Api\MollieApiClient;
|
||||
use Mollie\Api\Fake\MockResponse;
|
||||
use Mollie\Api\Http\Requests\GetPaymentRequest;
|
||||
|
||||
$client = MollieApiClient::fake([
|
||||
GetPaymentRequest::class => new MockResponse(
|
||||
body: [
|
||||
'resource' => 'payment',
|
||||
'id' => 'tr_xxxxxxxxxxxx',
|
||||
'mode' => 'test',
|
||||
'amount' => [
|
||||
'value' => '20.00',
|
||||
'currency' => 'EUR'
|
||||
],
|
||||
'description' => 'Test',
|
||||
'status' => 'open',
|
||||
// ...
|
||||
],
|
||||
status: 200
|
||||
)
|
||||
]);
|
||||
|
||||
$payment = $client->send(new GetPaymentRequest('tr_xxxxxxxxxxxx'));
|
||||
```
|
||||
|
||||
### Sequence Mock Responses
|
||||
To return different responses for the same request type, use `SequenceMockResponse` and pass `MockResponse` or `Closure` (which return `MockResponse` instances) in the order they should occur.
|
||||
|
||||
```php
|
||||
$client = MollieApiClient::fake([
|
||||
DynamicGetRequest::class => new SequenceMockResponse(
|
||||
MockResponse::ok(['first' => 'response']),
|
||||
MockResponse::ok(['second' => 'response']),
|
||||
function (PendingRequest $pendingRequest) {
|
||||
//...
|
||||
|
||||
return MockResponse::ok(['third' => 'response']);
|
||||
}
|
||||
)
|
||||
]);
|
||||
```
|
||||
|
||||
To verify that a request was sent, use `assertSent` or `assertSentCount`.
|
||||
|
||||
```php
|
||||
$client->send(new GetPaymentRequest('tr_xxxxxxxxxxxx', embedRefunds: true));
|
||||
|
||||
$client->assertSent(GetPaymentRequest::class);
|
||||
$client->assertSent(function (PendingRequest $pendingRequest, Response $response) {
|
||||
return $pendingRequest->query()->get('embed') === 'refunds';
|
||||
});
|
||||
|
||||
$client->assertSentCount(1);
|
||||
```
|
||||
|
||||
### MockResponse Options
|
||||
Configure responses using:
|
||||
- **Arrays**: Direct data structure
|
||||
- **Strings**: JSON payloads or predefined fixture names
|
||||
- **Callables**: Dynamic response generation *or* intercepting assertions
|
||||
|
||||
```php
|
||||
// Array response
|
||||
MockResponse::created([
|
||||
'id' => 'tr_xxxxxxxxxxxx',
|
||||
'amount' => ['value' => '20.00', 'currency' => 'EUR']
|
||||
]);
|
||||
|
||||
// Fixture response
|
||||
MockResponse::created('payment');
|
||||
|
||||
// Dynamic response
|
||||
MockResponse::created(function (PendingRequest $request) {
|
||||
return ['amount' => $request->hasParameter('amount') ? 10 : 20];
|
||||
});
|
||||
|
||||
// Intercepting assertions
|
||||
function (PendingRequest $request) use ($idempotencyKey) {
|
||||
$this->assertEquals($idempotencyKey, $request->headers()->get('Idempotency-Key'));
|
||||
|
||||
return MockResponse::created('payment');
|
||||
};
|
||||
```
|
||||
|
||||
### Working with Collections
|
||||
Create paginated list responses:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Resources\PaymentCollection;
|
||||
|
||||
$client = MollieApiClient::fake([
|
||||
GetPaginatedPaymentsRequest::class => MockResponse::list(PaymentCollection::class)
|
||||
->add([
|
||||
'resource' => 'payment',
|
||||
'id' => 'tr_xxxxxxxxxxxx',
|
||||
'mode' => 'test',
|
||||
'amount' => [
|
||||
'value' => '20.00',
|
||||
'currency' => 'EUR'
|
||||
],
|
||||
'description' => 'Test',
|
||||
'status' => 'open',
|
||||
// ...
|
||||
])
|
||||
->create()
|
||||
]);
|
||||
```
|
||||
|
||||
### Handling Embedded Resources
|
||||
Simulate HAL+JSON embedded resources using the `_embedded` property:
|
||||
|
||||
**Key Concepts**
|
||||
- Use `MockResponse::resource()` to start building a resource response
|
||||
- Chain `embed()` calls to add related collections
|
||||
- Maintain resource relationships with a fluent interface
|
||||
|
||||
```php
|
||||
use Mollie\Api\Resources\Payment;
|
||||
use Mollie\Api\Resources\RefundCollection;
|
||||
use Mollie\Api\Resources\ChargebackCollection;
|
||||
|
||||
$client = MollieApiClient::fake([
|
||||
GetPaymentRequest::class => MockResponse::resource(Payment::class)
|
||||
->with([ // Main resource properties
|
||||
'resource' => 'payment',
|
||||
'id' => 'tr_xxxxxxxxxxxx',
|
||||
'amount' => [
|
||||
'value' => '20.00',
|
||||
'currency' => 'EUR'
|
||||
]
|
||||
])
|
||||
->embed(RefundCollection::class) // First embedded collection
|
||||
->add([
|
||||
'resource' => 'refund',
|
||||
'id' => 're_12345',
|
||||
'amount' => [
|
||||
'value' => '10.00',
|
||||
'currency' => 'EUR'
|
||||
]
|
||||
])
|
||||
->embed(ChargebackCollection::class) // Second embedded collection
|
||||
->add([
|
||||
'resource' => 'chargeback',
|
||||
'id' => 'chb_12345',
|
||||
'amount' => [
|
||||
'value' => '20.00',
|
||||
'currency' => 'EUR'
|
||||
]
|
||||
])
|
||||
->create()
|
||||
]);
|
||||
|
||||
// Resulting response will contain:
|
||||
// - Payment details in main body
|
||||
// - Refunds in _embedded.refunds
|
||||
// - Chargebacks in _embedded.chargebacks
|
||||
```
|
||||
|
||||
### Error Response Mocking
|
||||
Simulate API error responses using dedicated helper methods or the generic error builder:
|
||||
|
||||
**Common Error Shortcuts**
|
||||
```php
|
||||
use Mollie\Api\Fake\MockResponse;
|
||||
|
||||
// 404 Not Found
|
||||
$client = MollieApiClient::fake([
|
||||
GetPaymentRequest::class => MockResponse::notFound('No payment exists with token tr_xxxxxxxxxxx')
|
||||
]);
|
||||
|
||||
// 422 Validation Error (with optional field reference)
|
||||
$client = MollieApiClient::fake([
|
||||
CreatePaymentRequest::class => MockResponse::unprocessableEntity(
|
||||
detail: 'Amount must be at least €1.00',
|
||||
field: 'amount'
|
||||
)
|
||||
]);
|
||||
```
|
||||
|
||||
**Generic Error Builder**
|
||||
```php
|
||||
// Custom status code example
|
||||
$response = MockResponse::error(
|
||||
status: 403,
|
||||
title: 'Forbidden',
|
||||
detail: 'Insufficient permissions to access this resource'
|
||||
);
|
||||
|
||||
// Special characters handling
|
||||
$detail = 'Invalid parameter "recurringType" - did you mean "sequenceType"?';
|
||||
$response = MockResponse::unprocessableEntity($detail, 'field');
|
||||
```
|
||||
|
||||
**Error Response Structure**
|
||||
All errors follow Mollie's standardized format:
|
||||
```json
|
||||
{
|
||||
"status": 404,
|
||||
"title": "Not Found",
|
||||
"detail": "No payment exists with token tr_xxxxxxxxxxx",
|
||||
"field": "amount" // Only present for validation errors
|
||||
}
|
||||
```
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
# Webhooks
|
||||
|
||||
Mollie uses webhooks to notify your application about events that occur in your Mollie account. This guide explains how to work with Mollie webhooks in your application securely and efficiently. Mollie currently supports two types of webhooks: the (soon to be labeled) "legacy webhooks" and "next-gen webhooks". This guide is about the next-gen webhooks.
|
||||
|
||||
## Overview
|
||||
|
||||
Webhooks are HTTP POST requests that Mollie sends to your application when specific events occur, such as when a payment is completed, failed, or refunded. This allows your application to respond to these events in real-time without constantly polling the Mollie API.
|
||||
|
||||
## Security
|
||||
|
||||
### Signature Verification
|
||||
|
||||
**Important**: Always verify webhook signatures to ensure requests come from Mollie and haven't been tampered with.
|
||||
|
||||
Mollie signs all webhook requests with an HMAC-SHA256 signature sent in the `X-Mollie-Signature` header. The SDK provides built-in signature verification:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Webhooks\SignatureValidator;
|
||||
use Mollie\Api\Exceptions\InvalidSignatureException;
|
||||
|
||||
$signingSecret = "your_webhook_signing_secret_from_dashboard";
|
||||
|
||||
try {
|
||||
$validator = new SignatureValidator($signingSecret);
|
||||
|
||||
/**
|
||||
* Validate the webhook signature
|
||||
*
|
||||
* This method will throw an InvalidSignatureException if:
|
||||
* - A signature header is present but doesn't contain a valid signature
|
||||
* - The payload has been tampered with
|
||||
*
|
||||
* For PSR-7 requests, you can also use validateRequest($psr7Request)
|
||||
*/
|
||||
$isValid = $validator->validatePayload($requestBody, $signature);
|
||||
|
||||
if (!$isValid) {
|
||||
// Handle invalid signature
|
||||
http_response_code(400);
|
||||
exit('Invalid signature');
|
||||
}
|
||||
|
||||
// Signature is valid - proceed with webhook processing
|
||||
|
||||
} catch (InvalidSignatureException $e) {
|
||||
// Log the invalid signature attempt for security monitoring
|
||||
error_log("Invalid webhook signature: " . $e->getMessage());
|
||||
http_response_code(400);
|
||||
exit('Invalid signature');
|
||||
}
|
||||
```
|
||||
|
||||
#### Key Rotation
|
||||
|
||||
During key rotation or migration periods, you can verify signatures against multiple secrets:
|
||||
|
||||
```php
|
||||
$signingSecrets = [
|
||||
"current_secret",
|
||||
"previous_secret" // Keep old secret during transition period
|
||||
];
|
||||
|
||||
$validator = new SignatureValidator($signingSecrets);
|
||||
$isValid = $validator->validatePayload($requestBody, $signature);
|
||||
```
|
||||
|
||||
### Processing Webhook Payloads
|
||||
|
||||
Once you've verified the webhook signature, you can safely process the payload:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Webhooks\Events\BalanceTransactionCreated;
|
||||
use Mollie\Api\Webhooks\Events\PaymentLinkPaid;
|
||||
use Mollie\Api\Webhooks\WebhookEventMapper;
|
||||
|
||||
// Process the webhook payload into an event object. Pass the signature
|
||||
// (when available) so the resulting resource carries webhook provenance
|
||||
// — see "Inspecting webhook provenance" below.
|
||||
$event = (new WebhookEventMapper())->processPayload(
|
||||
$request->getParsedBody(),
|
||||
$signature,
|
||||
);
|
||||
|
||||
// Extract the entity ID (e.g., payment ID, customer ID, etc.)
|
||||
$entityId = $event->entityData('id');
|
||||
|
||||
// Hydrate the embedded entity snapshot into a fully typed SDK resource.
|
||||
// No HTTP call is made — the signed webhook payload is the source of truth.
|
||||
// If you subscribe to "simple" payloads (entityId only), the $event->entity
|
||||
// property is null and calling $event->entity() throws. Check the property
|
||||
// first, or fetch the resource yourself via its Get request using
|
||||
// $event->entityId.
|
||||
$resource = $event->asResource($mollie);
|
||||
|
||||
// Handle different event types
|
||||
match (true) {
|
||||
$event instanceof PaymentLinkPaid => $this->handlePaymentLinkPaid(),
|
||||
$event instanceof BalanceTransactionCreated => $this->handleBalanceTransactionCreated(),
|
||||
// ... handle other event types
|
||||
};
|
||||
```
|
||||
|
||||
#### Using custom webhook Events
|
||||
If the API is ahead of this SDK's implementation of new Events, you can create your own Events as temporary workaround and pass it into the `WebhookEventMapper`
|
||||
|
||||
```php
|
||||
// Event class
|
||||
use Mollie\Api\Webhooks\Events\BaseEvent;
|
||||
|
||||
class SomeEventHappened extends BaseEvent
|
||||
{
|
||||
public static function type(): string
|
||||
{
|
||||
return 'some.event_happened'; // needs to match the eventType from the documentation
|
||||
}
|
||||
}
|
||||
|
||||
// passing into event mapper and processing payload
|
||||
$event = (new WebhookEventMapper([
|
||||
'some.event_happened' => SomeEventHappened::class
|
||||
]))->processPayload($request->getParsedBody());
|
||||
```
|
||||
|
||||
### Inspecting webhook provenance
|
||||
|
||||
Resources hydrated from a webhook carry a `WebhookSnapshotOrigin` instead
|
||||
of an HTTP `Response`. You can inspect the event metadata without hitting
|
||||
the API:
|
||||
|
||||
```php
|
||||
$resource = $event->asResource($mollie);
|
||||
|
||||
$resource->getResponse(); // null — there was no HTTP call
|
||||
$resource->getOrigin(); // WebhookSnapshotOrigin
|
||||
$resource->getOrigin()->getEventId(); // 'event_GvJ8WHrp5isUdRub9CJyH'
|
||||
$resource->getOrigin()->getSignature(); // the X-Mollie-Signature header, or null
|
||||
$resource->getOrigin()->getReceivedAt(); // DateTimeImmutable
|
||||
```
|
||||
|
||||
Resources fetched via the API (for example via `$mollie->send(new
|
||||
GetPaymentRequest(...))`) still return a `Response` from `getResponse()`
|
||||
as before.
|
||||
|
||||
Follow-up methods like `$payment->refunds()`, `$profile->methods()`, and
|
||||
`$subscription->payments()` work the same on webhook-origin resources
|
||||
as they do on HTTP-origin resources. When the embedded snapshot carries
|
||||
the link URL, the SDK follows it; when it does not, the SDK routes the
|
||||
request through the connector using the resource's id. Either way, the
|
||||
call fires real HTTP to Mollie, which means a valid API key must be
|
||||
configured on the client. A webhook handler running without an API key
|
||||
is limited to reading the signed snapshot itself — there is no path
|
||||
that lets the SDK reach Mollie without credentials.
|
||||
|
||||
### Reading from the snapshot vs. fetching fresh data
|
||||
|
||||
A complete handler usually combines both. The signed snapshot is enough
|
||||
to make decisions. When you need data the snapshot doesn't carry
|
||||
(related resources, the very latest server state), fall back to the
|
||||
API. The API fallback requires a valid key on the client — the snapshot
|
||||
path does not.
|
||||
|
||||
```php
|
||||
use Mollie\Api\Exceptions\InvalidSignatureException;
|
||||
use Mollie\Api\MollieApiClient;
|
||||
use Mollie\Api\Webhooks\Events\PaymentLinkPaid;
|
||||
use Mollie\Api\Webhooks\SignatureValidator;
|
||||
use Mollie\Api\Webhooks\WebhookEventMapper;
|
||||
|
||||
$mollie = new MollieApiClient;
|
||||
$mollie->setApiKey(getenv('MOLLIE_API_KEY')); // only needed for the fetch path
|
||||
|
||||
$signingSecret = getenv('MOLLIE_WEBHOOK_SIGNING_SECRET');
|
||||
$requestBody = (string) $request->getBody();
|
||||
$signature = $request->getHeaderLine('X-Mollie-Signature');
|
||||
|
||||
try {
|
||||
if (! (new SignatureValidator($signingSecret))->validatePayload($requestBody, $signature)) {
|
||||
http_response_code(400);
|
||||
exit('Invalid signature');
|
||||
}
|
||||
} catch (InvalidSignatureException $e) {
|
||||
error_log("Invalid webhook signature: " . $e->getMessage());
|
||||
http_response_code(400);
|
||||
exit('Invalid signature');
|
||||
}
|
||||
|
||||
$event = (new WebhookEventMapper)->processPayload(
|
||||
json_decode($requestBody, true),
|
||||
$signature,
|
||||
);
|
||||
|
||||
if (! $event instanceof PaymentLinkPaid) {
|
||||
// Not the event we care about — ack and return.
|
||||
http_response_code(200);
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Snapshot path: no HTTP, no API key required.
|
||||
// asResource() is typed as BaseResource, so narrow it for static analysis.
|
||||
/** @var \Mollie\Api\Resources\PaymentLink $paymentLink */
|
||||
$paymentLink = $event->asResource($mollie);
|
||||
|
||||
// PaymentLink::$amount is ?Money. An open-amount link never carried a fixed
|
||||
// amount, so there is nothing on the link itself to record — the amount that
|
||||
// was actually charged only exists on the payment that settled it (step 2).
|
||||
$amount = $paymentLink->amount;
|
||||
|
||||
if ($amount === null) {
|
||||
markOpenAmountOrderPaid(
|
||||
orderId: $paymentLink->id,
|
||||
paidAt: $event->createdAt,
|
||||
);
|
||||
} else {
|
||||
markOrderPaid(
|
||||
orderId: $paymentLink->id,
|
||||
amount: $amount->value,
|
||||
paidAt: $event->createdAt,
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Fetch path: fires HTTP, needs the API key configured above.
|
||||
// $paymentLink->payments() follows the link from the snapshot when
|
||||
// present, otherwise routes through $mollie->paymentLinkPayments.
|
||||
foreach ($paymentLink->payments() as $payment) {
|
||||
reconcilePaymentLine($paymentLink->id, $payment);
|
||||
}
|
||||
|
||||
http_response_code(200);
|
||||
```
|
||||
|
||||
If your webhook handler runs without an API key (signing-secret-only
|
||||
deployment), remove the `setApiKey()` call and skip step 2 — you can
|
||||
still do everything in step 1 from the signed payload alone.
|
||||
|
||||
### Testing Webhooks
|
||||
|
||||
Testing webhooks is crucial to ensure your application handles all event types correctly. The SDK provides several tools to help you test webhook scenarios.
|
||||
|
||||
Use `MockEvent` to create realistic webhook payloads for testing:
|
||||
|
||||
```php
|
||||
use Mollie\Api\Fake\MockEvent;
|
||||
use Mollie\Api\Webhooks\Events\PaymentLinkPaid;
|
||||
use Mollie\Api\Webhooks\Events\BalanceTransactionCreated;
|
||||
|
||||
// Create a mock PaymentLinkPaid event
|
||||
$paymentLinkEventPayload = MockEvent::for(PaymentLinkPaid::class)
|
||||
->entityId('pl_1234567890')
|
||||
->snapshot() // Include full resource data
|
||||
->create();
|
||||
|
||||
// Create a mock BalanceTransactionCreated event
|
||||
$balanceEventPayload = MockEvent::for(BalanceTransactionCreated::class)
|
||||
->entityId('bt_9876543210')
|
||||
->simple() // Webhook request without any resource data besides entityId
|
||||
->create();
|
||||
```
|
||||
Reference in new issue
Block a user