Initial commit
This commit is contained in:
commit
2b9e58beee
822 files changed
+62544
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user