Initial commit

This commit is contained in:
Piet Nijbacker committed 2026-10-10 21:32:00 +02:00
commit 2b9e58beee
822 files changed
+62544

No files matched your search

@@ -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