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,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class BalanceTransactionCreated extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::BALANCE_TRANSACTION_CREATED;
}
}
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use DateTimeImmutable;
use Mollie\Api\Contracts\Connector;
use Mollie\Api\Http\Data\DateTime;
use Mollie\Api\Resources\BaseResource;
use Mollie\Api\Webhooks\WebhookEntity;
use Mollie\Api\Webhooks\WebhookSnapshotOrigin;
abstract class BaseEvent
{
public string $id;
public string $entityId;
public DateTime $createdAt;
public object $links;
public ?WebhookEntity $entity;
/**
* The X-Mollie-Signature header captured when the webhook was
* validated. Null for legacy/unsigned deliveries or when the
* caller did not thread the signature through
* {@see \Mollie\Api\Webhooks\WebhookEventMapper::processPayload()}.
*/
public ?string $signature;
/**
* The timestamp at which the SDK first saw this webhook payload.
* Defaults to "now" when not supplied.
*/
public DateTimeImmutable $receivedAt;
public function __construct(
string $id,
string $entityId,
DateTime $createdAt,
object $links,
?WebhookEntity $entity = null,
?string $signature = null,
?DateTimeImmutable $receivedAt = null
) {
$this->id = $id;
$this->entityId = $entityId;
$this->createdAt = $createdAt;
$this->links = $links;
$this->entity = $entity;
$this->signature = $signature;
$this->receivedAt = $receivedAt ?? new DateTimeImmutable;
}
abstract public static function type(): string;
public function entity(): WebhookEntity
{
return $this->getEntitySafely();
}
public function entityData(?string $key = null): mixed
{
return $this->getEntitySafely()->getData($key);
}
/**
* Hydrate the embedded entity into a fully-typed SDK resource,
* propagating the rich webhook origin (event id, signature,
* received-at). Throws if the webhook delivery was "simple" and
* carried no embedded entity.
*/
public function asResource(Connector $connector): BaseResource
{
return $this->entity()->asResource(
$connector,
new WebhookSnapshotOrigin(
$connector,
$this->id,
$this->signature,
$this->receivedAt
)
);
}
private function getEntitySafely(): WebhookEntity
{
$this->guardAgainstMissingEntity();
/** @var WebhookEntity $entity */
$entity = $this->entity;
return $entity;
}
private function guardAgainstMissingEntity()
{
if (! $this->entity) {
throw new \Exception('Event entity not found. Make sure to subscribe to full event payloads.');
}
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class BusinessAccountTransferBlocked extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::BUSINESS_ACCOUNT_TRANSFER_BLOCKED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class BusinessAccountTransferFailed extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::BUSINESS_ACCOUNT_TRANSFER_FAILED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class BusinessAccountTransferInitiated extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::BUSINESS_ACCOUNT_TRANSFER_INITIATED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class BusinessAccountTransferPendingReview extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::BUSINESS_ACCOUNT_TRANSFER_PENDING_REVIEW;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class BusinessAccountTransferProcessed extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::BUSINESS_ACCOUNT_TRANSFER_PROCESSED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class BusinessAccountTransferRequested extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::BUSINESS_ACCOUNT_TRANSFER_REQUESTED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class BusinessAccountTransferReturned extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::BUSINESS_ACCOUNT_TRANSFER_RETURNED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class ConnectBalanceTransferFailed extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::CONNECT_BALANCE_TRANSFER_FAILED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class ConnectBalanceTransferSucceeded extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::CONNECT_BALANCE_TRANSFER_SUCCEEDED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class DisputeCreated extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::DISPUTE_CREATED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class DisputeResolved extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::DISPUTE_RESOLVED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class DisputeUpdated extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::DISPUTE_UPDATED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class FileAccepted extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::FILE_ACCEPTED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class FileFailed extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::FILE_FAILED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class FileRejected extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::FILE_REJECTED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class PaymentLinkPaid extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::PAYMENT_LINK_PAID;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class PayoutCanceled extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::PAYOUT_CANCELED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class PayoutCompleted extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::PAYOUT_COMPLETED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class PayoutFailed extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::PAYOUT_FAILED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class PayoutInitiated extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::PAYOUT_INITIATED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class PayoutProcessingAtBank extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::PAYOUT_PROCESSING_AT_BANK;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class ProfileBlocked extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::PROFILE_BLOCKED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class ProfileCreated extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::PROFILE_CREATED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class ProfileDeleted extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::PROFILE_DELETED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class ProfileVerified extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::PROFILE_VERIFIED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class SalesInvoiceCanceled extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::SALES_INVOICE_CANCELED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class SalesInvoiceCreated extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::SALES_INVOICE_CREATED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class SalesInvoiceIssued extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::SALES_INVOICE_ISSUED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class SalesInvoicePaid extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::SALES_INVOICE_PAID;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class UnmatchedCreditTransferExpired extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::UNMATCHED_CREDIT_TRANSFER_EXPIRED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class UnmatchedCreditTransferMatched extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::UNMATCHED_CREDIT_TRANSFER_MATCHED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class UnmatchedCreditTransferReceived extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::UNMATCHED_CREDIT_TRANSFER_RECEIVED;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks\Events;
use Mollie\Api\Webhooks\WebhookEventType;
class UnmatchedCreditTransferReturned extends BaseEvent
{
public static function type(): string
{
return WebhookEventType::UNMATCHED_CREDIT_TRANSFER_RETURNED;
}
}
@@ -0,0 +1,163 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks;
use Mollie\Api\Exceptions\InvalidSignatureException;
use Mollie\Api\Http\Data\DataCollection;
use Mollie\Api\Utils\Arr;
use Psr\Http\Message\RequestInterface;
class SignatureValidator
{
/**
* Signature header name.
*/
public const SIGNATURE_HEADER = 'X-Mollie-Signature';
/**
* Signature prefix in header.
*/
private const SIGNATURE_PREFIX = 'sha256=';
/**
* Signing secret(s) used to verify signatures.
* Can be a single string or an array of strings for migration periods.
*
* @var string[]
*/
private array $signingSecrets;
/**
* Create a new WebhookSignatureVerifier instance.
*
* @param string|string[] $signingSecrets One or more signing secrets
*/
public function __construct($signingSecrets)
{
$this->signingSecrets = Arr::wrap($signingSecrets);
}
/**
* Static method for simpler usage.
*
* @param RequestInterface|string $input PSR-7 request or raw payload
* @param string|string[] $signingSecrets One or more signing secrets
* @param string|string[]|null $signatures Required if $input is a string payload
* @return bool True if valid signature or legacy webhook
*
* @throws InvalidSignatureException If all signatures are invalid
*/
public static function validate($input, $signingSecrets, $signatures = null): bool
{
$verifier = new self($signingSecrets);
if ($input instanceof RequestInterface) {
return $verifier->validateRequest($input);
}
if (is_string($input) && ($signatures !== null)) {
return $verifier->validatePayload($input, $signatures);
}
throw new InvalidSignatureException('Unsupported input type');
}
/**
* Verify a PSR-7 compatible request.
*
* @param RequestInterface $request The PSR-7 request
* @return bool True if valid, false if legacy webhook (no signature)
*
* @throws InvalidSignatureException If signature validation fails
*/
public function validateRequest(RequestInterface $request): bool
{
$body = (string) $request->getBody();
$signatures = $request->getHeader(self::SIGNATURE_HEADER);
if (empty($signatures)) {
// No signatures found - treat as legacy webhook
return false;
}
return $this->validateSignatures($body, $signatures);
}
/**
* Verify webhook payload with provided signature(s).
*
* @param string $payload Raw request body
* @param string|string[]|null $signatures One or more signatures to validate
* @return bool True if any signature is valid
*
* @throws InvalidSignatureException If all signatures are invalid
*/
public function validatePayload(string $payload, $signatures): bool
{
$signatures = is_array($signatures) ? $signatures : array_filter([$signatures]);
if (empty($signatures)) {
// No signatures found - treat as legacy webhook
return false;
}
return $this->validateSignatures($payload, $signatures);
}
/**
* Verify signatures against all configured signing secrets.
*
* @param string $payload The raw request payload
* @param array $signatures The signatures to verify
* @return bool True if any signature matches any secret
*
* @throws InvalidSignatureException If all signatures are invalid
*/
private function validateSignatures(string $payload, array $signatures): bool
{
$validSignatureFound = DataCollection::collect($signatures)
->contains(fn ($signatureHeader) => $this->isValidSignature(
$this->extractSignature($signatureHeader),
$payload
));
if (! $validSignatureFound && ! empty($signatures)) {
throw new InvalidSignatureException('Invalid webhook signature');
}
return $validSignatureFound;
}
/**
* Extract the raw signature from a signature header.
*/
private function extractSignature(string $signatureHeader): string
{
return strpos($signatureHeader, self::SIGNATURE_PREFIX) === 0
? substr($signatureHeader, strlen(self::SIGNATURE_PREFIX))
: $signatureHeader;
}
/**
* Check if a signature is valid against any of our signing secrets.
*/
private function isValidSignature(string $providedSignature, string $payload): bool
{
return DataCollection::collect($this->signingSecrets)
->contains(function ($secret) use ($payload, $providedSignature) {
$expectedSignature = self::createSignature($payload, $secret);
return hash_equals($expectedSignature, $providedSignature);
});
}
/**
* Create a signature for a given payload and secret.
*/
public static function createSignature(string $payload, string $secret): string
{
return hash_hmac('sha256', $payload, $secret);
}
}
@@ -0,0 +1,37 @@
<?php
namespace Mollie\Api\Webhooks;
use Mollie\Api\Resources\BaseResource;
use Mollie\Api\Resources\ResourceHydrator;
/**
* Thin adapter that feeds a webhook snapshot array through the main
* {@see ResourceHydrator}. The only transformation performed is a
* `json_decode(json_encode(...))` round-trip which produces the same
* nested-stdClass shape that `Response::json()` produces from an HTTP
* body. That makes `$payment->amount->value` (object notation, used
* throughout the docs and recipes) work identically across origins.
*/
final class SnapshotHydrator
{
private ResourceHydrator $inner;
public function __construct(?ResourceHydrator $inner = null)
{
$this->inner = $inner ?? new ResourceHydrator;
}
/**
* @param array<string, mixed> $snapshot
*/
public function hydrate(
BaseResource $resource,
array $snapshot,
WebhookSnapshotOrigin $origin
): BaseResource {
$tree = json_decode(json_encode($snapshot));
return $this->inner->hydrate($resource, $tree, $origin);
}
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks;
use DateTimeImmutable;
use Mollie\Api\Config;
use Mollie\Api\Contracts\Connector;
use Mollie\Api\Resources\AnyResource;
use Mollie\Api\Resources\BaseResource;
use Mollie\Api\Resources\ResourceFactory;
use Mollie\Api\Utils\Arr;
use Mollie\Api\Utils\Utility;
class WebhookEntity
{
private string $resourceType;
private string $id;
private array $data;
public function __construct(string $resourceType, string $id, array $data)
{
$this->resourceType = $resourceType;
$this->id = $id;
$this->data = $data;
}
public function isInTestmode(): bool
{
return $this->getData('mode') === 'test';
}
/**
* Create an entity representation from webhook embedded entity data.
*
* @param array|object $entityData
*/
public static function create($entityData): WebhookEntity
{
$data = Utility::transform($entityData, fn ($data) => is_object($data) ? (array) $data : $data, null, []);
$resourceType = Arr::get($data, 'resource');
$id = Arr::get($data, 'id');
return new WebhookEntity($resourceType, $id, $data);
}
public function getResourceType(): string
{
return $this->resourceType;
}
public function getId(): string
{
return $this->id;
}
/**
* @return mixed
*/
public function getData(?string $key = null)
{
if ($key) {
return Arr::get($this->data, $key);
}
return $this->data;
}
/**
* Hydrate this entity into a fully-typed SDK resource using the embedded
* snapshot. No HTTP call is made — the signed webhook payload already
* contains the full resource state at event time.
*
* The caller may supply a pre-built {@see WebhookSnapshotOrigin} to
* record real event metadata (id, signature, received-at). When omitted
* a null-signature fallback origin is constructed so ad-hoc or test
* usages outside the {@see WebhookEventMapper} flow keep working.
*/
public function asResource(Connector $connector, ?WebhookSnapshotOrigin $origin = null): BaseResource
{
$targetClass = $this->resolveTargetResourceClass();
$resource = ResourceFactory::create($connector, $targetClass);
$origin = $origin ?? new WebhookSnapshotOrigin(
$connector,
'unknown',
null,
new DateTimeImmutable
);
return (new SnapshotHydrator)->hydrate($resource, $this->data, $origin);
}
private function resolveTargetResourceClass(): string
{
return Config::resourceRegistry()->for($this->resourceType) ?? AnyResource::class;
}
}
@@ -0,0 +1,214 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks;
use DateTimeImmutable;
use Mollie\Api\Http\Data\DateTime;
use Mollie\Api\Utils\Arr;
use Mollie\Api\Utils\Utility;
use Mollie\Api\Webhooks\Events\BalanceTransactionCreated;
use Mollie\Api\Webhooks\Events\BaseEvent;
use Mollie\Api\Webhooks\Events\BusinessAccountTransferBlocked;
use Mollie\Api\Webhooks\Events\BusinessAccountTransferFailed;
use Mollie\Api\Webhooks\Events\BusinessAccountTransferInitiated;
use Mollie\Api\Webhooks\Events\BusinessAccountTransferPendingReview;
use Mollie\Api\Webhooks\Events\BusinessAccountTransferProcessed;
use Mollie\Api\Webhooks\Events\BusinessAccountTransferRequested;
use Mollie\Api\Webhooks\Events\BusinessAccountTransferReturned;
use Mollie\Api\Webhooks\Events\ConnectBalanceTransferFailed;
use Mollie\Api\Webhooks\Events\ConnectBalanceTransferSucceeded;
use Mollie\Api\Webhooks\Events\DisputeCreated;
use Mollie\Api\Webhooks\Events\DisputeResolved;
use Mollie\Api\Webhooks\Events\DisputeUpdated;
use Mollie\Api\Webhooks\Events\FileAccepted;
use Mollie\Api\Webhooks\Events\FileFailed;
use Mollie\Api\Webhooks\Events\FileRejected;
use Mollie\Api\Webhooks\Events\PaymentLinkPaid;
use Mollie\Api\Webhooks\Events\PayoutCanceled;
use Mollie\Api\Webhooks\Events\PayoutCompleted;
use Mollie\Api\Webhooks\Events\PayoutFailed;
use Mollie\Api\Webhooks\Events\PayoutInitiated;
use Mollie\Api\Webhooks\Events\PayoutProcessingAtBank;
use Mollie\Api\Webhooks\Events\ProfileBlocked;
use Mollie\Api\Webhooks\Events\ProfileCreated;
use Mollie\Api\Webhooks\Events\ProfileDeleted;
use Mollie\Api\Webhooks\Events\ProfileVerified;
use Mollie\Api\Webhooks\Events\SalesInvoiceCanceled;
use Mollie\Api\Webhooks\Events\SalesInvoiceCreated;
use Mollie\Api\Webhooks\Events\SalesInvoiceIssued;
use Mollie\Api\Webhooks\Events\SalesInvoicePaid;
use Mollie\Api\Webhooks\Events\UnmatchedCreditTransferExpired;
use Mollie\Api\Webhooks\Events\UnmatchedCreditTransferMatched;
use Mollie\Api\Webhooks\Events\UnmatchedCreditTransferReceived;
use Mollie\Api\Webhooks\Events\UnmatchedCreditTransferReturned;
class WebhookEventMapper
{
/** @var array<string, class-string<BaseEvent>> */
private array $map;
public function __construct(array $map = [])
{
$this->setup($map);
}
/**
* Process incoming webhook payload and create the appropriate event handler.
*
* @param array|string $payload The raw webhook payload from POST request
* @param string|null $signature Optional X-Mollie-Signature header value,
* threaded through to the resulting event so downstream code can
* inspect webhook provenance without re-validating.
* @return BaseEvent The specific event handler
* @throws \InvalidArgumentException If payload is invalid
*/
public function processPayload($payload, ?string $signature = null): BaseEvent
{
if (is_string($payload)) {
$payload = json_decode($payload, true);
}
$this->validatePayload($payload);
return $this->resolveEvent(
Arr::get($payload, 'id'),
Arr::get($payload, 'type'),
Arr::get($payload, 'entityId'),
Utility::transform(Arr::get($payload, 'createdAt'), fn (string $timestamp) => new DateTime($timestamp), DateTime::class),
(object) (Arr::get($payload, '_links') ?? []),
$this->createWebhookEntityFromPayload($payload),
$signature,
new DateTimeImmutable
);
}
/**
* Register or override a mapping for a given type string.
*/
public function register(string $type, string $handlerClass): void
{
$this->map[$type] = $handlerClass;
}
/**
* Resolve the concrete event handler for a webhook event.
*
* @return BaseEvent
*/
public function resolveEvent(
string $id,
string $type,
string $entityId,
DateTime $createdAt,
object $links,
?WebhookEntity $entity = null,
?string $signature = null,
?DateTimeImmutable $receivedAt = null
): BaseEvent {
if (! Arr::exists($this->map, $type)) {
throw new \InvalidArgumentException("Unsupported event type: {$type}");
}
/** @var class-string<BaseEvent> $class */
$class = Arr::get($this->map, $type);
return new $class(
$id,
$entityId,
$createdAt,
$links,
$entity,
$signature,
$receivedAt ?? new DateTimeImmutable
);
}
private function setup(array $map): void
{
$this->map = array_merge([
PaymentLinkPaid::type() => PaymentLinkPaid::class,
BalanceTransactionCreated::type() => BalanceTransactionCreated::class,
PayoutInitiated::type() => PayoutInitiated::class,
PayoutProcessingAtBank::type() => PayoutProcessingAtBank::class,
PayoutCompleted::type() => PayoutCompleted::class,
PayoutCanceled::type() => PayoutCanceled::class,
PayoutFailed::type() => PayoutFailed::class,
ConnectBalanceTransferFailed::type() => ConnectBalanceTransferFailed::class,
ConnectBalanceTransferSucceeded::type() => ConnectBalanceTransferSucceeded::class,
DisputeCreated::type() => DisputeCreated::class,
DisputeResolved::type() => DisputeResolved::class,
DisputeUpdated::type() => DisputeUpdated::class,
FileAccepted::type() => FileAccepted::class,
FileRejected::type() => FileRejected::class,
FileFailed::type() => FileFailed::class,
UnmatchedCreditTransferReceived::type() => UnmatchedCreditTransferReceived::class,
UnmatchedCreditTransferMatched::type() => UnmatchedCreditTransferMatched::class,
UnmatchedCreditTransferReturned::type() => UnmatchedCreditTransferReturned::class,
UnmatchedCreditTransferExpired::type() => UnmatchedCreditTransferExpired::class,
BusinessAccountTransferRequested::type() => BusinessAccountTransferRequested::class,
BusinessAccountTransferInitiated::type() => BusinessAccountTransferInitiated::class,
BusinessAccountTransferPendingReview::type() => BusinessAccountTransferPendingReview::class,
BusinessAccountTransferProcessed::type() => BusinessAccountTransferProcessed::class,
BusinessAccountTransferFailed::type() => BusinessAccountTransferFailed::class,
BusinessAccountTransferBlocked::type() => BusinessAccountTransferBlocked::class,
BusinessAccountTransferReturned::type() => BusinessAccountTransferReturned::class,
SalesInvoiceCreated::type() => SalesInvoiceCreated::class,
SalesInvoiceIssued::type() => SalesInvoiceIssued::class,
SalesInvoiceCanceled::type() => SalesInvoiceCanceled::class,
SalesInvoicePaid::type() => SalesInvoicePaid::class,
ProfileCreated::type() => ProfileCreated::class,
ProfileVerified::type() => ProfileVerified::class,
ProfileBlocked::type() => ProfileBlocked::class,
ProfileDeleted::type() => ProfileDeleted::class,
], $map);
}
/**
* Validate that the payload contains required fields.
*
* @param array $payload
* @throws \InvalidArgumentException
*/
private function validatePayload(array $payload): void
{
$requiredFields = ['id', 'type', 'entityId', 'createdAt'];
foreach ($requiredFields as $field) {
if (! Arr::exists($payload, $field) || empty(Arr::get($payload, $field))) {
throw new \InvalidArgumentException("Missing or empty required field: {$field}");
}
}
}
/**
* Create a webhook entity from the embedded data in the payload.
*
* Mollie keys the embedded resource under `_embedded.entity`.
* Iteration is key-agnostic so any future schema tweak (additional
* `_embedded` sub-blocks, renamed key) cannot silently break
* webhook handling; only candidates carrying `id` and `resource`
* are eligible.
*
* @param array $payload
* @return WebhookEntity|null
*/
private function createWebhookEntityFromPayload(array $payload): ?WebhookEntity
{
$embedded = Arr::get($payload, '_embedded', []);
if (! is_array($embedded)) {
return null;
}
foreach ($embedded as $candidate) {
if (is_array($candidate) && isset($candidate['id'], $candidate['resource'])) {
return WebhookEntity::create($candidate);
}
}
return null;
}
}
@@ -0,0 +1,134 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Webhooks;
class WebhookEventType
{
/**
* Payment Link events
*/
public const PAYMENT_LINK_PAID = 'payment-link.paid';
/**
* Balance events
*/
public const BALANCE_TRANSACTION_CREATED = 'balance-transaction.created';
/**
* Payout events
*/
public const PAYOUT_INITIATED = 'payout.initiated';
public const PAYOUT_PROCESSING_AT_BANK = 'payout.processing-at-bank';
public const PAYOUT_COMPLETED = 'payout.completed';
public const PAYOUT_CANCELED = 'payout.canceled';
public const PAYOUT_FAILED = 'payout.failed';
/**
* Connect balance transfer events
*/
public const CONNECT_BALANCE_TRANSFER_FAILED = 'connect-balance-transfer.failed';
public const CONNECT_BALANCE_TRANSFER_SUCCEEDED = 'connect-balance-transfer.succeeded';
/**
* Dispute events
*/
public const DISPUTE_CREATED = 'dispute.created';
public const DISPUTE_RESOLVED = 'dispute.resolved';
public const DISPUTE_UPDATED = 'dispute.updated';
/**
* File events
*/
public const FILE_ACCEPTED = 'file.accepted';
public const FILE_REJECTED = 'file.rejected';
public const FILE_FAILED = 'file.failed';
/**
* Unmatched credit transfer events
*/
public const UNMATCHED_CREDIT_TRANSFER_RECEIVED = 'unmatched-credit-transfer.received';
public const UNMATCHED_CREDIT_TRANSFER_MATCHED = 'unmatched-credit-transfer.matched';
public const UNMATCHED_CREDIT_TRANSFER_RETURNED = 'unmatched-credit-transfer.returned';
public const UNMATCHED_CREDIT_TRANSFER_EXPIRED = 'unmatched-credit-transfer.expired';
/**
* Business account transfer events
*/
public const BUSINESS_ACCOUNT_TRANSFER_REQUESTED = 'business-account-transfer.requested';
public const BUSINESS_ACCOUNT_TRANSFER_INITIATED = 'business-account-transfer.initiated';
public const BUSINESS_ACCOUNT_TRANSFER_PENDING_REVIEW = 'business-account-transfer.pending-review';
public const BUSINESS_ACCOUNT_TRANSFER_PROCESSED = 'business-account-transfer.processed';
public const BUSINESS_ACCOUNT_TRANSFER_FAILED = 'business-account-transfer.failed';
public const BUSINESS_ACCOUNT_TRANSFER_BLOCKED = 'business-account-transfer.blocked';
public const BUSINESS_ACCOUNT_TRANSFER_RETURNED = 'business-account-transfer.returned';
/**
* Sales invoice events
*/
public const SALES_INVOICE_CREATED = 'sales-invoice.created';
public const SALES_INVOICE_ISSUED = 'sales-invoice.issued';
public const SALES_INVOICE_CANCELED = 'sales-invoice.canceled';
public const SALES_INVOICE_PAID = 'sales-invoice.paid';
/**
* Profile event types
*/
public const PROFILE_CREATED = 'profile.created';
public const PROFILE_VERIFIED = 'profile.verified';
public const PROFILE_BLOCKED = 'profile.blocked';
public const PROFILE_DELETED = 'profile.deleted';
/**
* Wildcard for all events
*/
public const ALL = '*';
/**
* Get all available webhook event types.
*
* @return array<int, string>
*/
public static function getAll(): array
{
return [
self::PAYMENT_LINK_PAID,
self::BALANCE_TRANSACTION_CREATED,
self::PAYOUT_INITIATED,
self::PAYOUT_PROCESSING_AT_BANK,
self::PAYOUT_COMPLETED,
self::PAYOUT_CANCELED,
self::PAYOUT_FAILED,
self::CONNECT_BALANCE_TRANSFER_FAILED,
self::CONNECT_BALANCE_TRANSFER_SUCCEEDED,
self::DISPUTE_CREATED,
self::DISPUTE_RESOLVED,
self::DISPUTE_UPDATED,
self::FILE_ACCEPTED,
self::FILE_REJECTED,
self::FILE_FAILED,
self::UNMATCHED_CREDIT_TRANSFER_RECEIVED,
self::UNMATCHED_CREDIT_TRANSFER_MATCHED,
self::UNMATCHED_CREDIT_TRANSFER_RETURNED,
self::UNMATCHED_CREDIT_TRANSFER_EXPIRED,
self::BUSINESS_ACCOUNT_TRANSFER_REQUESTED,
self::BUSINESS_ACCOUNT_TRANSFER_INITIATED,
self::BUSINESS_ACCOUNT_TRANSFER_PENDING_REVIEW,
self::BUSINESS_ACCOUNT_TRANSFER_PROCESSED,
self::BUSINESS_ACCOUNT_TRANSFER_FAILED,
self::BUSINESS_ACCOUNT_TRANSFER_BLOCKED,
self::BUSINESS_ACCOUNT_TRANSFER_RETURNED,
self::SALES_INVOICE_CREATED,
self::SALES_INVOICE_ISSUED,
self::SALES_INVOICE_CANCELED,
self::SALES_INVOICE_PAID,
self::PROFILE_CREATED,
self::PROFILE_VERIFIED,
self::PROFILE_BLOCKED,
self::PROFILE_DELETED,
self::ALL,
];
}
}
@@ -0,0 +1,56 @@
<?php
namespace Mollie\Api\Webhooks;
use DateTimeImmutable;
use Mollie\Api\Contracts\Connector;
use Mollie\Api\Contracts\ResourceOrigin;
/**
* Provenance record for a resource hydrated from a signed webhook
* envelope. Carries the event id, signature (when the caller retained
* it from validation), and the timestamp at which the SDK received the
* webhook. No HTTP response is involved.
*/
final class WebhookSnapshotOrigin implements ResourceOrigin
{
private Connector $connector;
private string $eventId;
private ?string $signature;
private DateTimeImmutable $receivedAt;
public function __construct(
Connector $connector,
string $eventId,
?string $signature,
DateTimeImmutable $receivedAt
) {
$this->connector = $connector;
$this->eventId = $eventId;
$this->signature = $signature;
$this->receivedAt = $receivedAt;
}
public function getConnector(): Connector
{
return $this->connector;
}
public function getEventId(): string
{
return $this->eventId;
}
public function getSignature(): ?string
{
return $this->signature;
}
public function getReceivedAt(): DateTimeImmutable
{
return $this->receivedAt;
}
}