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

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

+5
View File
@@ -0,0 +1,5 @@
{
"require": {
"mollie/mollie-api-php": "^4.0"
}
}
Generated
+669
View File
@@ -0,0 +1,669 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "db4660674af2476cfd22073c1b0ee9d5",
"packages": [
{
"name": "composer/ca-bundle",
"version": "1.5.14",
"source": {
"type": "git",
"url": "https://github.com/composer/ca-bundle.git",
"reference": "0c8abba0634f637bd78c4e451981da368d403463"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/composer/ca-bundle/zipball/0c8abba0634f637bd78c4e451981da368d403463",
"reference": "0c8abba0634f637bd78c4e451981da368d403463",
"shasum": ""
},
"require": {
"ext-openssl": "*",
"ext-pcre": "*",
"php": "^7.2 || ^8.0"
},
"require-dev": {
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^8 || ^9",
"psr/log": "^1.0 || ^2.0 || ^3.0",
"symfony/process": "^4.0 || ^5.0 || ^6.0 || ^7.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "1.x-dev"
}
},
"autoload": {
"psr-4": {
"Composer\\CaBundle\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be"
}
],
"description": "Lets you find a path to the system CA bundle, and includes a fallback to the Mozilla CA bundle.",
"keywords": [
"cabundle",
"cacert",
"certificate",
"ssl",
"tls"
],
"support": {
"irc": "irc://irc.freenode.org/composer",
"issues": "https://github.com/composer/ca-bundle/issues",
"source": "https://github.com/composer/ca-bundle/tree/1.5.14"
},
"funding": [
{
"url": "https://packagist.com",
"type": "custom"
},
{
"url": "https://github.com/composer",
"type": "github"
}
],
"time": "2026-08-21T14:57:29+00:00"
},
{
"name": "mollie/mollie-api-php",
"version": "v4.0.0",
"source": {
"type": "git",
"url": "https://github.com/mollie/mollie-api-php.git",
"reference": "265dfcb58339ec4fec726012ca40c672316bf8de"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/mollie/mollie-api-php/zipball/265dfcb58339ec4fec726012ca40c672316bf8de",
"reference": "265dfcb58339ec4fec726012ca40c672316bf8de",
"shasum": ""
},
"require": {
"composer/ca-bundle": "^1.4",
"ext-curl": "*",
"ext-json": "*",
"ext-openssl": "*",
"nyholm/psr7": "^1.8",
"php": "^8.2",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.1",
"psr/http-message": "^1.1|^2.0",
"symfony/var-dumper": "^5.4|^6.4|^7.2|^8.0"
},
"require-dev": {
"guzzlehttp/guzzle": "^7.6",
"laravel/pint": "1.30.4",
"pestphp/pest": "^3.0",
"phpstan/phpstan": "^2.0",
"phpunit/phpunit": "^11.5"
},
"suggest": {
"mollie/oauth2-mollie-php": "Use OAuth to authenticate with the Mollie API. This is needed for some endpoints. Visit https://docs.mollie.com/ for more information."
},
"type": "library",
"autoload": {
"psr-4": {
"Mollie\\Api\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-2-Clause"
],
"authors": [
{
"name": "Mollie B.V.",
"email": "info@mollie.com"
}
],
"description": "Mollie API client library for PHP. Mollie is a European Payment Service provider and offers international payment methods such as Mastercard, VISA, American Express and PayPal, and local payment methods such as iDEAL, Bancontact, SOFORT Banking, SEPA direct debit, Belfius Direct Net, KBC Payment Button and various gift cards such as Podiumcadeaukaart and fashioncheque.",
"homepage": "https://www.mollie.com/en/developers",
"keywords": [
"Apple Pay",
"CBC",
"Przelewy24",
"api",
"bancontact",
"banktransfer",
"belfius",
"belfius direct net",
"charges",
"creditcard",
"direct debit",
"fashioncheque",
"gateway",
"gift cards",
"ideal",
"inghomepay",
"intersolve",
"kbc",
"klarna",
"mistercash",
"mollie",
"paylater",
"payment",
"payments",
"paypal",
"paysafecard",
"podiumcadeaukaart",
"recurring",
"refunds",
"sepa",
"service",
"sliceit",
"sofort",
"sofortbanking",
"subscriptions"
],
"support": {
"issues": "https://github.com/mollie/mollie-api-php/issues",
"source": "https://github.com/mollie/mollie-api-php/tree/v4.0.0"
},
"time": "2026-09-23T13:16:56+00:00"
},
{
"name": "nyholm/psr7",
"version": "1.8.2",
"source": {
"type": "git",
"url": "https://github.com/Nyholm/psr7.git",
"reference": "a71f2b11690f4b24d099d6b16690a90ae14fc6f3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Nyholm/psr7/zipball/a71f2b11690f4b24d099d6b16690a90ae14fc6f3",
"reference": "a71f2b11690f4b24d099d6b16690a90ae14fc6f3",
"shasum": ""
},
"require": {
"php": ">=7.2",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.1 || ^2.0"
},
"provide": {
"php-http/message-factory-implementation": "1.0",
"psr/http-factory-implementation": "1.0",
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"http-interop/http-factory-tests": "^0.9",
"php-http/message-factory": "^1.0",
"php-http/psr7-integration-tests": "^1.0",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.4",
"symfony/error-handler": "^4.4"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.8-dev"
}
},
"autoload": {
"psr-4": {
"Nyholm\\Psr7\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com"
},
{
"name": "Martijn van der Ven",
"email": "martijn@vanderven.se"
}
],
"description": "A fast PHP7 implementation of PSR-7",
"homepage": "https://tnyholm.se",
"keywords": [
"psr-17",
"psr-7"
],
"support": {
"issues": "https://github.com/Nyholm/psr7/issues",
"source": "https://github.com/Nyholm/psr7/tree/1.8.2"
},
"funding": [
{
"url": "https://github.com/Zegnat",
"type": "github"
},
{
"url": "https://github.com/nyholm",
"type": "github"
}
],
"time": "2024-09-09T07:06:30+00:00"
},
{
"name": "psr/http-client",
"version": "1.0.3",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-client.git",
"reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90",
"reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90",
"shasum": ""
},
"require": {
"php": "^7.0 || ^8.0",
"psr/http-message": "^1.0 || ^2.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Client\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for HTTP clients",
"homepage": "https://github.com/php-fig/http-client",
"keywords": [
"http",
"http-client",
"psr",
"psr-18"
],
"support": {
"source": "https://github.com/php-fig/http-client"
},
"time": "2023-09-23T14:17:50+00:00"
},
{
"name": "psr/http-factory",
"version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-factory.git",
"reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"shasum": ""
},
"require": {
"php": ">=7.1",
"psr/http-message": "^1.0 || ^2.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "PSR-17: Common interfaces for PSR-7 HTTP message factories",
"keywords": [
"factory",
"http",
"message",
"psr",
"psr-17",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-factory"
},
"time": "2024-04-15T12:06:14+00:00"
},
{
"name": "psr/http-message",
"version": "2.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71",
"reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-message/tree/2.0"
},
"time": "2023-04-04T09:54:51+00:00"
},
{
"name": "symfony/deprecation-contracts",
"version": "v3.7.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d",
"reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d",
"shasum": ""
},
"require": {
"php": ">=8.1"
},
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/contracts",
"name": "symfony/contracts"
},
"branch-alias": {
"dev-main": "3.7-dev"
}
},
"autoload": {
"files": [
"function.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.1"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2026-06-05T06:23:12+00:00"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.43.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "4d5d331bf731e0aedbc6b2f5e61135b7b7996a72"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/4d5d331bf731e0aedbc6b2f5e61135b7b7996a72",
"reference": "4d5d331bf731e0aedbc6b2f5e61135b7b7996a72",
"shasum": ""
},
"require": {
"ext-iconv": "*",
"php": ">=7.2"
},
"provide": {
"ext-mbstring": "*"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.43.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2026-09-24T15:19:04+00:00"
},
{
"name": "symfony/var-dumper",
"version": "v7.4.18",
"source": {
"type": "git",
"url": "https://github.com/symfony/var-dumper.git",
"reference": "e088da50b813f32473a76871616cbb8fa54653a8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/var-dumper/zipball/e088da50b813f32473a76871616cbb8fa54653a8",
"reference": "e088da50b813f32473a76871616cbb8fa54653a8",
"shasum": ""
},
"require": {
"php": ">=8.2",
"symfony/deprecation-contracts": "^2.5|^3",
"symfony/polyfill-mbstring": "~1.0"
},
"conflict": {
"symfony/console": "<6.4"
},
"require-dev": {
"symfony/console": "^6.4|^7.0|^8.0",
"symfony/http-kernel": "^6.4|^7.0|^8.0",
"symfony/process": "^6.4|^7.0|^8.0",
"symfony/uid": "^6.4|^7.0|^8.0",
"twig/twig": "^3.12|^4.0"
},
"bin": [
"Resources/bin/var-dump-server"
],
"type": "library",
"autoload": {
"files": [
"Resources/functions/dump.php"
],
"psr-4": {
"Symfony\\Component\\VarDumper\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Provides mechanisms for walking through any arbitrary PHP variable",
"homepage": "https://symfony.com",
"keywords": [
"debug",
"dump"
],
"support": {
"source": "https://github.com/symfony/var-dumper/tree/v7.4.18"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2026-08-30T20:10:52+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": {},
"prefer-stable": false,
"prefer-lowest": false,
"platform": {},
"platform-dev": {},
"plugin-api-version": "2.9.0"
}
+34
View File
@@ -0,0 +1,34 @@
<?php
// ============================================================
// CONFIGURATIE — pas dit aan per verkoopactie
// ============================================================
// Mollie API-sleutel (test_ of live_)
define('MOLLIE_API_KEY', 'test_VtJAw5aSjv2A6PbWGN7mFj66Pkhytz');
// URL van jouw Google Apps Script Web App (zie README)
define('GOOGLE_SCRIPT_URL', 'https://script.google.com/macros/s/AKfycbyJt0uZJxCKCgLh24rhyWvMhv0gARiDGIL1NjO8aYJbMdHJwRmDM58ft_VPbHh8xLBOpg/exec');
// Basisinformatie van de actie
define('ACTIE_NAAM', 'Stroopwafels actie'); // naam op de website en betaalpagina
define('PRODUCT_NAAM', 'Stroopwafels'); // naam op Mollie-betaalpagina
define('PRIJS_PER_STUK', 3.50); // bedrag in euro's per stuk
define('ACTIE_EINDDATUM', '2026-10-11'); // yyyy-mm-dd
// Groepen die de koper kan kiezen
define('GROEPEN', [
'klant van ...',
'welpen',
'verkenners',
'wiva',
'stam',
]);
// URL's (pas aan naar jouw domein)
define('BASE_URL', 'https://quill-bobbed-contend.ngrok-free.dev');
define('RETURN_URL', BASE_URL . '/return.php');
define('WEBHOOK_URL', BASE_URL . '/webhook.php');
// Sessie-instellingen
session_name('verkoopactie');
session_start();
+233
View File
@@ -0,0 +1,233 @@
<?php
require_once 'config.php';
require_once 'vendor/autoload.php';
// ── Controleer of de actie verlopen is ──
$verlopen = strtotime(ACTIE_EINDDATUM) < time();
$errors = [];
if (!$verlopen && $_SERVER['REQUEST_METHOD'] === 'POST') {
$groep = trim($_POST['groep'] ?? '');
$naam_verkoper = trim($_POST['naam_verkoper'] ?? '');
$naam_ouder = trim($_POST['naam_ouder'] ?? '');
$aantal = (int)($_POST['aantal'] ?? 0);
if (!in_array($groep, GROEPEN)) $errors[] = 'Kies een geldige groep.';
if (empty($naam_verkoper)) $errors[] = 'Naam verkoper is verplicht.';
if ($aantal < 1 || $aantal > 10000) $errors[] = 'Aantal moet tussen 1 en 10000 liggen.';
if (empty($errors)) {
$totaal = round($aantal * PRIJS_PER_STUK, 2);
$_SESSION['order'] = [
'groep' => $groep,
'naam_verkoper' => $naam_verkoper,
'naam_ouder' => $naam_ouder,
'aantal' => $aantal,
'totaal' => $totaal,
'datum' => date('Y-m-d H:i:s'),
];
try {
$mollie = new \Mollie\Api\MollieApiClient();
$mollie->setApiKey(MOLLIE_API_KEY);
$payment = $mollie->payments->create([
'amount' => [
'currency' => 'EUR',
'value' => number_format($totaal, 2, '.', ''),
],
'description' => ACTIE_NAAM . ' — ' . $aantal . 'x ' . PRODUCT_NAAM . ' (' . $naam_verkoper . ')',
'redirectUrl' => RETURN_URL,
// 'webhookUrl' => WEBHOOK_URL,
'metadata' => [
'groep' => $groep,
'naam_verkoper' => $naam_verkoper,
'naam_ouder' => $naam_ouder,
'aantal' => $aantal,
'datum' => $_SESSION['order']['datum'],
],
]);
$_SESSION['order']['payment_id'] = $payment->id;
header('Location: ' . $payment->getCheckoutUrl());
exit;
} catch (\Mollie\Api\Exceptions\ApiException $e) {
$errors[] = 'Betaling kon niet worden aangemaakt: ' . htmlspecialchars($e->getMessage());
}
}
}
?>
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bestelling — <?= htmlspecialchars(ACTIE_NAAM) ?></title>
<link rel="stylesheet" href="https://unpkg.com/bootstrap@5.3.3/dist/css/bootstrap.min.css">
</head>
<body class="bg-light">
<section class="bg-light p-3 p-md-4 p-xl-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-12 col-xxl-11">
<div class="card border-light-subtle shadow-sm">
<div class="row g-0">
<!-- Afbeelding links -->
<div class="col-12 col-md-6">
<img class="img-fluid rounded-start w-100 h-100 object-fit-cover"
loading="lazy"
src="/assets/markus.jpg"
alt="<?= htmlspecialchars(ACTIE_NAAM) ?>">
</div>
<!-- Rechterkolom -->
<div class="col-12 col-md-6 d-flex align-items-center justify-content-center">
<div class="col-12 col-lg-11 col-xl-10">
<div class="card-body p-3 p-md-4 p-xl-5">
<div class="mb-4">
<a href="index.php" class="text-secondary text-decoration-none small">← Terug</a>
<h1 class="fs-4 fw-bold mt-2 mb-0">Bestelling plaatsen</h1>
<p class="text-secondary small mt-1">
<?= htmlspecialchars(ACTIE_NAAM) ?> &middot;
€<?= number_format(PRIJS_PER_STUK, 2, ',', '.') ?> per stuk
</p>
</div>
<?php if ($verlopen): ?>
<!-- ── VERLOPEN MELDING ── -->
<div class="text-center py-4">
<div style="font-size:3rem;">⏰</div>
<h2 class="fs-5 fw-bold mt-3 mb-2">De besteltermijn is verlopen</h2>
<p class="text-secondary small">
Bestellingen konden worden geplaatst tot<br>
<strong><?= date('j F Y \o\m H:i', strtotime(ACTIE_EINDDATUM)) ?></strong>.
</p>
<p class="text-secondary small mt-2">
Heb je vragen? Neem contact op met de leiding.
</p>
<a href="index.php" class="btn btn-outline-secondary mt-3">← Terug naar de actiepagina</a>
</div>
<?php else: ?>
<!-- ── NORMAAL FORMULIER ── -->
<?php if (!empty($errors)): ?>
<div class="alert alert-danger py-2">
<ul class="mb-0 ps-3">
<?php foreach ($errors as $err): ?>
<li><?= htmlspecialchars($err) ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<!-- Einddatum banner -->
<div class="alert alert-warning py-2 small mb-3">
⏳ Bestel vóór <strong><?= date('j F Y', strtotime(ACTIE_EINDDATUM)) ?></strong>
</div>
<form method="POST" id="orderForm">
<div class="row gy-3">
<div class="col-12">
<div class="form-floating">
<select class="form-select" name="groep" id="groep" required>
<option value="">— Kies een groep —</option>
<?php foreach (GROEPEN as $g): ?>
<option value="<?= htmlspecialchars($g) ?>"
<?= (($_POST['groep'] ?? '') === $g) ? 'selected' : '' ?>>
<?= htmlspecialchars($g) ?>
</option>
<?php endforeach; ?>
</select>
<label for="groep">Groep</label>
</div>
</div>
<div class="col-12">
<div class="form-floating">
<input type="text" class="form-control" name="naam_verkoper" id="naam_verkoper"
placeholder="Naam verkoper"
value="<?= htmlspecialchars($_POST['naam_verkoper'] ?? '') ?>" required>
<label for="naam_verkoper">Naam verkoper</label>
</div>
</div>
<div class="col-12">
<div class="form-floating">
<input type="text" class="form-control" name="naam_ouder" id="naam_ouder"
placeholder="Naam ouder"
value="<?= htmlspecialchars($_POST['naam_ouder'] ?? '') ?>">
<label for="naam_ouder">Naam ouder <span class="text-secondary fw-normal">(betreft welpen/verkenners)</span></label>
</div>
</div>
<div class="col-12">
<div class="form-floating">
<input type="number" class="form-control" name="aantal" id="aantal"
min="1" max="10000" placeholder="Aantal"
value="<?= htmlspecialchars($_POST['aantal'] ?? '') ?>" required>
<label for="aantal">Aantal stuks</label>
</div>
</div>
<div class="col-12" id="totaalPreview" style="display:none">
<div class="alert alert-success py-2 mb-0">
Totaalbedrag: <strong id="totaalBedrag"></strong>
</div>
</div>
<div class="col-12">
<div class="d-grid">
<button class="btn btn-dark btn-lg" type="submit">
Doorgaan naar betaling →
</button>
</div>
</div>
</div>
</form>
<?php endif; ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<?php if (!$verlopen): ?>
<script>
const aantalInput = document.getElementById('aantal');
const preview = document.getElementById('totaalPreview');
const bedragEl = document.getElementById('totaalBedrag');
const prijs = <?= PRIJS_PER_STUK ?>;
aantalInput.addEventListener('input', () => {
const n = parseInt(aantalInput.value);
if (n > 0) {
bedragEl.textContent = '€' + (n * prijs).toFixed(2).replace('.', ',');
preview.style.display = 'block';
} else {
preview.style.display = 'none';
}
});
if (aantalInput.value) aantalInput.dispatchEvent(new Event('input'));
</script>
<?php endif; ?>
</body>
</html>
+108
View File
@@ -0,0 +1,108 @@
<?php require_once 'config.php'; ?>
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= htmlspecialchars(ACTIE_NAAM) ?></title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
height: 100%;
font-family: 'Segoe UI', sans-serif;
background: #fff;
color: #2c2c2c;
display: flex;
flex-direction: column;
overflow: hidden;
}
.iframe-wrapper {
flex: 1;
overflow: hidden;
position: relative;
}
/* ── Desktop ── */
.iframe-wrapper iframe {
position: absolute;
top: -60px;
left: 50%;
transform: translateX(-50%);
width: 750px;
height: calc(100% + 60px);
border: none;
}
/* ── Mobiel: schaal de iframe zodat 750px past in het scherm ── */
@media (max-width: 750px) {
.iframe-wrapper iframe {
left: 0;
top: -40px;
transform-origin: top left;
transform: scale(var(--iframe-scale, 0.52));
width: 750px;
height: calc((100% + 40px) / var(--iframe-scale, 0.52));
}
}
.bottom-bar {
background: #fff;
border-top: 1px solid #e0e0dc;
padding: 1rem 1.5rem;
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
flex-shrink: 0;
z-index: 10;
}
.bottom-bar .info {
font-size: 0.95rem;
color: #555;
}
.bottom-bar .info strong {
color: #1a1a1a;
font-size: 1.1rem;
}
.btn {
display: inline-block;
background: #3a6b3e;
color: #fff;
text-decoration: none;
padding: 0.8rem 1.5rem;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
white-space: nowrap;
transition: background 0.2s;
}
.btn:hover { background: #2e5431; }
</style>
</head>
<body>
<div class="iframe-wrapper">
<iframe src="https://docs.google.com/document/d/e/2PACX-1vRrsztpT267pPyXb223oW3vaSl1swseXAymcs2ZfTtuYcqGBP4UvTyd8Lud5j3m0A/pub?embedded=true"></iframe>
</div>
<div class="bottom-bar">
<div class="info">
<?= htmlspecialchars(ACTIE_NAAM) ?> &nbsp;·&nbsp;
<strong>€<?= number_format(PRIJS_PER_STUK, 2, ',', '.') ?></strong> per stuk
</div>
<a href="form.php" class="btn">Bestelling plaatsen →</a>
</div>
<script>
function pasSchaalAan() {
if (window.innerWidth <= 750) {
const schaal = window.innerWidth / 750;
document.documentElement.style.setProperty('--iframe-scale', schaal);
}
}
pasSchaalAan();
window.addEventListener('resize', pasSchaalAan);
</script>
</body>
</html>
+103
View File
@@ -0,0 +1,103 @@
<?php
require_once 'config.php';
require_once 'vendor/autoload.php';
$status = 'onbekend';
$payment = null;
$paymentId = $_SESSION['order']['payment_id'] ?? null;
if ($paymentId) {
try {
$mollie = new \Mollie\Api\MollieApiClient();
$mollie->setApiKey(MOLLIE_API_KEY);
$payment = $mollie->payments->get($paymentId);
$status = $payment->status->value;
} catch (\Exception $e) {
$status = 'fout';
}
}
?>
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Betaling — <?= htmlspecialchars(ACTIE_NAAM) ?></title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Segoe UI', sans-serif;
background: #f4f4f2;
color: #2c2c2c;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 2rem;
}
.card {
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0,0,0,0.08);
max-width: 480px;
width: 100%;
padding: 2.5rem;
text-align: center;
}
.icon { font-size: 3rem; margin-bottom: 1rem; }
h1 { font-size: 1.6rem; margin-bottom: 0.6rem; }
p { color: #666; line-height: 1.6; margin-bottom: 1.5rem; }
.detail { font-size: 0.85rem; color: #aaa; margin-bottom: 2rem; }
.btn {
display: inline-block;
background: #3a6b3e;
color: #fff;
text-decoration: none;
padding: 0.8rem 2rem;
border-radius: 8px;
font-weight: 600;
}
.btn-secondary {
background: #e8e8e4;
color: #444;
margin-left: 0.5rem;
}
</style>
</head>
<body>
<div class="card">
<?php if ($status === 'paid'): ?>
<div class="icon">✅</div>
<h1>Betaling geslaagd!</h1>
<p>Bedankt voor je bestelling. De registratie is verwerkt.</p>
<?php if ($payment): ?>
<p class="detail">
Betaald: €<?= htmlspecialchars($payment->amount->value) ?><br>
Referentie: <?= htmlspecialchars($payment->id) ?>
</p>
<?php endif; ?>
<a href="form.php" class="btn">Nieuwe bestelling</a>
<a href="index.php" class="btn btn-secondary">Home</a>
<?php elseif ($status === 'canceled' || $status === 'failed'): ?>
<div class="icon">❌</div>
<h1>Betaling mislukt</h1>
<p>De betaling is geannuleerd of mislukt. Je kunt het opnieuw proberen.</p>
<a href="form.php" class="btn">Opnieuw proberen</a>
<?php elseif ($status === 'open' || $status === 'pending'): ?>
<div class="icon">⏳</div>
<h1>Betaling in behandeling</h1>
<p>Je betaling wordt nog verwerkt. Dit kan enkele minuten duren.</p>
<a href="index.php" class="btn btn-secondary">Terug naar home</a>
<?php else: ?>
<div class="icon">❓</div>
<h1>Status onbekend</h1>
<p>We konden de betaalstatus niet ophalen. Neem contact op als je vragen hebt.</p>
<a href="index.php" class="btn btn-secondary">Terug naar home</a>
<?php endif; ?>
</div>
</body>
</html>
+22
View File
@@ -0,0 +1,22 @@
<?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
throw new RuntimeException($err);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitb2e8b17b7bf14503f0c9e0dffbd1b062::getLoader();
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env php
<?php
/**
* Proxy PHP file generated by Composer
*
* This file includes the referenced bin path (../symfony/var-dumper/Resources/bin/var-dump-server)
* using a stream wrapper to prevent the shebang from being output on PHP<8
*
* @generated
*/
namespace Composer;
$GLOBALS['_composer_bin_dir'] = __DIR__;
$GLOBALS['_composer_autoload_path'] = __DIR__ . '/..'.'/autoload.php';
if (PHP_VERSION_ID < 80000) {
if (!class_exists('Composer\BinProxyWrapper')) {
/**
* @internal
*/
final class BinProxyWrapper
{
private $handle;
private $position;
private $realpath;
public function stream_open($path, $mode, $options, &$opened_path)
{
// get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution
$opened_path = substr($path, 17);
$this->realpath = realpath($opened_path) ?: $opened_path;
$opened_path = $this->realpath;
$this->handle = fopen($this->realpath, $mode);
$this->position = 0;
return (bool) $this->handle;
}
public function stream_read($count)
{
$data = fread($this->handle, $count);
if ($this->position === 0) {
$data = preg_replace('{^#!.*\r?\n}', '', $data);
}
$this->position += strlen($data);
return $data;
}
public function stream_cast($castAs)
{
return $this->handle;
}
public function stream_close()
{
fclose($this->handle);
}
public function stream_lock($operation)
{
return $operation ? flock($this->handle, $operation) : true;
}
public function stream_seek($offset, $whence)
{
if (0 === fseek($this->handle, $offset, $whence)) {
$this->position = ftell($this->handle);
return true;
}
return false;
}
public function stream_tell()
{
return $this->position;
}
public function stream_eof()
{
return feof($this->handle);
}
public function stream_stat()
{
return array();
}
public function stream_set_option($option, $arg1, $arg2)
{
return true;
}
public function url_stat($path, $flags)
{
$path = substr($path, 17);
if (file_exists($path)) {
return stat($path);
}
return false;
}
}
}
if (
(function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true))
|| (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper'))
) {
return include("phpvfscomposer://" . __DIR__ . '/..'.'/symfony/var-dumper/Resources/bin/var-dump-server');
}
}
return include __DIR__ . '/..'.'/symfony/var-dumper/Resources/bin/var-dump-server';
+5
View File
@@ -0,0 +1,5 @@
@ECHO OFF
setlocal DISABLEDELAYEDEXPANSION
SET BIN_TARGET=%~dp0/var-dump-server
SET COMPOSER_RUNTIME_BIN_DIR=%~dp0
php "%BIN_TARGET%" %*
+579
View File
@@ -0,0 +1,579 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var \Closure(string):void */
private static $includeFile;
/** @var string|null */
private $vendorDir;
// PSR-4
/**
* @var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* List of PSR-0 prefixes
*
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
*
* @var array<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var string|null */
private $apcuPrefix;
/**
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return list<string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array<string, string> $classMap Class to filename map
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
$paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
$paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
$paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
$paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
$includeFile = self::$includeFile;
$includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders keyed by their corresponding vendor directories.
*
* @return array<string, self>
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = \Closure::bind(static function($file) {
include $file;
}, null, null);
}
}
+396
View File
@@ -0,0 +1,396 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*
* @final
*/
class InstalledVersions
{
/**
* @var string|null if set (by reflection by Composer), this should be set to the path where this class is being copied to
* @internal
*/
private static $selfDir = null;
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool
*/
private static $installedIsLocalDir;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
// when using reload, we disable the duplicate protection to ensure that self::$installed data is
// always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not,
// so we have to assume it does not, and that may result in duplicate data being returned when listing
// all installed packages for example
self::$installedIsLocalDir = false;
}
/**
* @return string
*/
private static function getSelfDir()
{
if (self::$selfDir === null) {
self::$selfDir = strtr(__DIR__, '\\', '/');
}
return self::$selfDir;
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
$copiedLocalDir = false;
if (self::$canGetVendors) {
$selfDir = self::getSelfDir();
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
$vendorDir = strtr($vendorDir, '\\', '/');
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
self::$installedByVendor[$vendorDir] = $required;
$installed[] = $required;
if (self::$installed === null && $vendorDir.'/composer' === $selfDir) {
self::$installed = $required;
self::$installedIsLocalDir = true;
}
}
if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) {
$copiedLocalDir = true;
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array() && !$copiedLocalDir) {
$installed[] = self::$installed;
}
return $installed;
}
}
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+10
View File
@@ -0,0 +1,10 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
);
+12
View File
@@ -0,0 +1,12 @@
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'667aeda72477189d0494fecd327c3641' => $vendorDir . '/symfony/var-dumper/Resources/functions/dump.php',
);
+9
View File
@@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);
+16
View File
@@ -0,0 +1,16 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Component\\VarDumper\\' => array($vendorDir . '/symfony/var-dumper'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'),
'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'),
'Nyholm\\Psr7\\' => array($vendorDir . '/nyholm/psr7/src'),
'Mollie\\Api\\' => array($vendorDir . '/mollie/mollie-api-php/src'),
'Composer\\CaBundle\\' => array($vendorDir . '/composer/ca-bundle/src'),
);
+50
View File
@@ -0,0 +1,50 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitb2e8b17b7bf14503f0c9e0dffbd1b062
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInitb2e8b17b7bf14503f0c9e0dffbd1b062', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInitb2e8b17b7bf14503f0c9e0dffbd1b062', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitb2e8b17b7bf14503f0c9e0dffbd1b062::getInitializer($loader));
$loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInitb2e8b17b7bf14503f0c9e0dffbd1b062::$files;
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
require $file;
}
}, null, null);
foreach ($filesToLoad as $fileIdentifier => $file) {
$requireFile($fileIdentifier, $file);
}
return $loader;
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitb2e8b17b7bf14503f0c9e0dffbd1b062
{
public static $files = array (
'6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'667aeda72477189d0494fecd327c3641' => __DIR__ . '/..' . '/symfony/var-dumper/Resources/functions/dump.php',
);
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Symfony\\Polyfill\\Mbstring\\' => 26,
'Symfony\\Component\\VarDumper\\' => 28,
),
'P' =>
array (
'Psr\\Http\\Message\\' => 17,
'Psr\\Http\\Client\\' => 16,
),
'N' =>
array (
'Nyholm\\Psr7\\' => 12,
),
'M' =>
array (
'Mollie\\Api\\' => 11,
),
'C' =>
array (
'Composer\\CaBundle\\' => 18,
),
);
public static $prefixDirsPsr4 = array (
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Symfony\\Component\\VarDumper\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/var-dumper',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-factory/src',
1 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Psr\\Http\\Client\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-client/src',
),
'Nyholm\\Psr7\\' =>
array (
0 => __DIR__ . '/..' . '/nyholm/psr7/src',
),
'Mollie\\Api\\' =>
array (
0 => __DIR__ . '/..' . '/mollie/mollie-api-php/src',
),
'Composer\\CaBundle\\' =>
array (
0 => __DIR__ . '/..' . '/composer/ca-bundle/src',
),
);
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitb2e8b17b7bf14503f0c9e0dffbd1b062::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitb2e8b17b7bf14503f0c9e0dffbd1b062::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInitb2e8b17b7bf14503f0c9e0dffbd1b062::$classMap;
}, null, ClassLoader::class);
}
}
+19
View File
@@ -0,0 +1,19 @@
Copyright (C) 2016 Composer
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+85
View File
@@ -0,0 +1,85 @@
composer/ca-bundle
==================
Small utility library that lets you find a path to the system CA bundle,
and includes a fallback to the Mozilla CA bundle.
Originally written as part of [composer/composer](https://github.com/composer/composer),
now extracted and made available as a stand-alone library.
Installation
------------
Install the latest version with:
```bash
$ composer require composer/ca-bundle
```
Requirements
------------
* PHP 5.3.2 is required but using the latest version of PHP is highly recommended.
Basic usage
-----------
### `Composer\CaBundle\CaBundle`
- `CaBundle::getSystemCaRootBundlePath()`: Returns the system CA bundle path, or a path to the bundled one as fallback
- `CaBundle::getBundledCaBundlePath()`: Returns the path to the bundled CA file
- `CaBundle::validateCaFile($filename)`: Validates a CA file using openssl_x509_parse only if it is safe to use
- `CaBundle::isOpensslParseSafe()`: Test if it is safe to use the PHP function openssl_x509_parse()
- `CaBundle::reset()`: Resets the static caches
#### To use with curl
```php
$curl = curl_init("https://example.org/");
$caPathOrFile = \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath();
if (is_dir($caPathOrFile)) {
curl_setopt($curl, CURLOPT_CAPATH, $caPathOrFile);
} else {
curl_setopt($curl, CURLOPT_CAINFO, $caPathOrFile);
}
$result = curl_exec($curl);
```
#### To use with php streams
```php
$opts = array(
'http' => array(
'method' => "GET"
)
);
$caPathOrFile = \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath();
if (is_dir($caPathOrFile)) {
$opts['ssl']['capath'] = $caPathOrFile;
} else {
$opts['ssl']['cafile'] = $caPathOrFile;
}
$context = stream_context_create($opts);
$result = file_get_contents('https://example.com', false, $context);
```
#### To use with Guzzle
```php
$client = new \GuzzleHttp\Client([
\GuzzleHttp\RequestOptions::VERIFY => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath()
]);
```
License
-------
composer/ca-bundle is licensed under the MIT License, see the LICENSE file for details.
+54
View File
@@ -0,0 +1,54 @@
{
"name": "composer/ca-bundle",
"description": "Lets you find a path to the system CA bundle, and includes a fallback to the Mozilla CA bundle.",
"type": "library",
"license": "MIT",
"keywords": [
"cabundle",
"cacert",
"certificate",
"ssl",
"tls"
],
"authors": [
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be"
}
],
"support": {
"irc": "irc://irc.freenode.org/composer",
"issues": "https://github.com/composer/ca-bundle/issues"
},
"require": {
"ext-openssl": "*",
"ext-pcre": "*",
"php": "^7.2 || ^8.0"
},
"require-dev": {
"phpunit/phpunit": "^8 || ^9",
"phpstan/phpstan": "^1.10",
"psr/log": "^1.0 || ^2.0 || ^3.0",
"symfony/process": "^4.0 || ^5.0 || ^6.0 || ^7.0"
},
"autoload": {
"psr-4": {
"Composer\\CaBundle\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Composer\\CaBundle\\": "tests"
}
},
"extra": {
"branch-alias": {
"dev-main": "1.x-dev"
}
},
"scripts": {
"test": "@php phpunit",
"phpstan": "@php phpstan analyse"
}
}
File diff suppressed because it is too large. Load diff
+322
View File
@@ -0,0 +1,322 @@
<?php
/*
* This file is part of composer/ca-bundle.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\CaBundle;
use Psr\Log\LoggerInterface;
use Symfony\Component\Process\PhpProcess;
/**
* @author Chris Smith <chris@cs278.org>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class CaBundle
{
/** @var string|null */
private static $caPath;
/** @var array<string, bool> */
private static $caFileValidity = array();
/**
* Returns the system CA bundle path, or a path to the bundled one
*
* This method was adapted from Sslurp.
* https://github.com/EvanDotPro/Sslurp
*
* (c) Evan Coury <me@evancoury.com>
*
* For the full copyright and license information, please see below:
*
* Copyright (c) 2013, Evan Coury
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @param LoggerInterface $logger optional logger for information about which CA files were loaded
* @return string path to a CA bundle file or directory
*/
public static function getSystemCaRootBundlePath(?LoggerInterface $logger = null)
{
if (self::$caPath !== null) {
return self::$caPath;
}
$caBundlePaths = array();
// If SSL_CERT_FILE env variable points to a valid certificate/bundle, use that.
// This mimics how OpenSSL uses the SSL_CERT_FILE env variable.
$caBundlePaths[] = self::getEnvVariable('SSL_CERT_FILE');
// If SSL_CERT_DIR env variable points to a valid certificate/bundle, use that.
// This mimics how OpenSSL uses the SSL_CERT_FILE env variable.
$caBundlePaths[] = self::getEnvVariable('SSL_CERT_DIR');
$caBundlePaths[] = ini_get('openssl.cafile');
$caBundlePaths[] = ini_get('openssl.capath');
$otherLocations = array(
'/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem', // Fedora, RHEL, CentOS (ca-certificates package) - NEW
'/etc/pki/tls/certs/ca-bundle.crt', // Fedora, RHEL, CentOS (ca-certificates package) - Deprecated
'/etc/ssl/certs/ca-certificates.crt', // Debian, Ubuntu, Gentoo, Arch Linux (ca-certificates package)
'/etc/ssl/ca-bundle.pem', // SUSE, openSUSE (ca-certificates package)
'/usr/ssl/certs/ca-bundle.crt', // Cygwin
'/opt/local/share/curl/curl-ca-bundle.crt', // OS X macports, curl-ca-bundle package
'/usr/local/share/curl/curl-ca-bundle.crt', // Default cURL CA bunde path (without --with-ca-bundle option)
'/usr/share/ssl/certs/ca-bundle.crt', // Really old RedHat?
'/etc/ssl/cert.pem', // OpenBSD
'/usr/local/etc/openssl/cert.pem', // OS X homebrew, openssl package
'/usr/local/etc/openssl@1.1/cert.pem', // OS X homebrew, openssl@1.1 package
'/opt/homebrew/etc/openssl@3/cert.pem', // macOS silicon homebrew, openssl@3 package
'/opt/homebrew/etc/openssl@1.1/cert.pem', // macOS silicon homebrew, openssl@1.1 package
'/etc/pki/tls/certs',
'/etc/ssl/certs', // FreeBSD
);
$caBundlePaths = array_merge($caBundlePaths, $otherLocations);
foreach ($caBundlePaths as $caBundle) {
if ($caBundle && self::caFileUsable($caBundle, $logger)) {
return self::$caPath = $caBundle;
}
if ($caBundle && self::caDirUsable($caBundle, $logger)) {
return self::$caPath = $caBundle;
}
}
return self::$caPath = static::getBundledCaBundlePath(); // Bundled CA file, last resort
}
/**
* Returns the path to the bundled CA file
*
* In case you don't want to trust the user or the system, you can use this directly
*
* @return string path to a CA bundle file
*/
public static function getBundledCaBundlePath()
{
$caBundleFile = __DIR__.'/../res/cacert.pem';
// cURL does not understand 'phar://' paths
// see https://github.com/composer/ca-bundle/issues/10
if (0 === strpos($caBundleFile, 'phar://')) {
$tempCaBundleFile = tempnam(sys_get_temp_dir(), 'openssl-ca-bundle-');
if (false === $tempCaBundleFile) {
throw new \RuntimeException('Could not create a temporary file to store the bundled CA file');
}
file_put_contents(
$tempCaBundleFile,
file_get_contents($caBundleFile)
);
register_shutdown_function(function() use ($tempCaBundleFile) {
@unlink($tempCaBundleFile);
});
$caBundleFile = $tempCaBundleFile;
}
return $caBundleFile;
}
/**
* Validates a CA file using opensl_x509_parse only if it is safe to use
*
* @param string $filename
* @param LoggerInterface $logger optional logger for information about which CA files were loaded
*
* @return bool
*/
public static function validateCaFile($filename, ?LoggerInterface $logger = null)
{
static $warned = false;
if (isset(self::$caFileValidity[$filename])) {
return self::$caFileValidity[$filename];
}
$contents = file_get_contents($filename);
if (is_string($contents) && strlen($contents) > 0) {
$contents = preg_replace("/^(\\-+(?:BEGIN|END))\\s+TRUSTED\\s+(CERTIFICATE\\-+)\$/m", '$1 $2', $contents);
if (null === $contents) {
// regex extraction failed
$isValid = false;
} else {
$isValid = (bool) openssl_x509_parse($contents);
}
} else {
$isValid = false;
}
if ($logger) {
$logger->debug('Checked CA file '.realpath($filename).': '.($isValid ? 'valid' : 'invalid'));
}
return self::$caFileValidity[$filename] = $isValid;
}
/**
* Test if it is safe to use the PHP function openssl_x509_parse().
*
* This checks if OpenSSL extensions is vulnerable to remote code execution
* via the exploit documented as CVE-2013-6420.
*
* @return bool
*/
public static function isOpensslParseSafe()
{
return true;
}
/**
* Resets the static caches
* @return void
*/
public static function reset()
{
self::$caFileValidity = array();
self::$caPath = null;
}
/**
* @param string $name
* @return string|false
*/
private static function getEnvVariable($name)
{
if (isset($_SERVER[$name])) {
return (string) $_SERVER[$name];
}
if (PHP_SAPI === 'cli' && ($value = getenv($name)) !== false && $value !== null) {
return (string) $value;
}
return false;
}
/**
* @param string|false $certFile
* @param LoggerInterface|null $logger
* @return bool
*/
private static function caFileUsable($certFile, ?LoggerInterface $logger = null)
{
return $certFile
&& self::isFile($certFile, $logger)
&& self::isReadable($certFile, $logger)
&& self::validateCaFile($certFile, $logger);
}
/**
* @param string|false $certDir
* @param LoggerInterface|null $logger
* @return bool
*/
private static function caDirUsable($certDir, ?LoggerInterface $logger = null)
{
return $certDir
&& self::isDir($certDir, $logger)
&& self::isReadable($certDir, $logger)
&& self::glob($certDir . '/*', $logger);
}
/**
* @param string $certFile
* @param LoggerInterface|null $logger
* @return bool
*/
private static function isFile($certFile, ?LoggerInterface $logger = null)
{
$isFile = @is_file($certFile);
if (!$isFile && $logger) {
$logger->debug(sprintf('Checked CA file %s does not exist or it is not a file.', $certFile));
}
return $isFile;
}
/**
* @param string $certDir
* @param LoggerInterface|null $logger
* @return bool
*/
private static function isDir($certDir, ?LoggerInterface $logger = null)
{
$isDir = @is_dir($certDir);
if (!$isDir && $logger) {
$logger->debug(sprintf('Checked directory %s does not exist or it is not a directory.', $certDir));
}
return $isDir;
}
/**
* @param string $certFileOrDir
* @param LoggerInterface|null $logger
* @return bool
*/
private static function isReadable($certFileOrDir, ?LoggerInterface $logger = null)
{
$isReadable = @is_readable($certFileOrDir);
if (!$isReadable && $logger) {
$logger->debug(sprintf('Checked file or directory %s is not readable.', $certFileOrDir));
}
return $isReadable;
}
/**
* @param string $pattern
* @param LoggerInterface|null $logger
* @return bool
*/
private static function glob($pattern, ?LoggerInterface $logger = null)
{
$certs = glob($pattern);
if ($certs === false) {
if ($logger) {
$logger->debug(sprintf("An error occurred while trying to find certificates for pattern: %s", $pattern));
}
return false;
}
if (count($certs) === 0) {
if ($logger) {
$logger->debug(sprintf("No CA files found for pattern: %s", $pattern));
}
return false;
}
return true;
}
}
+683
View File
@@ -0,0 +1,683 @@
{
"packages": [
{
"name": "composer/ca-bundle",
"version": "1.5.14",
"version_normalized": "1.5.14.0",
"source": {
"type": "git",
"url": "https://github.com/composer/ca-bundle.git",
"reference": "0c8abba0634f637bd78c4e451981da368d403463"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/composer/ca-bundle/zipball/0c8abba0634f637bd78c4e451981da368d403463",
"reference": "0c8abba0634f637bd78c4e451981da368d403463",
"shasum": ""
},
"require": {
"ext-openssl": "*",
"ext-pcre": "*",
"php": "^7.2 || ^8.0"
},
"require-dev": {
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^8 || ^9",
"psr/log": "^1.0 || ^2.0 || ^3.0",
"symfony/process": "^4.0 || ^5.0 || ^6.0 || ^7.0"
},
"time": "2026-08-21T14:57:29+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "1.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Composer\\CaBundle\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be"
}
],
"description": "Lets you find a path to the system CA bundle, and includes a fallback to the Mozilla CA bundle.",
"keywords": [
"cabundle",
"cacert",
"certificate",
"ssl",
"tls"
],
"support": {
"irc": "irc://irc.freenode.org/composer",
"issues": "https://github.com/composer/ca-bundle/issues",
"source": "https://github.com/composer/ca-bundle/tree/1.5.14"
},
"funding": [
{
"url": "https://packagist.com",
"type": "custom"
},
{
"url": "https://github.com/composer",
"type": "github"
}
],
"install-path": "./ca-bundle"
},
{
"name": "mollie/mollie-api-php",
"version": "v4.0.0",
"version_normalized": "4.0.0.0",
"source": {
"type": "git",
"url": "https://github.com/mollie/mollie-api-php.git",
"reference": "265dfcb58339ec4fec726012ca40c672316bf8de"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/mollie/mollie-api-php/zipball/265dfcb58339ec4fec726012ca40c672316bf8de",
"reference": "265dfcb58339ec4fec726012ca40c672316bf8de",
"shasum": ""
},
"require": {
"composer/ca-bundle": "^1.4",
"ext-curl": "*",
"ext-json": "*",
"ext-openssl": "*",
"nyholm/psr7": "^1.8",
"php": "^8.2",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.1",
"psr/http-message": "^1.1|^2.0",
"symfony/var-dumper": "^5.4|^6.4|^7.2|^8.0"
},
"require-dev": {
"guzzlehttp/guzzle": "^7.6",
"laravel/pint": "1.30.4",
"pestphp/pest": "^3.0",
"phpstan/phpstan": "^2.0",
"phpunit/phpunit": "^11.5"
},
"suggest": {
"mollie/oauth2-mollie-php": "Use OAuth to authenticate with the Mollie API. This is needed for some endpoints. Visit https://docs.mollie.com/ for more information."
},
"time": "2026-09-23T13:16:56+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Mollie\\Api\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-2-Clause"
],
"authors": [
{
"name": "Mollie B.V.",
"email": "info@mollie.com"
}
],
"description": "Mollie API client library for PHP. Mollie is a European Payment Service provider and offers international payment methods such as Mastercard, VISA, American Express and PayPal, and local payment methods such as iDEAL, Bancontact, SOFORT Banking, SEPA direct debit, Belfius Direct Net, KBC Payment Button and various gift cards such as Podiumcadeaukaart and fashioncheque.",
"homepage": "https://www.mollie.com/en/developers",
"keywords": [
"Apple Pay",
"CBC",
"Przelewy24",
"api",
"bancontact",
"banktransfer",
"belfius",
"belfius direct net",
"charges",
"creditcard",
"direct debit",
"fashioncheque",
"gateway",
"gift cards",
"ideal",
"inghomepay",
"intersolve",
"kbc",
"klarna",
"mistercash",
"mollie",
"paylater",
"payment",
"payments",
"paypal",
"paysafecard",
"podiumcadeaukaart",
"recurring",
"refunds",
"sepa",
"service",
"sliceit",
"sofort",
"sofortbanking",
"subscriptions"
],
"support": {
"issues": "https://github.com/mollie/mollie-api-php/issues",
"source": "https://github.com/mollie/mollie-api-php/tree/v4.0.0"
},
"install-path": "../mollie/mollie-api-php"
},
{
"name": "nyholm/psr7",
"version": "1.8.2",
"version_normalized": "1.8.2.0",
"source": {
"type": "git",
"url": "https://github.com/Nyholm/psr7.git",
"reference": "a71f2b11690f4b24d099d6b16690a90ae14fc6f3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Nyholm/psr7/zipball/a71f2b11690f4b24d099d6b16690a90ae14fc6f3",
"reference": "a71f2b11690f4b24d099d6b16690a90ae14fc6f3",
"shasum": ""
},
"require": {
"php": ">=7.2",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.1 || ^2.0"
},
"provide": {
"php-http/message-factory-implementation": "1.0",
"psr/http-factory-implementation": "1.0",
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"http-interop/http-factory-tests": "^0.9",
"php-http/message-factory": "^1.0",
"php-http/psr7-integration-tests": "^1.0",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.4",
"symfony/error-handler": "^4.4"
},
"time": "2024-09-09T07:06:30+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.8-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Nyholm\\Psr7\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com"
},
{
"name": "Martijn van der Ven",
"email": "martijn@vanderven.se"
}
],
"description": "A fast PHP7 implementation of PSR-7",
"homepage": "https://tnyholm.se",
"keywords": [
"psr-17",
"psr-7"
],
"support": {
"issues": "https://github.com/Nyholm/psr7/issues",
"source": "https://github.com/Nyholm/psr7/tree/1.8.2"
},
"funding": [
{
"url": "https://github.com/Zegnat",
"type": "github"
},
{
"url": "https://github.com/nyholm",
"type": "github"
}
],
"install-path": "../nyholm/psr7"
},
{
"name": "psr/http-client",
"version": "1.0.3",
"version_normalized": "1.0.3.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-client.git",
"reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90",
"reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90",
"shasum": ""
},
"require": {
"php": "^7.0 || ^8.0",
"psr/http-message": "^1.0 || ^2.0"
},
"time": "2023-09-23T14:17:50+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Http\\Client\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for HTTP clients",
"homepage": "https://github.com/php-fig/http-client",
"keywords": [
"http",
"http-client",
"psr",
"psr-18"
],
"support": {
"source": "https://github.com/php-fig/http-client"
},
"install-path": "../psr/http-client"
},
{
"name": "psr/http-factory",
"version": "1.1.0",
"version_normalized": "1.1.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-factory.git",
"reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"shasum": ""
},
"require": {
"php": ">=7.1",
"psr/http-message": "^1.0 || ^2.0"
},
"time": "2024-04-15T12:06:14+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "PSR-17: Common interfaces for PSR-7 HTTP message factories",
"keywords": [
"factory",
"http",
"message",
"psr",
"psr-17",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-factory"
},
"install-path": "../psr/http-factory"
},
{
"name": "psr/http-message",
"version": "2.0",
"version_normalized": "2.0.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71",
"reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0"
},
"time": "2023-04-04T09:54:51+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-message/tree/2.0"
},
"install-path": "../psr/http-message"
},
{
"name": "symfony/deprecation-contracts",
"version": "v3.7.1",
"version_normalized": "3.7.1.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d",
"reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d",
"shasum": ""
},
"require": {
"php": ">=8.1"
},
"time": "2026-06-05T06:23:12+00:00",
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/contracts",
"name": "symfony/contracts"
},
"branch-alias": {
"dev-main": "3.7-dev"
}
},
"installation-source": "dist",
"autoload": {
"files": [
"function.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.1"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/deprecation-contracts"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.43.0",
"version_normalized": "1.43.0.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "4d5d331bf731e0aedbc6b2f5e61135b7b7996a72"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/4d5d331bf731e0aedbc6b2f5e61135b7b7996a72",
"reference": "4d5d331bf731e0aedbc6b2f5e61135b7b7996a72",
"shasum": ""
},
"require": {
"ext-iconv": "*",
"php": ">=7.2"
},
"provide": {
"ext-mbstring": "*"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"time": "2026-09-24T15:19:04+00:00",
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"installation-source": "dist",
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.43.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/polyfill-mbstring"
},
{
"name": "symfony/var-dumper",
"version": "v7.4.18",
"version_normalized": "7.4.18.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/var-dumper.git",
"reference": "e088da50b813f32473a76871616cbb8fa54653a8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/var-dumper/zipball/e088da50b813f32473a76871616cbb8fa54653a8",
"reference": "e088da50b813f32473a76871616cbb8fa54653a8",
"shasum": ""
},
"require": {
"php": ">=8.2",
"symfony/deprecation-contracts": "^2.5|^3",
"symfony/polyfill-mbstring": "~1.0"
},
"conflict": {
"symfony/console": "<6.4"
},
"require-dev": {
"symfony/console": "^6.4|^7.0|^8.0",
"symfony/http-kernel": "^6.4|^7.0|^8.0",
"symfony/process": "^6.4|^7.0|^8.0",
"symfony/uid": "^6.4|^7.0|^8.0",
"twig/twig": "^3.12|^4.0"
},
"time": "2026-08-30T20:10:52+00:00",
"bin": [
"Resources/bin/var-dump-server"
],
"type": "library",
"installation-source": "dist",
"autoload": {
"files": [
"Resources/functions/dump.php"
],
"psr-4": {
"Symfony\\Component\\VarDumper\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Provides mechanisms for walking through any arbitrary PHP variable",
"homepage": "https://symfony.com",
"keywords": [
"debug",
"dump"
],
"support": {
"source": "https://github.com/symfony/var-dumper/tree/v7.4.18"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/var-dumper"
}
],
"dev": true,
"dev-package-names": []
}
+122
View File
@@ -0,0 +1,122 @@
<?php return array(
'root' => array(
'name' => '__root__',
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => null,
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => true,
),
'versions' => array(
'__root__' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => null,
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'composer/ca-bundle' => array(
'pretty_version' => '1.5.14',
'version' => '1.5.14.0',
'reference' => '0c8abba0634f637bd78c4e451981da368d403463',
'type' => 'library',
'install_path' => __DIR__ . '/./ca-bundle',
'aliases' => array(),
'dev_requirement' => false,
),
'mollie/mollie-api-php' => array(
'pretty_version' => 'v4.0.0',
'version' => '4.0.0.0',
'reference' => '265dfcb58339ec4fec726012ca40c672316bf8de',
'type' => 'library',
'install_path' => __DIR__ . '/../mollie/mollie-api-php',
'aliases' => array(),
'dev_requirement' => false,
),
'nyholm/psr7' => array(
'pretty_version' => '1.8.2',
'version' => '1.8.2.0',
'reference' => 'a71f2b11690f4b24d099d6b16690a90ae14fc6f3',
'type' => 'library',
'install_path' => __DIR__ . '/../nyholm/psr7',
'aliases' => array(),
'dev_requirement' => false,
),
'php-http/message-factory-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.0',
),
),
'psr/http-client' => array(
'pretty_version' => '1.0.3',
'version' => '1.0.3.0',
'reference' => 'bb5906edc1c324c9a05aa0873d40117941e5fa90',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/http-client',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/http-factory' => array(
'pretty_version' => '1.1.0',
'version' => '1.1.0.0',
'reference' => '2b4765fddfe3b508ac62f829e852b1501d3f6e8a',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/http-factory',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/http-factory-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.0',
),
),
'psr/http-message' => array(
'pretty_version' => '2.0',
'version' => '2.0.0.0',
'reference' => '402d35bcb92c70c026d1a6a9883f06b2ead23d71',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/http-message',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/http-message-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.0',
),
),
'symfony/deprecation-contracts' => array(
'pretty_version' => 'v3.7.1',
'version' => '3.7.1.0',
'reference' => 'f3202fa1b5097b0af062dc978b32ecf63404e31d',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/deprecation-contracts',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-mbstring' => array(
'pretty_version' => 'v1.43.0',
'version' => '1.43.0.0',
'reference' => '4d5d331bf731e0aedbc6b2f5e61135b7b7996a72',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-mbstring',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/var-dumper' => array(
'pretty_version' => 'v7.4.18',
'version' => '7.4.18.0',
'reference' => 'e088da50b813f32473a76871616cbb8fa54653a8',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/var-dumper',
'aliases' => array(),
'dev_requirement' => false,
),
),
);
+25
View File
@@ -0,0 +1,25 @@
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 80200)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.2.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
throw new \RuntimeException(
'Composer detected issues in your platform: ' . implode(' ', $issues)
);
}
+543
View File
@@ -0,0 +1,543 @@
# Changelog
Starting with v3, all notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased](https://github.com/mollie/mollie-api-php/compare/v4.0.0...HEAD)
## [v4.0.0](https://github.com/mollie/mollie-api-php/compare/v4.0.0-beta.3...v4.0.0) - 2026-09-23
The first stable v4 release requires PHP 8.2 or newer. See [UPGRADING.md](UPGRADING.md) for the v3 migration guide and the beta entries below for detailed changes.
### Added
- `PaymentMethod::Wero` brings the v3.14.0 payment method addition to v4. The enum remains SDK vocabulary, not an allow-list; unknown methods still arrive as strings.
### Included from the v4 betas
- String-backed enums, typed resources, readonly value objects, and inferred `MollieApiClient::send()` return types.
- `Money::of()` builders, exponential retries with `Retry-After` handling, improved validation errors, and typed fake responses.
- Profile webhook events, webhook snapshot hydration, and the v3 endpoint additions through v3.13.2.
- Request serialization preserves `0`, `"0"`, and `0.0`; the latest v3 fix is already present in v4. See the beta.2 notes for related request factory behavior.
## [v3.14.0](https://github.com/mollie/mollie-api-php/compare/v3.13.2...v3.14.0) - 2026-09-07
### What's Changed
* fix: support applicationFee on payment link creation by @Naoray in https://github.com/mollie/mollie-api-php/pull/895
* Update signature-verification.md by @fjbender in https://github.com/mollie/mollie-api-php/pull/902
* Do not drop request fields whose value is 0, "0" or 0.0 by @winklemad in https://github.com/mollie/mollie-api-php/pull/907
* fix: repair release changelog automation by @Naoray in https://github.com/mollie/mollie-api-php/pull/909
* Reconcile main with the published v3 releases by @Naoray in https://github.com/mollie/mollie-api-php/pull/912
* Add wero as supported payment method by @robindirksen1 in https://github.com/mollie/mollie-api-php/pull/924
### New Contributors
* @winklemad made their first contribution in https://github.com/mollie/mollie-api-php/pull/907
* @robindirksen1 made their first contribution in https://github.com/mollie/mollie-api-php/pull/924
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.13.0...v3.14.0
## [v4.0.0-beta.3](https://github.com/mollie/mollie-api-php/compare/v4.0.0-beta.2...v4.0.0-beta.3) - 2026-08-26
### Added
- `PaymentStatusReason` value object (`code`, `message`); `Payment::$statusReason` is now `?PaymentStatusReason` instead of an untyped `stdClass`. `->code`/`->message` reads and `json_encode()` keep working; update `instanceof stdClass` checks, any mutation (the object is readonly), and array-only consumers by calling `toArray()`.
- `PaymentMethod` cases `Billink`, `Bizum`, `Mobilepay`, `Vipps`, and `Voucher`. Existing cases are unchanged; the enum documents known SDK vocabulary, not an allow-list.
- `CapabilityStatus::Unrequested` and `Capability::isUnrequested()`.
- `Balance::$pendingAmount` (`?Money`), the amount field the Balance API returns.
- `ResourceHydratableRequest::hydrateInto()` and `::wrapInto()`. Both carry `@phpstan-self-out` and `@psalm-this-out` annotations that PHPStan honors so `send()` infers the re-targeted class or wrapper. `setHydratableResource()` is unchanged but cannot narrow the type.
### Changed
- **`PaymentMethodStatus` and `TerminalPairingCodeStatus` are string-backed enums.** Their `SCREAMING_SNAKE` constants are gone, the same migration the other value sets took in beta.1. `PaymentMethodStatus::NOT_REQUESTED` has no case: `Method::$status` is `null` for a method that was never requested. `TerminalPairingCode::$status` is typed `TerminalPairingCodeStatus|string`.
- `Method::$status` no longer has a `null` default. The API marks the field required (nullable), so an omitted field now stays uninitialized instead of reading as "not requested"; an explicit `null` still means the method was never requested.
### Fixed
- **Nullable enum unions now hydrate to enum cases.** `Enum|string|null` properties resolved as `mixed` and kept the raw API string. Affected: `Payment::$method`, `Payment::$sequenceType`, `Refund::$status`, `Mandate::$status`, `Settlement::$status`, `Profile::$status`, `CurrentProfile::$status`, `Invoice::$status`, `Subscription::$status`, and, after its enum migration, `Method::$status`. Code written against beta.2 that compares these to raw strings must compare with the case or `->value`, or use `Utility::equals()`, which accepts the case or raw value on either side. `MandateCollection::whereStatus()` accepts a `MandateStatus` case or raw string. Unknown values still arrive as strings; `null` is unchanged. `Profile::$categoryCode` (`int|string|null`) keeps the delivered scalar type.
- `Organization::$address`, `$registrationNumber`, and `$vatNumber` are nullable with a `null` default, matching the API contract. Beta.2 threw `TypeError` on `null` and `Error` on an omitted field. `Organization::$locale` stays a required, non-null `string`.
- `Capability::$statusReason` accepts `null`; `Capability::$organizationId` is nullable with a `null` default because the field is not part of the Capability response.
- `Balance` no longer fails on a conformant response: `$incomingAmount` and `$outgoingAmount` (both deprecated because they are not part of the Balance response), `$transferFrequency`, and `$transferThreshold` are nullable with a `null` default.
- Fields the API contract marks nullable or optional no longer throw `TypeError` on `null` or `Error` when omitted: `Terminal::$brand`, `$model`, `$serialNumber` (`?string`); `Terminal::$timezone`, `$locale` (`?string = null`); `Capture::$amount` (`?Money`); `PaymentLink::$profileId` (`?string`); `Webhook::$profileId` (`?string`); `Partner::$partnerType` (`?string`); `Partner::$partnerContractUpdateAvailable` (`?bool = null`); `BalanceTransaction::$deductions` (`?Money = null`); `BalanceTransaction::$mode` (`?string = null`); `Route::$releaseDate` (`?string = null`); `ConnectBalanceTransfer::$category` (`?string = null`); `SalesInvoice::$paymentTerm`, `$currency`, `$webhookUrl` (`?string = null`); and `SalesInvoice::$lines` (`?array = null`). Other `SalesInvoice` fields are unchanged pending further contract review.
- UPGRADING.md no longer prints a Types class count and now documents enum reflection, rebuilding readonly value objects, uninitialized typed properties, wrapped-request inference, and caller-side `strict_types` behavior.
### For contributors
- A test asserts every file under `src/Types/` is a backed enum except the query helpers and `Types\Method`.
- A PHPStan fixture under `tests/` asserts the inferred `send()` types on every analysis run.
## [v4.0.0-beta.2](https://github.com/mollie/mollie-api-php/compare/v4.0.0-beta.1...v4.0.0-beta.2) - 2026-08-25
### Added
- `RateLimit` value object and `Response::rateLimit()` accessor for `RateLimit` and `RateLimit-Policy` response headers.
- `middleware()->onResolved()`, a post-hydration middleware phase for transforms that need the hydrated resource or collection rather than the raw response.
- `Mollie\Api\Utils\Utility::isTrue()`, the shared boolean coercion used for API-facing scalar values such as `testmode` arriving from a query string or payload.
### Changed
- `ExponentialRetryStrategy` skips 429 retries when `Retry-After` exceeds `maxDelayMs` and adds bounded, additive jitter when honoring the header.
- `ExponentialRetryStrategy` applies the `maxDelayMs` cap before exponential full jitter, avoiding a probability spike at the cap.
- **`onResponse()` callbacks now always receive the raw `Response`**, regardless of priority. Move transforms that expect a hydrated resource or collection to `onResolved()`. See [UPGRADING.md](UPGRADING.md) section 3.7.
- **Custom endpoint maps are declared with a class constant.** Subclasses that mutated the protected static `$endpoints` property must override the protected `ENDPOINTS` constant instead. See [UPGRADING.md](UPGRADING.md) section 3.6.
- The one-shot idempotency key is now transferred to the request while it is assembled and cleared from the connector immediately, so a failed or exhausted retry can no longer leak it into a later request. Retries reuse the key already on the assembled request.
- Test mode is resolved once per request, with API-key precedence, so the value observed on the request cannot drift from the value sent to Mollie.
- Balance transaction listing propagates one effective test mode across every list, page and iterator route.
- Request factories resolve values by key presence rather than truthiness, so explicitly supplied falsy values such as `0`, `"0"` and `0.0` are no longer dropped.
- `ResourceRegistry` keeps its class and type indexes consistent, and paginated query factories build their query from one authoritative input map.
### Removed
- `Mollie\Api\Http\Middleware\ResetIdempotencyKey`. It cleared the connector key from the response phase, which never runs when a request throws. Clearing now happens during request assembly, so no replacement is needed. `setIdempotencyKey()` and `resetIdempotencyKey()` are unchanged.
### For contributors
- Formatting moved from PHP-CS-Fixer to [Laravel Pint](https://laravel.com/docs/pint). Run `composer format` to apply and `composer check:format` to verify. The rule set is unchanged, so no reformatting is required on in-flight branches.
- The code style workflow reports violations instead of committing fixes back to the branch, and CI validation reads the repository's real PHPStan and PHPUnit configuration.
- `bin/release` publishes only from an already-merged remote state and honors the operator's tag signing configuration.
- The changelog workflow derives its identity from the release event and triggers on `published`, so pre-releases are no longer skipped.
## [v3.13.2](https://github.com/mollie/mollie-api-php/compare/v3.13.1...v3.13.2) - 2026-08-24
### What's Changed
* Update signature-verification.md by @fjbender in https://github.com/mollie/mollie-api-php/pull/902
* Do not drop request fields whose value is 0, "0" or 0.0 by @winklemad in https://github.com/mollie/mollie-api-php/pull/907
### New Contributors
* @winklemad made their first contribution in https://github.com/mollie/mollie-api-php/pull/907
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.13.1...v3.13.2
## [v4.0.0-beta.1](https://github.com/mollie/mollie-api-php/compare/v3.13.0...v4.0.0-beta.1) - 2026-08-12
PHP 8.2+ modernization. See [UPGRADING.md](UPGRADING.md) for the full guide.
### Breaking changes
- **PHP 8.2+ required.** PHP 7.4, 8.0, 8.1 dropped. CI matrix is 8.2, 8.3, 8.4.
- **Type constants → string-backed enums.** The API value-set classes under `src/Types/` are now `enum ... : string` with `PascalCase` cases (`PaymentStatus::Paid`). `PaymentMethodStatus` and `TerminalPairingCodeStatus` followed after v4.0.0-beta.2; query helpers and `Types\Method` stay classes. Resource `$status`-style properties are typed `EnumName|string`. The `Mollie\Api\Traits\GetAllConstants` trait is removed with this migration — call `cases()` on the enum instead; `BusinessCategory`, `ConnectBalanceTransferCategory`, and `SubscriptionStatus` keep a static `all()` returning the raw values.
- **Resource properties typed.** Fields previously typed `\stdClass` are now concrete value objects. Property names are unchanged — `$payment->amount->value` and `->currency` still work.
- **Value objects are `readonly class`.** `Money`, `Address`, `OrderLine` etc. cannot be subclassed by non-readonly children. Prefer the new `Macroable` extension point.
- **Constructor signatures via promotion.** Named arguments unchanged; positional callers may need to reorder.
- **Typed signatures throughout.** Coercion of your arguments depends on `strict_types` in *your* files, not the SDK's; see UPGRADING.md section 3.3.
- **`Macroable` on `Money`** — undefined methods now throw `BadMethodCallException` instead of PHP's default fatal error.
- **PHPUnit + Paratest → Pest v3** in `require-dev` (consumer impact only if running SDK tests).
### Added
- Generic `@template` return type on `MollieApiClient::send()` — return type inferred from the request class. Resolves [#875](https://github.com/mollie/mollie-api-php/issues/875).
- `Money::of(string $currency)` fluent builder with `minorUnits(int $amount)` and `fromString(string $value)`. Resolves [#876](https://github.com/mollie/mollie-api-php/issues/876).
- `ExponentialRetryStrategy` with optional jitter and HTTP 429 (`Retry-After`) support.
- Typed `MockResponse` factories: `payment(...)`, `customer(...)`, `subscription(...)`, `mandate(...)`, `refund(...)`, `chargeback(...)`, `method(...)`, `paymentLink(...)`, `invoice(...)`, `capture(...)`.
- `Macroable` trait for `Money` (and other value objects) for custom factories without subclassing.
- `ValidationException` exposes per-field errors; `TooManyRequestsException` exposes `retryAfterSeconds`; `Response` exposes header access.
- 4 profile webhook event classes (`ProfileCreated`, `ProfileVerified`, `ProfileBlocked`, `ProfileDeleted`) for constants-to-class parity.
### Changed
- `ResourceHydrator` rewritten reflection-based so it can populate the new typed resource properties (value objects, enums, nested collections). Origin routing (HTTP vs. webhook snapshot) behaves exactly as in v3.13.
- Constructor promotion applied across Request and Exception classes.
### Removed
- PHP 7.4 / 8.0 / 8.1 support.
- Paratest dev dependency (Pest has `--parallel` built in).
- `Mollie\Api\Traits\GetAllConstants` trait — superseded by the enum migration. Use the enum's native `cases()`; `BusinessCategory`, `ConnectBalanceTransferCategory`, and `SubscriptionStatus` keep a static `all()` returning the raw string values.
### Fixed
- Exception messages no longer include invalid authentication tokens or request body contents, while structured exception accessors remain available.
- `docs/webhooks.md` previously stated that `$event->entity()` returns null for simple payloads. It actually throws. Updated to correctly describe reading the nullable `$event->entity` property or fetching the resource via `$event->entityId`.
## [v3.13.1](https://github.com/mollie/mollie-api-php/compare/v3.13.0...v3.13.1) - 2026-06-08
## What's Changed
* fix: support applicationFee on payment link creation by @Naoray in https://github.com/mollie/mollie-api-php/pull/895
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.13.0...v3.13.1
## [v3.13.0](https://github.com/mollie/mollie-api-php/compare/v3.12.0...v3.13.0) - 2026-06-01
## What's Changed
* feat: add terminal pairing code endpoints by @gabrielciobanu-mollie in https://github.com/mollie/mollie-api-php/pull/894
* feat: re-add payouts endpoints (restored after revert) by @Naoray in https://github.com/mollie/mollie-api-php/pull/893
## New Contributors
* @gabrielciobanu-mollie made their first contribution in https://github.com/mollie/mollie-api-php/pull/894
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.12.0...v3.13.0
## [v3.12.0](https://github.com/mollie/mollie-api-php/compare/v3.11.0...v3.12.0) - 2026-05-19
## What's Changed
* fix: add scopes query parameter to list customer mandates by @Naoray in https://github.com/mollie/mollie-api-php/pull/887
* feat: add Google Pay direct integration support by @Naoray in https://github.com/mollie/mollie-api-php/pull/888
* fix: pass settlement pagination filters by @Naoray in https://github.com/mollie/mollie-api-php/pull/889
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.11.0...v3.12.0
## [v3.11.0](https://github.com/mollie/mollie-api-php/compare/v3.10.0...v3.11.0) - 2026-05-06
### Added
- `Mollie\Api\Contracts\ResourceOrigin` marker interface describing where
a hydrated resource came from. `Http\Response` now implements it.
- `BaseResource::getOrigin()` / `setOrigin()` accessors on every hydrated
resource and collection. HTTP-hydrated resources set origin to the
`Response` automatically; no migration needed for existing user code.
- `Mollie\Api\Webhooks\WebhookSnapshotOrigin` exposes the event id,
signature, and received-at timestamp of the webhook that produced a
hydrated resource. Accessible via `$resource->getOrigin()`.
- `Mollie\Api\Webhooks\SnapshotHydrator` feeds a webhook snapshot through
the main `ResourceHydrator` after a one-line `json_decode(json_encode())`
normalization so nested values arrive as stdClass (matching the HTTP
path byte-for-byte).
- `BaseEvent::asResource(Connector)` hydrates the embedded entity into a
fully-typed SDK resource and automatically threads the rich origin
(event id, signature, received-at).
- `WebhookEventMapper::processPayload()` gains an optional `?string $signature` parameter that is threaded through to the resulting event
and carried onto hydrated resources via `WebhookSnapshotOrigin`.
- `ResourceCollection::withOrigin()` factory as the origin-aware sibling
of `withResponse()`.
### Changed
- **BC-implied:** `IsResponseAware::getResponse()` return type narrowed
from `Response` to `?Response`. HTTP-hydrated resources continue to
return a non-null `Response`, matching pre-refactor behavior.
Webhook-hydrated resources return `null`. User code that chains
`$resource->getResponse()->successful()` or similar without a null
check will NPE on webhook-origin resources — audit your webhook
handlers before upgrading. HTTP-only consumers see no change.
- **BC-implied:** `HasResponse::getPendingRequest()` return type
narrowed from `PendingRequest` to `?PendingRequest`. Same rationale.
- `WebhookEntity::asResource()` gains an optional
`?WebhookSnapshotOrigin` second parameter. Callers using the
single-arg form (`$event->entity()->asResource($mollie)`) continue to
work and receive a fallback origin with null signature. Mapper-driven
flow (`$event->asResource($mollie)`) passes the rich origin
automatically.
- Hydrating a webhook payload no longer requires a valid API key on the
connector. Signed snapshots are self-sufficient, so a signing-secret-only
webhook worker can read the snapshot without any key. **Follow-up calls**
(`$payment->refunds()`, `$subscription->payments()`, etc.) still
require an authenticator — they fire real HTTP requests.
- Follow-up methods on hydrated resources (`Payment::refunds/captures/chargebacks`,
`Profile::chargebacks/methods/payments/refunds`, `Subscription::payments`)
now fall back to their endpoint collection when the embedded webhook
snapshot does not carry the corresponding `_links.{name}.href`.
Previously these methods returned an empty collection in that case,
which was a silent behavioural difference between HTTP-origin and
webhook-origin resources. With this change the SDK routes through
the connector using the resource's id (same pattern
`PaymentLink::payments()` already used), so you get a live child
collection on both origins. Relative `_links.{name}.href` values in
webhook payloads are resolved against the client's base URL via
`Url::join`, no special handling required on the caller's side.
### For contributors
- `WebhookEventMapper::createWebhookEntityFromPayload()` switched from
`array_pop($_embedded)` to key-agnostic iteration that picks the first
candidate carrying `id` and `resource` fields. Mollie keys the
embedded entity under `_embedded.entity`; the new iteration resolves
that correctly and is resilient to any future schema tweak (additional
`_embedded` sub-blocks, renamed key) without silently breaking webhook
handling.
### Removed
- `WebhookEntity::buildSyntheticResponse()` and its dependencies on
`PendingRequest`, `DynamicGetRequest`, `Nyholm\Psr7\Request`, and
`Nyholm\Psr7\Response`. Webhook hydration goes through
`SnapshotHydrator`.
- `protected Response $response` property on the `HasResponse` trait.
Storage is now `?ResourceOrigin $origin`; the `getResponse()` accessor
narrows back to `?Response` for callers. Third-party subclasses that
read `$this->response` directly must migrate to `$this->getResponse()`
or `$this->getOrigin()`.
### Fixed
- `docs/webhooks.md` previously stated that `$event->entity()` returns
null for simple payloads. It actually throws. Updated to correctly
describe reading the nullable `$event->entity` property or fetching
the resource via `$event->entityId`.
## What's Changed
* refactor(webhooks): decouple hydrated resources from the HTTP domain by @Naoray in https://github.com/mollie/mollie-api-php/pull/880
* fix(webhooks): hydrate entity locally from signed snapshot by @Naoray in https://github.com/mollie/mollie-api-php/pull/879
* fix: change customer email property type to a nullable string by @edwinvdpol in https://github.com/mollie/mollie-api-php/pull/882
* fix: make all UpdateSalesInvoiceRequest params optional by @Naoray in https://github.com/mollie/mollie-api-php/pull/885
* fix: make all UpdateSalesInvoiceRequest params optional by @fjbender in https://github.com/mollie/mollie-api-php/pull/884
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.10.0...v3.11.0
## [v3.10.0](https://github.com/mollie/mollie-api-php/compare/v3.9.0...v3.10.0) - 2026-04-15
## What's Changed
* Update documentation link for methods API by @sandervanhooft in https://github.com/mollie/mollie-api-php/pull/866
* docs: add full OAuth permission scopes list and link to official reference by @Naoray in https://github.com/mollie/mollie-api-php/pull/867
* docs: fix documentation reference url by @dionnijssen in https://github.com/mollie/mollie-api-php/pull/871
* Fix: Add missing `googlepay` type to wallet constants by @NormanAlbert91 in https://github.com/mollie/mollie-api-php/pull/869
* feat: Add BACS mandate method for UK direct debit support by @sandervanhooft in https://github.com/mollie/mollie-api-php/pull/870
* Fix PHPStan CI: replace ramsey/composer-install with plain composer install by @Naoray in https://github.com/mollie/mollie-api-php/pull/873
* Fix PHP 8+ deprecation warning in CreatePaymentRefundRequest by @Naoray in https://github.com/mollie/mollie-api-php/pull/872
* Fix onFatal callback bug + strict comparison consistency by @Naoray in https://github.com/mollie/mollie-api-php/pull/874
* feat: add lines, addresses and minimumAmount to Payment Links API by @Naoray in https://github.com/mollie/mollie-api-php/pull/877
* feat(sessions): align session endpoint with API specification by @Naoray in https://github.com/mollie/mollie-api-php/pull/858
## New Contributors
* @dionnijssen made their first contribution in https://github.com/mollie/mollie-api-php/pull/871
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.9.0...v3.10.0
## [v3.9.0](https://github.com/mollie/mollie-api-php/compare/v3.8.0...v3.9.0) - 2026-02-09
## What's Changed
* Fix: Don't call deprecated `setAccessible()` by @derrabus in https://github.com/mollie/mollie-api-php/pull/852
* Fix documented `Capability::$requirements` structure by @derrabus in https://github.com/mollie/mollie-api-php/pull/853
* feat(auth): add setToken helper for api keys by @Naoray in https://github.com/mollie/mollie-api-php/pull/859
* Chore/enhance sdk with docs and convenience methods by @Naoray in https://github.com/mollie/mollie-api-php/pull/855
* Fix/wrong payment details attribute by @Naoray in https://github.com/mollie/mollie-api-php/pull/854
* Remove incorrect null return type from ClientLink::getRedirectUrl() by @Naoray in https://github.com/mollie/mollie-api-php/pull/865
* Remove incorrect null return type from ClientLink::getRedirectUrl() by @NormanAlbert91 in https://github.com/mollie/mollie-api-php/pull/862
## New Contributors
* @derrabus made their first contribution in https://github.com/mollie/mollie-api-php/pull/852
* @NormanAlbert91 made their first contribution in https://github.com/mollie/mollie-api-php/pull/862
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.8.0...v3.9.0
## [v3.8.0](https://github.com/mollie/mollie-api-php/compare/v3.7.0...v3.8.0) - 2026-01-06
### What's Changed
* feat: add metadata to connect balance transfer by @Naoray in https://github.com/mollie/mollie-api-php/pull/848
* Fix cURL deprecation notice for PHP 8.5 and higher by @RobinvanderVliet in https://github.com/mollie/mollie-api-php/pull/847
* fix: make TransferParty data accessible for debugging by @Naoray in https://github.com/mollie/mollie-api-php/pull/849
* Sandervanhooft fix/inclusion qr mismatch by @Naoray in https://github.com/mollie/mollie-api-php/pull/851
### New Contributors
* @RobinvanderVliet made their first contribution in https://github.com/mollie/mollie-api-php/pull/847
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.7.0...v3.8.0
## [v3.7.0](https://github.com/mollie/mollie-api-php/compare/v3.6.0...v3.7.0) - 2025-12-01
### What's Changed
* Add GOOGLEPAY and SWISH payment methods by @samdejongobc in https://github.com/mollie/mollie-api-php/pull/844
* Add fromArray to Money by @Naoray in https://github.com/mollie/mollie-api-php/pull/846
### New Contributors
* @samdejongobc made their first contribution in https://github.com/mollie/mollie-api-php/pull/844
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.6.0...v3.7.0
## [v3.6.0](https://github.com/mollie/mollie-api-php/compare/v3.5.0...v3.6.0) - 2025-11-05
### What's Changed
* Feat/add balance transfer webhook events by @sandervanhooft in https://github.com/mollie/mollie-api-php/pull/842
* Fixed webhook docs typo and explained next-gen webhook focus by @sandervanhooft in https://github.com/mollie/mollie-api-php/pull/841
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.5.0...v3.6.0
## [v3.5.0](https://github.com/mollie/mollie-api-php/compare/v3.4.0...v3.5.0) - 2025-10-28
### Added
* Feat/add retry logic by @Naoray in https://github.com/mollie/mollie-api-php/pull/826
* Feat/add fake retain requests option by @Naoray in https://github.com/mollie/mollie-api-php/pull/830
* feat: add isEInvoice param and add support for testmode in all sales-… by @Naoray in https://github.com/mollie/mollie-api-php/pull/832
* feat: add customerId and mandateId to create sales invoice request by @Naoray in https://github.com/mollie/mollie-api-php/pull/834
* Feat/add balance transfer endpoint by @Naoray in https://github.com/mollie/mollie-api-php/pull/831
* Feat/add webhook mapping and events by @Naoray in https://github.com/mollie/mollie-api-php/pull/829
- global Config that serves as a lookup map to easily map resources to their respective collection keys
- `MockEvent` to easily test event handling
- `Str` utility class
- `classBasename` to `Utility`
- `WebhookEntity` to serve as Container for Resource data received through webhooks (-> can be transformed into BaseResource)
- Webhook Events that are instanced via the `WebhookEventMapper`
### Changed
- Feat/make sequence mock responses consume callables by @Naoray in https://github.com/mollie/mollie-api-php/pull/833
### Fixed
* Change include to embed just like in GetPaginatedChargebacksRequest.php #837 by @Naoray in https://github.com/mollie/mollie-api-php/pull/838
* Allow description on CreatePaymentRefundRequest to be empty by @Naoray in https://github.com/mollie/mollie-api-php/pull/839
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.4.0...v3.5.0
## [v3.4.0](https://github.com/mollie/mollie-api-php/compare/v3.3.3...v3.4.0) - 2025-08-13
### What's Changed
* Feat/add new payment route endpoints by @Naoray in https://github.com/mollie/mollie-api-php/pull/825
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.3.3...v3.4.0
## [v3.3.3](https://github.com/mollie/mollie-api-php/compare/v3.3.2...v3.3.3) - 2025-08-12
## What's Changed
* Fix/823 inconsistencies on payment link request by @Naoray in https://github.com/mollie/mollie-api-php/pull/824
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.3.2...v3.3.3
## [v3.3.2](https://github.com/mollie/mollie-api-php/compare/v3.3.1...v3.3.2) - 2025-07-25
## What's Changed
* Fix/819 signature date invalid by @Naoray in https://github.com/mollie/mollie-api-php/pull/820
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.3.1...v3.3.2
## [v3.3.1](https://github.com/mollie/mollie-api-php/compare/v3.3.0...v3.3.1) - 2025-07-25
### What's Changed
* fix: signature validator handling null signatures by @Naoray in https://github.com/mollie/mollie-api-php/pull/822
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.3.0...v3.3.1
## [v3.3.0](https://github.com/mollie/mollie-api-php/compare/v3.2.0...v3.3.0) - 2025-07-25
## What's Changed
* Feat/expose webhook signature header by @Naoray in https://github.com/mollie/mollie-api-php/pull/821
* Feat/expose webhook signature creation by @Naoray
## [v3.2.0](https://github.com/mollie/mollie-api-php/compare/v3.1.5...v3.2.0) - 2025-07-23
### What's Changed
* Feat/add create webhook endpoint by @Naoray in https://github.com/mollie/mollie-api-php/pull/812
* Feat/webhook signature verification by @Naoray in https://github.com/mollie/mollie-api-php/pull/813
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.1.5...v3.2.0
## [v3.1.5](https://github.com/mollie/mollie-api-php/compare/v3.1.4...v3.1.5) - 2025-07-10
### What's Changed
* Fix: allow array of payment methods when creating a payment by @jockri in https://github.com/mollie/mollie-api-php/pull/811
* Sandervanhooft fix/recipe classes by @Naoray in https://github.com/mollie/mollie-api-php/pull/815
* Fix class references on recipes by @sandervanhooft in https://github.com/mollie/mollie-api-php/pull/814
* Fix payment links expiresAt by @sandervanhooft in https://github.com/mollie/mollie-api-php/pull/817
* Change "include" into "embed" on GetPaginatedChargebacksRequest by @sandervanhooft in https://github.com/mollie/mollie-api-php/pull/818
### New Contributors
* @jockri made their first contribution in https://github.com/mollie/mollie-api-php/pull/811
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.1.4...v3.1.5
## [v3.1.4](https://github.com/mollie/mollie-api-php/compare/v3.1.3...v3.1.4) - 2025-06-11
## What's Changed
* Fix 400 Bad Request on DELETE when store array is empty by @cswiers in https://github.com/mollie/mollie-api-php/pull/810
## New Contributors
* @cswiers made their first contribution in https://github.com/mollie/mollie-api-php/pull/810
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.1.3...v3.1.4
## [v3.1.3](https://github.com/mollie/mollie-api-php/compare/v3.1.2...v3.1.3) - 2025-06-11
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.1.3...v3.1.3
## [v3.1.2](https://github.com/mollie/mollie-api-php/compare/v3.1.1...v3.1.2) - 2025-06-10
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.1.1...v3.1.2
## [v3.1.1](https://github.com/mollie/mollie-api-php/compare/v3.1.0...v3.1.1) - 2025-06-10
## What's Changed
* Fix/include resources by @Naoray in https://github.com/mollie/mollie-api-php/pull/808
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.1.0...v3.1.1
## [v3.1.0](https://github.com/mollie/mollie-api-php/compare/v3.0.6...v3.1.0) - 2025-06-05
### What's Changed
* Main by @Naoray in https://github.com/mollie/mollie-api-php/pull/804
* feat: add status reason to payment resource by @Naoray in https://github.com/mollie/mollie-api-php/pull/806
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.0.6...v3.1.0
## [v3.0.6](https://github.com/mollie/mollie-api-php/compare/v1.0.0-test...v3.0.6) - 2025-06-02
### What's Changed
* Amend capturable recipe by @fjbender in https://github.com/mollie/mollie-api-php/pull/796
* fix: exchange wrong request name by @Naoray in https://github.com/mollie/mollie-api-php/pull/797
* Removes nullability from delete() method, as it cannot return null by @Sjustein in https://github.com/mollie/mollie-api-php/pull/802
* fix: use payload instead of query params for testmode by @Naoray in https://github.com/mollie/mollie-api-php/pull/803
### New Contributors
* @Sjustein made their first contribution in https://github.com/mollie/mollie-api-php/pull/802
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.0.5...v3.0.6
## [v3.0.5](https://github.com/mollie/mollie-api-php/compare/v3.0.4...v3.0.5) - 2025-04-27
### What's Changed
* Fix/791 data types may mess up property order by @Naoray in https://github.com/mollie/mollie-api-php/pull/794
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.0.4...v3.0.5
## [v3.0.4](https://github.com/mollie/mollie-api-php/compare/v3.0.3...v3.0.4) - 2025-04-25
### What's Changed
* Chore/allow psr message v1 by @Naoray in https://github.com/mollie/mollie-api-php/pull/793
* Fix/789 remove overhault to resource calls by @Naoray in https://github.com/mollie/mollie-api-php/pull/792
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.0.3...v3.0.4
## [v3.0.3](https://github.com/mollie/mollie-api-php/compare/v3.0.2...v3.0.3) - 2025-04-23
### What's Changed
* Fixed docs links by @sandervanhooft in https://github.com/mollie/mollie-api-php/pull/787
* Feat/small improvements by @Naoray in https://github.com/mollie/mollie-api-php/pull/788
* make `MockResponse` serializable
* add changed `$metadata` handling to upgrade guide
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.0.2...v3.0.3
## [v3.0.2](https://github.com/mollie/mollie-api-php/compare/v3.0.0...v3.0.2) - 2025-04-17
### What's Changed
* handle nullable 422 exception field by @sandervanhooft in https://github.com/mollie/mollie-api-php/pull/786
**Full Changelog**: https://github.com/mollie/mollie-api-php/compare/v3.0.1...v3.0.2
+104
View File
@@ -0,0 +1,104 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
PHP SDK for the Mollie API (https://docs.mollie.com/reference/overview). Supports PHP ^8.2. Namespace: `Mollie\Api`.
## Commands
```bash
# Run all tests (parallel)
composer test # runs: vendor/bin/pest --parallel
# Run a single test file
vendor/bin/pest tests/Path/To/TestFile.php
# Run a single test method
vendor/bin/pest --filter testMethodName tests/Path/To/TestFile.php
# Static analysis (level 5)
vendor/bin/phpstan
# Install dependencies
composer install
```
## Architecture
This SDK has two interaction layers:
### 1. Modern Request Layer (preferred for new code)
Send typed request objects directly via `$client->send()`. Inspired by SaloonPHP.
```
src/Http/Requests/ → Typed request classes (CreatePaymentRequest, GetPaymentRequest, etc.)
src/Http/Request.php → Abstract base class (ResourceHydratableRequest, CollectionHydratableRequest)
src/Http/PendingRequest → Orchestrates the request pipeline
src/Http/Middleware/ → Request/response middleware (auth, hydration, error handling, idempotency)
src/Http/Adapter/ → HTTP client adapters (Guzzle, cURL, PSR-18)
```
### 2. Legacy EndpointCollection Layer
Fluent interface via magic properties on the client (`$client->payments->create(...)`). Delegates to the modern request layer via Factories.
```
src/EndpointCollection/ → Fluent endpoint classes (PaymentEndpointCollection, etc.)
src/Factories/ → Convert unstructured array data → typed Request objects
```
The `HasEndpoints` trait provides `__get()` magic to lazy-load endpoint collections.
### Supporting Code
```
src/MollieApiClient.php → Main entry point, composed via traits
src/Resources/ → Response models (Payment, Customer, etc.) with convenience methods
src/Contracts/ → Interfaces for extensibility (Connector, HttpAdapterContract, etc.)
src/Traits/ → Shared behavior (HandlesAuthentication, SendsRequests, HasMiddleware, etc.)
src/Types/ → Constants and enums (PaymentStatus, PaymentMethod, etc.)
src/Exceptions/ → Custom exception hierarchy (ApiException → specific subtypes)
src/Http/Data/ → Value objects (Money, Address, OrderLine, etc.)
src/Fake/ → Testing utilities (MockMollieClient, MockResponse)
```
### Request Execution Flow
```
MollieApiClient::send(Request)
→ PendingRequest applies handlers (user-agent, headers, auth, testmode)
→ Middleware pipeline (onRequest)
→ HttpAdapter sends HTTP request
→ Middleware pipeline (onResponse: error conversion, hydration)
→ Returns hydrated Resource object
```
### Adding a New Endpoint
1. Create Request class in `src/Http/Requests/` (extend `ResourceHydratableRequest` or `CollectionHydratableRequest`)
2. Create Factory class in `src/Factories/` to bridge array input → typed request
3. Add method to the appropriate `EndpointCollection` in `src/EndpointCollection/`
4. Add Resource class in `src/Resources/` if it's a new resource type
### Testing Pattern
Use the built-in mock client — no real HTTP calls needed:
```php
$client = MollieApiClient::fake([
GetPaymentRequest::class => MockResponse::ok(['resource' => 'payment', ...]),
]);
$payment = $client->send(new GetPaymentRequest('tr_xxx'));
$client->assertSent(GetPaymentRequest::class);
```
Test fixtures live in `tests/Fixtures/`. Documentation and code examples are in `docs/`.
## CI
- **Tests**: Pest v3 across PHP 8.2, 8.3, 8.4
- **Static analysis**: PHPStan level 5 (with baseline)
- **Code style**: Laravel Pint
+8
View File
@@ -0,0 +1,8 @@
Copyright (c) 2013-2016, Mollie B.V.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+155
View File
@@ -0,0 +1,155 @@
<p align="center">
<img src="https://github.com/mollie/mollie-api-php/assets/7265703/140510a5-ede5-41bf-9d77-0d09b906e8f4" width="128" height="128"/>
</p>
<h1 align="center">Mollie API client for PHP</h1>
<div align="center">
[![Build Status](https://github.com/mollie/mollie-api-php/workflows/tests/badge.svg)](https://github.com/mollie/mollie-api-php/actions)
[![Latest Stable Version](https://poser.pugx.org/mollie/mollie-api-php/v/stable)](https://packagist.org/packages/mollie/mollie-api-php)
[![Total Downloads](https://poser.pugx.org/mollie/mollie-api-php/downloads)](https://packagist.org/packages/mollie/mollie-api-php)
[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/mollie/mollie-api-php/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/mollie/mollie-api-php/actions?query=workflow%3A"Fix+Code+Style"+branch%3Amain)
</div>
Accepting [iDEAL](https://www.mollie.com/payments/ideal/), [Apple Pay](https://www.mollie.com/payments/apple-pay), [Google Pay](https://www.mollie.com/payments/googlepay), [Creditcard](https://www.mollie.com/payments/credit-card/), [Bancontact](https://www.mollie.com/payments/bancontact/), [SOFORT Banking](https://www.mollie.com/payments/sofort/), [SEPA Bank transfer](https://www.mollie.com/payments/bank-transfer/), [SEPA Direct debit](https://www.mollie.com/payments/direct-debit/), [PayPal](https://www.mollie.com/payments/paypal/), [Belfius Direct Net](https://www.mollie.com/payments/belfius/), [KBC/CBC](https://www.mollie.com/payments/kbc-cbc/), [paysafecard](https://www.mollie.com/payments/paysafecard/), [ING Home'Pay](https://www.mollie.com/payments/ing-homepay/), [Giropay](https://www.mollie.com/payments/giropay/), [EPS](https://www.mollie.com/payments/eps/), [Przelewy24](https://www.mollie.com/payments/przelewy24/), [Postepay](https://www.mollie.com/en/payments/postepay), [In3](https://www.mollie.com/payments/in3/), [Klarna](https://www.mollie.com/payments/klarna-pay-later/) ([Pay now](https://www.mollie.com/payments/klarna-pay-now/), [Pay later](https://www.mollie.com/payments/klarna-pay-later/), [Slice it](https://www.mollie.com/payments/klarna-slice-it/), [Pay in 3](https://www.mollie.com/payments/klarna-pay-in-3/)), [Giftcard](https://www.mollie.com/payments/gift-cards/) and [Voucher](https://www.mollie.com/en/payments/meal-eco-gift-vouchers) online payments without fixed monthly costs or any punishing registration procedures. Just use the Mollie API to receive payments directly on your website or easily refund transactions to your customers.
## Requirements ##
To use the Mollie API client, the following things are required:
+ Get yourself a free [Mollie account](https://www.mollie.com/signup). No sign up costs.
+ Now you're ready to use the Mollie API client in test mode.
+ Follow [a few steps](https://www.mollie.com/dashboard/?modal=onboarding) to enable payment methods in live mode, and let us handle the rest.
+ PHP >= 8.2
+ cUrl >= 7.19.4
+ Up-to-date OpenSSL (or other SSL/TLS toolkit)
For leveraging [Mollie Connect](https://docs.mollie.com/oauth/overview) (advanced use cases only), we recommend also installing our [OAuth2 client](https://github.com/mollie/oauth2-mollie-php).
## Installation ##
### Using Composer ###
The easiest way to install the Mollie API client is by using [Composer](http://getcomposer.org/doc/00-intro.md). You can require it with the following command:
```bash
composer require mollie/mollie-api-php
```
## Usage ##
Initializing the Mollie API client, and setting your API key.
```php
$mollie = new \Mollie\Api\MollieApiClient();
$mollie->setToken("test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM");
```
The `setToken` method automatically detects whether you're using an API key (`test_`/`live_`) or an OAuth access token (`access_`). You can also use `setApiKey()` or `setAccessToken()` directly if you prefer to be explicit.
Find our full documentation online on [docs.mollie.com](https://docs.mollie.com).
#### Example usage ####
```php
use Mollie\Api\Http\Data\Money;
use Mollie\Api\Http\Requests\CreatePaymentRequest;
use Mollie\Api\Types\PaymentStatus;
$payment = $mollie->send(new CreatePaymentRequest(
description: 'My first API payment',
amount: new Money(currency: 'EUR', value: '10.00'),
redirectUrl: 'https://webshop.example.org/order/12345/',
webhookUrl: 'https://webshop.example.org/mollie-webhook/'
));
if ($payment->status === PaymentStatus::Paid) {
echo "Paid {$payment->amount->value} {$payment->amount->currency}";
}
```
## Documentation
For an in-depth understanding of our API, please explore the [Mollie Developer Portal](https://www.mollie.com/developers). Our API documentation is available in English.
For detailed documentation about using this PHP client, see the following guides:
- [Endpoint Collections](docs/endpoint-collections.md) - Learn how to interact with all available API endpoints.
- [HTTP Adapters](docs/http-adapters.md) - Information on customizing HTTP communication.
- [Idempotency](docs/idempotency.md) - Best practices and setup for idempotent requests.
- [Payments](docs/payments.md) - Comprehensive guide on handling payments.
- [Requests](docs/requests.md) - Overview and usage of request objects in the API client.
- [Responses](docs/responses.md) - Handling and understanding responses from the API.
- [Testing](docs/testing.md) - Guidelines for testing with the Mollie API client.
- [Debugging](docs/debugging.md) - How to debug API requests and responses safely.
- [Webhooks](docs/webhooks.md) - How to process Webhook requests
These guides provide in-depth explanations and examples for advanced usage of the client.
## Recipes
The Mollie API client comes with a variety of recipes to help you understand how to implement various API features. These recipes are a great resource for learning how to integrate Mollie payments into your application.
Here are some of the key recipes included:
- **Payments**: Demonstrates how to handle various payment scenarios.
- [Create a payment](docs/recipes/payments/create-payment.md)
- [Create a capturable payment](docs/recipes/payments/create-capturable-payment.md)
- [Handle webhooks](docs/recipes/payments/handle-webhook.md)
- [Refund payments](docs/recipes/payments/refund-payment.md)
- **Customers**: Shows how to manage customers and their payments.
- [Manage customers](docs/recipes/customers/manage-customers.md)
- [Customer payments](docs/recipes/customers/customer-payments.md)
- **Subscriptions and Recurring Payments**:
- [Manage mandates](docs/recipes/mandates/manage-mandates.md)
- [Manage subscriptions](docs/recipes/subscriptions/manage-subscriptions.md)
For a full list of recipes, please refer to the [recipes directory](docs/recipes/).
These recipes are designed to help you integrate Mollie into your application. Make sure to use your test API keys when testing the integration.
## Upgrading
Please see [UPGRADING](UPGRADING.md) for details.
## Testing
The SDK ships a `MollieApiClient::fake()` helper so you don't need real HTTP calls. The test suite runs on Pest v3:
```bash
vendor/bin/pest --parallel
```
Use the typed `MockResponse` factories for terse, refactor-safe fixtures:
```php
use Mollie\Api\Fake\MockResponse;
use Mollie\Api\Http\Data\Money;
use Mollie\Api\Http\Requests\GetPaymentRequest;
use Mollie\Api\MollieApiClient;
use Mollie\Api\Types\PaymentStatus;
$client = MollieApiClient::fake([
GetPaymentRequest::class => MockResponse::payment(
id: 'tr_xxx',
status: PaymentStatus::Paid,
amount: new Money(currency: 'EUR', value: '10.00'),
),
]);
$payment = $client->send(new GetPaymentRequest('tr_xxx'));
$client->assertSent(GetPaymentRequest::class);
```
See [docs/testing.md](docs/testing.md) for the full reference.
## Contributing to Our API Client ##
Would you like to contribute to improving our API client? We welcome [pull requests](https://github.com/mollie/mollie-api-php/pulls?utf8=%E2%9C%93&q=is%3Apr). But, if you're interested in contributing to a technology-focused organization, Mollie is actively recruiting developers and system engineers. Discover our current [job openings](https://jobs.mollie.com/) or [reach out](mailto:personeel@mollie.com).
## License ##
[BSD (Berkeley Software Distribution) License](https://opensource.org/licenses/bsd-license.php).
Copyright (c) 2013-2018, Mollie B.V.
## Support ##
Contact: [www.mollie.com](https://www.mollie.com) — info@mollie.com — +31 20 820 20 70
+487
View File
@@ -0,0 +1,487 @@
# Upgrading
- [Upgrading from v3 to v4](#upgrading-from-v3-to-v4)
- [Upgrading from v2 to v3](#upgrading-from-v2-to-v3)
# Upgrading from v3 to v4
Use this guide to upgrade an application from v3 to v4. The public surface is largely the same, but PHP language-level changes require a few manual updates in consuming applications. Work through the sections below before deploying v4.
## 1. Set the minimum PHP version
Set your application's PHP requirement to **8.2 or newer**. Remove support for PHP 7.4, 8.0, and 8.1; v4's CI matrix covers PHP 8.2, 8.3, and 8.4.
`composer.json`:
```json
"require": {
"php": "^8.2"
}
```
## 2. High-impact changes
### 2.1 Type constants → enum cases
Every API value set under `src/Types/` is now a PHP **string-backed enum**. Only the query helpers (`ClientQuery`, `MandateQuery`, `MethodQuery`, `PaymentIncludesQuery`, `PaymentQuery`, `TerminalPairingCodeQuery`) and `Mollie\Api\Types\Method` (HTTP verbs) remain constant classes. Change each `SCREAMING_SNAKE` constant reference to its `PascalCase` case:
```php
// v3
if ($payment->status === PaymentStatus::PAID) { /* ... */ }
// v4
use Mollie\Api\Types\PaymentStatus;
if ($payment->status === PaymentStatus::Paid) { /* ... */ }
```
When you read a resource property that holds an API status or type, handle it as `EnumName|string`. The `string` fallback keeps unknown API values from breaking your integration:
```php
public PaymentStatus|string $status;
```
Remove imports and uses of the `Mollie\Api\Traits\GetAllConstants` trait. Use the enum cases directly:
```php
// v3
BusinessCategory::all();
// v4 — generic enum approach
array_column(PaymentStatus::cases(), 'value');
```
Keep calling `::all()` on `BusinessCategory`, `ConnectBalanceTransferCategory`, and `SubscriptionStatus`; these enums retain compatibility methods that return their raw string values. If your own classes imported `GetAllConstants`, replace the trait with a local helper or migrate those classes to enums.
If you enumerated constants through reflection, replace that too. On an enum, `ReflectionClass::getConstants()` returns the **case objects**, not their string values, and `defined()` / `constant()` on the old `SCREAMING_SNAKE` names now fail:
```php
// v3
(new ReflectionClass(PaymentMethod::class))->getConstants(); // ['IDEAL' => 'ideal', ...]
// v4 — the same call returns ['Ideal' => PaymentMethod::Ideal, ...] with no error
array_column(PaymentMethod::cases(), 'value'); // ['ideal', ...] — the replacement
```
`cases()` is the vocabulary this SDK release knows, not an allow-list. Mollie can return a value that is not a case yet; it reaches you as a raw string through the `EnumName|string` property types. `CreatePaymentRequest` accepts a raw string for `method`; `Payment::$method` preserves unknown response values as raw strings. Use the Methods API to learn which methods are enabled on a profile.
`PaymentMethodStatus` and `TerminalPairingCodeStatus` became enums after v4.0.0-beta.2. `PaymentMethodStatus::NOT_REQUESTED` has no case: a method that was never requested has `$method->status === null`. `Method::$status` is required but nullable and has no default. `GetEnabledMethodsRequest` reads it while filtering, so a conformant response must include `status`, using an explicit `null` when the method was not requested; an omitted field is malformed and remains visibly uninitialized.
### 2.2 Resource properties typed (no more `\stdClass`)
Update code that assumes a resource field is an untyped `\stdClass`. **Property names are unchanged** — `$payment->amount->value` and `$payment->amount->currency` still work — but the runtime value is a typed value object.
```php
// v3
$payment->amount; // \stdClass { value: "10.00", currency: "EUR" }
$payment->amount->value; // "10.00"
// v4
$payment->amount; // Mollie\Api\Http\Data\Money
$payment->amount->value; // "10.00" (still works)
$payment->amount->currency; // "EUR" (still works)
```
If your code checks `$amount instanceof \stdClass` or requires an array, update that path and call `$payment->amount->toArray()` where needed. `json_encode($payment->amount)` continues to work because the value object's properties are public.
### 2.3 Value objects are `readonly`: rebuild instead of mutating
`Money`, `Address`, `OrderLine`, and the other classes under `src/Http/Data/` are `readonly class`. Any code that assigned to one of their properties fails with `Cannot modify readonly property`. The place most integrations hit this is `onRequest()` middleware, which runs before the SDK serializes the payload and therefore sees the live value objects. Rebuild the object instead:
```php
use Mollie\Api\Http\Data\Address;
// v3 — worked
$address->email = $this->punycodeEmailDomain($address->email);
// v4 — Cannot modify readonly property; rebuild through fromArray()
$address = Address::fromArray([
...$address->toArray(),
'email' => $this->punycodeEmailDomain($address->email),
]);
```
Subclassing is the second, rarer break:
If you extend `Money`, `Address`, `OrderLine`, or another value object under `src/Http/Data/`, declare the child as `readonly class`; PHP 8.2 does not allow a non-readonly child. Prefer the `Macroable` extension point when you only need to add factory methods.
```php
// v3
class TaxedMoney extends Money { public string $tax; }
// v4 — must also be readonly, or you'll get a fatal error
final readonly class TaxedMoney extends Money {
public function __construct(string $currency, string $value, public string $tax) {
parent::__construct($currency, $value);
}
}
```
Use the **`Macroable`** extension point instead of subclassing when you need to add factory methods:
```php
use Mollie\Api\Http\Data\Money;
Money::macro('platinum', fn (string $value) => new Money('XAU', $value));
$gold = Money::platinum('1.00');
```
See the [custom-money-factory recipe](docs/recipes/money/custom-factory.md).
### 2.4 Typed properties can be uninitialized
Resource properties are typed in v4. When a response omits a field that has no default, reading it no longer returns `null` as in v3; it throws `Error: Typed property Mollie\Api\Resources\... must not be accessed before initialization`. This is the most common runtime break after upgrading and it is invisible at the call site.
Read fields that a partial or malformed response may omit through `isset()` or `??` at the boundary. Both treat an uninitialized typed property as unset instead of throwing:
```php
// v3
$description = $payment->description; // null when the response omitted it
// v4
$description = $payment->description ?? null; // same result, no Error
```
Two caveats. A guard only helps when *your* variable may be null: guarding a value you then pass to a non-nullable parameter moves the failure one line down. The SDK deliberately does **not** default fields the API marks as required (`Payment::$id`, `Organization::$name`, and others): an uninitialized required field means the response was malformed, and hiding it behind `null` would turn a visible failure into wrong data. Where a field has been verified against the API contract, an optional field carries `?T` with a `null` default and a required-but-nullable field carries `?T` without one.
## 3. Medium-impact changes
### 3.1 Generic `send()` return type
Remove manual return-type workarounds around `MollieApiClient::send()`. Its `@template`-based generics let PHPStan infer the concrete return type from the request class.
```php
// v3 — manual cast / @var was needed
/** @var Payment $payment */
$payment = $client->send(new GetPaymentRequest('tr_xxx'));
// v4 — inferred automatically
$payment = $client->send(new GetPaymentRequest('tr_xxx'));
// $payment is Mollie\Api\Resources\Payment
```
Delete the `@var` annotations and manual casts around `send()` calls that only existed to help static analysis.
This holds for wrapped requests too, as long as you use the named methods added after v4.0.0-beta.2. `setHydratableResource(new WrapperResource(...))` returns the request unchanged for static analysis, so `send()` cannot infer the wrapper; `wrapInto()` (and `hydrateInto()` for re-targeting) can:
```php
// inferred: PaymentWrapper
$wrapper = $client->send(
(new GetPaymentRequest('tr_xxx'))->wrapInto(PaymentWrapper::class)
);
// inferred: RefundsWrapper
$wrapped = $client->send(
(new DynamicGetRequest($href))
->hydrateInto(RefundCollection::class)
->wrapInto(RefundsWrapper::class)
);
```
Call request-specific setters first, then `hydrateInto()`, then `wrapInto()` last. Reversing the two named helpers makes static analysis report the hydration target while runtime still returns the wrapper. PHPStan currently honors both the `@phpstan-self-out` and `@psalm-this-out` annotations, and the committed fixture guards their combined inference contract. This repository does not run Psalm, so Psalm behavior is not verified here. PhpStorm does not infer the narrowed type. See [`docs/responses.md`](docs/responses.md#resource-wrappers).
### 3.2 Constructor signatures use property promotion
Review calls to request, exception, and value object constructors. These constructors use PHP 8 property promotion in v4. **Named arguments are unchanged** and continue to work. Reorder positional arguments when a constructor uses a different parameter order.
```php
// v4 — recommended (named args)
new CreatePaymentRequest(
description: 'Order #1',
amount: new Money(currency: 'EUR', value: '10.00'),
);
```
Search for positional constructor calls and verify their argument order before upgrading.
### 3.3 Typed signatures: coercion depends on *your* `strict_types`
v4 signatures are fully typed, but `declare(strict_types=1)` is a property of the **calling** file, not of the SDK. A strict declaration in an SDK file does not make calls from your weak-mode file strict.
```php
// consumer file WITHOUT declare(strict_types=1) — the default in most frameworks
new Money('EUR', 10); // no error; value is coerced to '10' (not '10.00' — Mollie rejects it)
// consumer file WITH declare(strict_types=1)
new Money('EUR', 10); // TypeError: value must be of type string, int given
// correct in both
new Money(currency: 'EUR', value: '10.00');
```
Audit every SDK boundary for scalar coercions: in weak-mode files they are silent and can produce values the API rejects; in strict-mode files they throw. Do not rely on a `TypeError` to catch bad input unless your own file is strict.
### 3.4 `Macroable` on `Money` changes undefined-method behavior
`Money` (and other value objects using `Macroable`) intercept calls to undefined methods. Instead of PHP's default fatal error, you'll get a `BadMethodCallException` with a clear message. This matters only for code that catches `Error` rather than `Exception` around Money calls.
### 3.5 Custom retry strategies must decide retryable exceptions
Update custom implementations of `RetryStrategyContract` with `shouldRetry(Throwable $exception): bool`. Pass the triggering exception to `delayBeforeAttemptMs()` when you need exception-specific backoff:
```php
use Mollie\Api\Exceptions\RetryableNetworkRequestException;
use Throwable;
public function shouldRetry(Throwable $exception): bool
{
return $exception instanceof RetryableNetworkRequestException;
}
public function delayBeforeAttemptMs(int $attempt, ?Throwable $exception = null): int
{
return $attempt * 1000;
}
```
If you provide your own retry strategy, add this method before upgrading. Keep `LinearRetryStrategy` to preserve the v3 default behavior for retryable network failures, or switch to `ExponentialRetryStrategy` if you also want to retry HTTP 429 responses.
### 3.6 Custom endpoint maps use a class constant
If an undocumented `MollieApiClient` subclass directly mutated the protected static `$endpoints` property, replace that mutation with a protected `ENDPOINTS` constant override:
```php
class CustomMollieApiClient extends MollieApiClient
{
protected const ENDPOINTS = [
...parent::ENDPOINTS,
'customPayments' => CustomPaymentEndpointCollection::class,
];
}
```
### 3.7 Response middleware runs in two phases
`onResponse()` callbacks now always receive the raw SDK `Response`, regardless of priority. Move transforms that need a hydrated resource or collection to `onResolved()`.
Before:
```php
$client->middleware()->onResponse(function ($result) {
return $result instanceof MethodCollection
? $result->filter(fn (Method $method) => $method->status !== null)
: $result;
}, MiddlewarePriority::LOW);
```
After:
```php
$client->middleware()->onResolved(function ($result) {
return $result instanceof MethodCollection
? $result->filter(fn (Method $method) => $method->status !== null)
: $result;
}, MiddlewarePriority::LOW);
$client->middleware()->onResponse(function (Response $response): void {
// Inspect the raw HTTP response.
});
```
Returning `null` or returning without a value preserves the current value in both phases. An `onResponse()` callback may otherwise return only `Mollie\Api\Http\Response`; another return type throws `UnexpectedValueException` immediately. Priorities control order only within their own raw or resolved phase.
# Upgrading from v2 to v3
Use this guide to move your application from v2 to v3. Complete the breaking-change updates before switching the dependency to v3.
After the migration, you can use the v3 APIs for modern PHP practices, stronger type safety, and a more predictable developer experience.
## Breaking Changes
### Deprecations
#### MethodEndpointCollection.allActive()
The method `MethodEndpointCollection.allActive()` has been removed. Use `MethodEndpointCollection.allEnabled()` instead.
#### Order endpoint
Replace Order and Shipment endpoint calls with Payment endpoint calls. Mollie removed the Order and Shipment endpoints from `mollie-api-php`, and the Payment endpoint provides the replacement functionality.
- All `/orders/*` endpoints and related classes (`Order*Endpoint`)
- Removed `MollieApiClient` properties:
```php
$client->orderPayments; // Removed
$client->orderRefunds; // Removed
$client->orderLines; // Removed
$client->shipments; // Removed
```
#### Integration code examples
Move any code you copied from `/examples` to the markdown recipes in `/docs/recipes`; v3 uses those recipes as the maintained integration examples.
### Metadata Type Restriction
Change every v2 request that sends metadata as a string or object. Pass metadata as an array in v3 request payloads.
```php
// Before (v2) - Using legacy array approach
$client->payments->create([
"amount" => [
"currency" => "EUR",
"value" => "10.00"
],
"metadata" => "some string" // Worked in v2
]);
// After (v3) - Using legacy array approach
$client->payments->create([
"amount" => [
"currency" => "EUR",
"value" => "10.00"
],
"metadata" => ["key" => "value"] // Only arrays are accepted in v3
]);
// After (v3) - Using request class
use Mollie\Api\Http\Data\Money;
use Mollie\Api\Http\Requests\CreatePaymentRequest;
$request = new CreatePaymentRequest(
description: "My payment",
amount: new Money("EUR", "10.00"),
metadata: ["key" => "value"] // Only arrays are accepted
);
$payment = $client->send($request);
```
### Class & Method Renames
#### Endpoint Class Changes
| Old Class | New Class | Method Changes |
|------------------------------|----------------------------------------|------------------------------------------------------------|
| `MethodEndpoint` | `MethodEndpointCollection` | `allAvailable()` → `all()`<br>`all()` → `allEnabled()` |
| `BalanceTransactionEndpoint` | `BalanceTransactionEndpointCollection` | `listFor()` → `pageFor()`<br>`listForId()` → `pageForId()` |
| `CustomerPaymentsEndpoint` | `CustomerPaymentsEndpointCollection` | `listFor()` → `pageFor()`<br>`listForId()` → `pageForId()` |
| `MandateEndpoint` | `MandateEndpointCollection` | `listFor()` → `pageFor()`<br>`listForId()` → `pageForId()` |
| `PaymentRefundEndpoint` | `PaymentRefundEndpointCollection` | `listFor()` → `pageFor()`<br>`listForId()` → `pageForId()` |
| `OnboardingEndpoint` | `OnboardingEndpointCollection` | `get()` → `status()` |
| `SubscriptionEndpoint` | `SubscriptionEndpointCollection` | `page()` → `allFor()` |
#### Signature Changes
Use named parameters to make request calls easier to read and maintain:
```php
// Before (v2)
$mandates = $client->mandates->listFor($customer, 0, 10);
// After (v3)
$mandates = $client->mandates->pageForCustomer(
$customer,
from: null,
limit: 10,
testmode: false
);
```
### Constant & Collection Changes
- **Streamlined constants** - Remove redundant prefixes and use the shorter constant names:
```php
// Before
Payment::STATUS_PAID;
// After
Payment::PAID;
```
- **Simplified SequenceType constants** - Use the shorter enum cases:
```php
// Before
SequenceType::SEQUENCETYPE_FIRST;
// After
SequenceType::FIRST;
```
- **Cleaner collection initialization** - Pass the items array directly:
```php
// Before
new PaymentCollection(10, $payments);
// After
new PaymentCollection($payments);
```
### Test Mode Handling
- **Automatic detection** with API keys
- **Explicit parameter** for organization credentials:
```php
// Get payment link in test mode
$link = $client->paymentLinks->get('pl_123', testmode: true);
```
Read the full testing documentation [here](docs/testing.md).
### Removed Collections
- `OrganizationCollection`
- `RouteCollection`
## New Features
### Modern HTTP Handling
#### PSR-18 Support
Configure any PSR-18-compatible HTTP client with the SDK:
```php
use Mollie\Api\HttpAdapter\PSR18MollieHttpAdapter;
$adapter = new PSR18MollieHttpAdapter(
new GuzzleClient(),
new Psr17Factory(),
new Psr17Factory()
);
$client = new MollieApiClient($adapter);
```
### Enhanced Request Handling
#### Typed Request Objects
Replace array-based payloads with type-safe request objects:
```php
use Mollie\Api\Http\Requests\CreatePaymentRequest;
$request = new CreatePaymentRequest(
amount: new Money('EUR', '10.00'),
description: 'Order 123',
redirectUrl: 'https://example.com/redirect'
);
$payment = $client->send($request);
```
Read the full request documentation [here](docs/requests.md).
### Collection Improvements
Use the collection methods below to write more expressive queries:
```php
// New methods
$activePayments = $payments->filter(fn($p) => $p->isActive());
$hasRefunds = $payments->contains(fn($p) => $p->hasRefunds());
```
### Method Issuer Contracts
Manage method issuers by passing optional contract IDs:
```php
$client->methodIssuers->enable(
profileId: 'pfl_123',
methodId: 'voucher',
issuerId: 'iss_456',
contractId: 'contract_789' // Optional
);
```
## Further reading
Usage guides for the PHP client can be found in the [docs](docs). For more information on the Mollie API, check out [the official Mollie docs](https://docs.mollie.com).
+285
View File
@@ -0,0 +1,285 @@
#!/bin/bash
set -u -o pipefail
TAG_PUSH_ATTEMPTED=0
die() {
echo "❌ Error: $*" >&2
if [ "$TAG_PUSH_ATTEMPTED" -eq 1 ]; then
echo " The tag may now exist remotely. Rerun this command to use the supported tag-only recovery path; no overwrite or cleanup was attempted." >&2
else
echo " No further publication was attempted." >&2
fi
exit 1
}
if [ "$#" -ne 1 ] || [ -z "$1" ]; then
echo "❌ Error: Version number is required" >&2
echo "Usage: ./bin/release <version>" >&2
echo "Example: ./bin/release 1.0.0" >&2
exit 1
fi
VERSION=$1
TAG="v$VERSION"
TAG_REF="refs/tags/$TAG"
MOLLIE_CLIENT_FILE="src/MollieApiClient.php"
command -v git >/dev/null 2>&1 || die "git is not installed or is not available on PATH."
command -v gh >/dev/null 2>&1 || die "GitHub CLI (gh) is not installed or is not available on PATH."
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || die "Run this command from the Mollie API PHP Git worktree."
[ -f "$MOLLIE_CLIENT_FILE" ] || die "MollieApiClient.php was not found at $MOLLIE_CLIENT_FILE."
git check-ref-format "$TAG_REF" >/dev/null 2>&1 || die "Version '$VERSION' does not form a valid tag ref."
repo_details=$(gh repo view --json nameWithOwner,defaultBranchRef --jq '[.nameWithOwner, .defaultBranchRef.name] | @tsv') || die "The exact GitHub repository/default-branch lookup failed. Check authentication and repository access."
case "$repo_details" in
*$'\n'*) die "The GitHub repository/default-branch lookup returned multiple rows." ;;
esac
IFS=$'\t' read -r REPOSITORY DEFAULT_BRANCH extra <<< "$repo_details"
[ -n "${REPOSITORY:-}" ] && [ -n "${DEFAULT_BRANCH:-}" ] && [ -z "${extra:-}" ] || die "The GitHub repository/default-branch lookup returned malformed data."
OWNER=${REPOSITORY%%/*}
REPOSITORY_NAME=${REPOSITORY#*/}
[ -n "$OWNER" ] && [ -n "$REPOSITORY_NAME" ] && [ "$OWNER" != "$REPOSITORY" ] && [[ "$REPOSITORY_NAME" != */* ]] || die "The GitHub repository identity '$REPOSITORY' is malformed."
git check-ref-format --branch "$DEFAULT_BRANCH" >/dev/null 2>&1 || die "The GitHub default branch '$DEFAULT_BRANCH' is not a valid branch name."
is_oid() {
[[ "$1" =~ ^[0-9a-fA-F]{40}$ || "$1" =~ ^[0-9a-fA-F]{64}$ ]]
}
read_client_version() {
local line
local pattern
local -a matches=()
pattern="^[[:space:]]+public const CLIENT_VERSION = '([^']*)';[[:space:]]*$"
while IFS= read -r line || [ -n "$line" ]; do
if [[ "$line" =~ $pattern ]]; then
matches+=("${BASH_REMATCH[1]}")
fi
done < "$MOLLIE_CLIENT_FILE" || die "CLIENT_VERSION could not be read from $MOLLIE_CLIENT_FILE."
[ "${#matches[@]}" -eq 1 ] || die "Expected exactly one syntactically exact CLIENT_VERSION declaration; found ${#matches[@]}."
CLIENT_VERSION=${matches[0]}
}
assert_base_state() {
local branch
local status_output
local current_head
local remote_head
branch=$(git symbolic-ref --quiet --short HEAD) || die "HEAD is detached; the symbolic default branch '$DEFAULT_BRANCH' must be checked out."
[ "$branch" = "$DEFAULT_BRANCH" ] || die "Checked-out branch '$branch' is not the GitHub default branch '$DEFAULT_BRANCH'."
status_output=$(git status --porcelain=v1 --untracked-files=all) || die "The complete worktree status check failed."
[ -z "$status_output" ] || die "The worktree is not completely clean, including untracked files."
git fetch --no-tags origin "refs/heads/$DEFAULT_BRANCH:refs/remotes/origin/$DEFAULT_BRANCH" || die "Fetching the exact default branch from origin failed."
current_head=$(git rev-parse --verify 'HEAD^{commit}') || die "HEAD could not be resolved to a commit."
remote_head=$(git rev-parse --verify "refs/remotes/origin/$DEFAULT_BRANCH^{commit}") || die "origin/$DEFAULT_BRANCH could not be resolved to a commit."
if ! is_oid "$current_head" || ! is_oid "$remote_head"; then
die "A local or remote commit ID was malformed."
fi
[ "$current_head" = "$remote_head" ] || die "HEAD does not equal the fetched origin/$DEFAULT_BRANCH commit."
if [ -n "${SNAPSHOT_HEAD:-}" ]; then
[ "$current_head" = "$SNAPSHOT_HEAD" ] || die "HEAD changed after release validation began."
fi
read_client_version
[ "$CLIENT_VERSION" = "$VERSION" ] || die "CLIENT_VERSION '$CLIENT_VERSION' does not exactly match requested version '$VERSION'."
ASSERTED_HEAD=$current_head
}
classify_remote_tag() {
local output
local oid
local ref
local extra
local base_count=0
local peeled_count=0
local base_oid=''
local peeled_oid=''
output=$(git ls-remote --tags origin "$TAG_REF" "$TAG_REF^{}") || die "The exact remote tag query failed."
while IFS=$'\t' read -r oid ref extra; do
[ -n "$oid" ] || continue
is_oid "$oid" && [ -n "$ref" ] && [ -z "${extra:-}" ] || die "The exact remote tag query returned malformed data."
if [ "$ref" = "$TAG_REF" ]; then
base_count=$((base_count + 1))
base_oid=$oid
elif [ "$ref" = "$TAG_REF^{}" ]; then
peeled_count=$((peeled_count + 1))
peeled_oid=$oid
else
die "The exact remote tag query returned an unexpected ref."
fi
done <<< "$output"
if [ "$base_count" -eq 0 ] && [ "$peeled_count" -eq 0 ]; then
REMOTE_TAG_STATE=absent
elif [ "$base_count" -eq 1 ] && [ "$peeled_count" -eq 0 ]; then
REMOTE_TAG_STATE=lightweight
elif [ "$base_count" -eq 1 ] && [ "$peeled_count" -eq 1 ]; then
[ -n "$base_oid" ] || die "The remote annotated tag object ID was empty."
if [ "$peeled_oid" = "$SNAPSHOT_HEAD" ]; then
REMOTE_TAG_STATE=annotated
else
REMOTE_TAG_STATE=mismatch
fi
else
die "The exact remote tag query returned a peeled-only, duplicate, or contradictory state."
fi
}
classify_release() {
local output
local graphql_query
graphql_query="query(\$owner:String!,\$name:String!,\$tag:String!){repository(owner:\$owner,name:\$name){release(tagName:\$tag){tagName}}}"
output=$(gh api graphql \
-f "query=$graphql_query" \
-f "owner=$OWNER" \
-f "name=$REPOSITORY_NAME" \
-f "tag=$TAG" \
--jq 'if (.data | type) != "object" then "invalid" elif (.data.repository | type) != "object" then "invalid" elif (.data.repository | has("release") | not) then "invalid" elif .data.repository.release == null then "absent" elif (.data.repository.release | type) != "object" then "invalid" elif (.data.repository.release.tagName | type) == "string" then "present\t" + .data.repository.release.tagName else "invalid" end') || die "The exact GitHub release query failed."
case "$output" in
absent)
RELEASE_STATE=absent
;;
$'present\t'*)
[ "${output#*$'\t'}" = "$TAG" ] || die "The GitHub release query returned a contradictory tag name."
RELEASE_STATE=present
;;
*)
die "The GitHub release query returned malformed data."
;;
esac
}
classify_remote_state() {
classify_remote_tag
classify_release
}
require_valid_or_absent_state() {
case "$REMOTE_TAG_STATE:$RELEASE_STATE" in
annotated:present|annotated:absent|absent:absent) ;;
lightweight:*) die "Remote tag '$TAG' is lightweight; annotated tags are required." ;;
mismatch:*) die "Remote tag '$TAG' does not peel to the validated HEAD." ;;
absent:present) die "GitHub release '$TAG' exists without a valid matching annotated tag." ;;
*) die "Remote tag/release state is contradictory." ;;
esac
}
classify_local_tag() {
local ref_type
local peeled
if git show-ref --verify --quiet "$TAG_REF"; then
ref_type=$(git cat-file -t "$TAG_REF") || die "Local tag '$TAG' could not be inspected."
[ "$ref_type" = tag ] || die "Local tag '$TAG' is lightweight; refusing to replace it."
peeled=$(git rev-parse --verify "$TAG_REF^{}") || die "Local tag '$TAG' could not be peeled."
is_oid "$peeled" || die "Local tag '$TAG' peeled to a malformed object ID."
[ "$peeled" = "$SNAPSHOT_HEAD" ] || die "Local tag '$TAG' does not peel to the validated HEAD; refusing to replace it."
LOCAL_TAG_STATE=annotated
else
local show_ref_status=$?
[ "$show_ref_status" -eq 1 ] || die "Local tag '$TAG' could not be queried."
LOCAL_TAG_STATE=absent
fi
}
publish_release() {
assert_base_state
classify_remote_state
require_valid_or_absent_state
if [ "$REMOTE_TAG_STATE" = annotated ] && [ "$RELEASE_STATE" = present ]; then
echo "✅ Release $TAG already exists with the valid annotated tag at $SNAPSHOT_HEAD."
return 0
fi
[ "$REMOTE_TAG_STATE" = annotated ] && [ "$RELEASE_STATE" = absent ] || die "Release publication requires the valid annotated remote tag and no existing release."
if ! gh release create "$TAG" --verify-tag --target "$SNAPSHOT_HEAD" --latest --generate-notes; then
die "GitHub release creation failed."
fi
classify_remote_state
[ "$REMOTE_TAG_STATE" = annotated ] && [ "$RELEASE_STATE" = present ] || die "Post-publication verification did not find the valid final tag/release state."
echo "✅ Release $TAG created successfully at $SNAPSHOT_HEAD."
}
SNAPSHOT_HEAD=''
ASSERTED_HEAD=''
CLIENT_VERSION=''
assert_base_state
SNAPSHOT_HEAD=$ASSERTED_HEAD
echo "📌 Repository: $REPOSITORY"
echo "📌 Default branch and HEAD: $DEFAULT_BRANCH at $SNAPSHOT_HEAD"
classify_remote_state
require_valid_or_absent_state
case "$REMOTE_TAG_STATE:$RELEASE_STATE" in
annotated:present)
echo "✅ Release $TAG already exists with the valid annotated tag at $SNAPSHOT_HEAD."
exit 0
;;
annotated:absent)
publish_release
exit 0
;;
absent:absent)
classify_local_tag
assert_base_state
classify_remote_state
require_valid_or_absent_state
if [ "$REMOTE_TAG_STATE" = annotated ]; then
publish_release
exit 0
fi
[ "$REMOTE_TAG_STATE" = absent ] && [ "$RELEASE_STATE" = absent ] || die "Remote state changed before local tag preparation."
if [ "$LOCAL_TAG_STATE" = absent ]; then
git tag --annotate "$TAG" "$SNAPSHOT_HEAD" --message "Release $VERSION" || die "Creating the local annotated tag failed."
fi
classify_local_tag
assert_base_state
classify_remote_state
require_valid_or_absent_state
if [ "$REMOTE_TAG_STATE" = absent ] && [ "$RELEASE_STATE" = absent ]; then
TAG_PUSH_ATTEMPTED=1
git push --atomic origin "$TAG_REF:$TAG_REF" || die "The explicit non-force tag-only push failed."
elif [ "$REMOTE_TAG_STATE" != annotated ] || [ "$RELEASE_STATE" != absent ]; then
die "Remote state changed before the tag push."
fi
classify_remote_state
[ "$REMOTE_TAG_STATE" = annotated ] && [ "$RELEASE_STATE" = absent ] || die "The pushed tag did not verify as an annotated tag at the validated HEAD."
publish_release
exit 0
;;
esac
die "Unhandled remote tag/release state."
+106
View File
@@ -0,0 +1,106 @@
{
"name": "mollie/mollie-api-php",
"description": "Mollie API client library for PHP. Mollie is a European Payment Service provider and offers international payment methods such as Mastercard, VISA, American Express and PayPal, and local payment methods such as iDEAL, Bancontact, SOFORT Banking, SEPA direct debit, Belfius Direct Net, KBC Payment Button and various gift cards such as Podiumcadeaukaart and fashioncheque.",
"keywords": [
"mollie",
"payment",
"service",
"ideal",
"creditcard",
"apple pay",
"mistercash",
"bancontact",
"sofort",
"sofortbanking",
"sepa",
"paypal",
"paysafecard",
"podiumcadeaukaart",
"przelewy24",
"banktransfer",
"direct debit",
"belfius",
"belfius direct net",
"refunds",
"api",
"payments",
"gateway",
"subscriptions",
"recurring",
"charges",
"kbc",
"cbc",
"gift cards",
"intersolve",
"fashioncheque",
"inghomepay",
"klarna",
"paylater",
"sliceit"
],
"homepage": "https://www.mollie.com/en/developers",
"license": "BSD-2-Clause",
"authors": [
{
"name": "Mollie B.V.",
"email": "info@mollie.com"
}
],
"require": {
"php": "^8.2",
"ext-curl": "*",
"ext-json": "*",
"ext-openssl": "*",
"composer/ca-bundle": "^1.4",
"nyholm/psr7": "^1.8",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.1",
"psr/http-message": "^1.1|^2.0",
"symfony/var-dumper": "^5.4|^6.4|^7.2|^8.0"
},
"require-dev": {
"guzzlehttp/guzzle": "^7.6",
"laravel/pint": "1.30.4",
"pestphp/pest": "^3.0",
"phpstan/phpstan": "^2.0",
"phpunit/phpunit": "^11.5"
},
"suggest": {
"mollie/oauth2-mollie-php": "Use OAuth to authenticate with the Mollie API. This is needed for some endpoints. Visit https://docs.mollie.com/ for more information."
},
"config": {
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true
}
},
"autoload": {
"psr-4": {
"Mollie\\Api\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/",
"Tests\\Mollie\\Api\\": "tests/Mollie/API/"
}
},
"scripts": {
"test": "./vendor/bin/pest --parallel",
"format": "pint",
"check:format": "pint --test",
"generate:currency-trait": "@php tools/generate-currency-trait.php",
"check:currency-trait": [
"@php tools/generate-currency-trait.php",
"git diff --exit-code src/Traits/HasCurrencyConvenienceMethods.php"
]
},
"repositories": [{
"name": "mollie-local",
"type": "path",
"url": "../mollie-api-php",
"options": {
"symlink": true
}
}]
}
+102
View File
@@ -0,0 +1,102 @@
# Debugging with Mollie API Client
## Overview
The Mollie API client provides debugging callbacks to help you inspect and troubleshoot API requests and responses. The built-in Symfony VarDumper debugger prints request and response details for local development. Exception handling sanitizes sensitive request data before it is attached to thrown exceptions, but default debug output itself is not a production-safe logging surface.
## Basic Usage
### Enable All Debugging
To enable both request and response debugging:
```php
$mollie = new \Mollie\Api\MollieApiClient();
$mollie->debug(); // Enables both request and response debugging
```
The default debugger requires `symfony/var-dumper`. If that package is not installed, calling the default debugger throws an actionable runtime exception. Pass custom callbacks to `debugRequest()` or `debugResponse()` if you want to avoid that optional dependency.
### Enable on Request
To enable debugging for a specific request:
```php
$request = new CreatePaymentRequest(...);
// enable output for request and response
$mollie->send($request->debug());
// only debug request
$mollie->send($request->debugRequest(die: true));
// only debug response
$mollie->send($request->debugResponse(die: true));
```
### Debug Specific Parts
You can choose to debug only requests or only responses:
```php
// Debug only requests
$mollie->debugRequest();
// Debug only responses
$mollie->debugResponse();
```
## Custom Debuggers
You can provide your own debugging functions to customize how debugging information is displayed:
```php
// Custom request debugger
$mollie->debugRequest(function($pendingRequest, $psrRequest) {
// Your custom debugging logic here
});
// Custom response debugger
$mollie->debugResponse(function($response, $psrResponse) {
// Your custom debugging logic here
});
```
## Security Features
### Automatic Sanitization
When an exception is thrown while debugging is enabled, the client sanitizes the request data attached to the exception. The default request/response debug callbacks are for local inspection and may print headers and request bodies. Treat their output as sensitive.
### Die After Debug
For development purposes, you can halt execution after debugging output:
```php
$mollie->debug(die: true); // Will stop execution after debugging output
```
## Best Practices
1. **Development Only**: Never enable debugging in production environments
2. **Custom Debuggers**: When implementing custom debuggers, redact credentials and personal data before writing to logs
3. **Exception Handling**: Debug mode works with exceptions, and exception request data is sanitized before being exposed
## Example Usage
```php
try {
$mollie = new \Mollie\Api\MollieApiClient();
$mollie->setApiKey("test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM");
// Enable debugging for development
$mollie->debug();
// Your API calls here
$payment = $mollie->payments->create([...]);
} catch (\Mollie\Api\Exceptions\ApiException $e) {
// Exception will include sanitized debug information
echo "API call failed: " . htmlspecialchars($e->getMessage());
}
```
@@ -0,0 +1,765 @@
# Introduction
Endpoint collections provide a fluent interface for interacting with Mollie's API. Each collection manages specific resource types like payments, customers, and subscriptions, offering methods to create, retrieve, update, and delete these resources.
## Setup
1. **Initialize the Mollie Client:**
```php
$mollie = new \Mollie\Api\MollieApiClient();
$mollie->setApiKey("test_*************************");
```
2. **Access Endpoints via the Client:**
```php
// Payments endpoint
$mollie->payments->...
// Customers endpoint
$mollie->customers->...
// Other endpoints
$mollie->balances->...
$mollie->orders->...
```
3. **Call methods**
**Simple: Using arrays**
This approach is direct but provides less type safety:
```php
$payment = $mollie->payments->create([
'amount' => [
'currency' => 'EUR',
'value' => '10.00'
],
'description' => 'My first API payment'
]);
```
**Advanced: Using typed array params**
You can use dedicated `Data` objects to add partial type safety to your parameters.
```php
use Mollie\Api\Http\Data\Money;
use Mollie\Api\Http\Data\CreatePaymentPayload;
$payment = $mollie->payments->create([
'description' => 'My first API payment',
'amount' => new Money(currency: 'EUR', value: '10.00')
]);
```
If you're starting with an array and need to convert it into a structured request, you can use a specific factory designed for this purpose.
```php
use Mollie\Api\Http\Data\Money;
use Mollie\Api\Factories\CreatePaymentRequestFactory;
// Fully untyped data
$createPaymentRequest = CreatePaymentRequestFactory::new([
'amount' => [
'currency' => 'EUR',
'value' => '10.00'
],
'description' => 'My first API payment'
]);
// Partially untyped
$createPaymentRequest = CreatePaymentRequestFactory::new([
'amount' => new Money(currency: 'EUR', value: '10.00'),
'description' => 'My first API payment'
]);
```
This method lets you effortlessly transform arrays into typed objects, thereby enhancing IDE support and increasing type safety while handling your data.
# Available Endpoints
## Balances
[Official Documentation](https://docs.mollie.com/reference/v2/balances-api/get-balance)
### Balance Information
```php
// Get primary balance
$balance = $mollie->balances->primary();
// Get specific balance
$balance = $mollie->balances->get('bal_12345');
// List balances
$balances = $mollie->balances->page();
```
## Balance Reports
[Official Documentation](https://docs.mollie.com/reference/v2/balance-reports-api/get-balance-report)
### Balance Report Details
```php
// Get report for specific balance
$report = $mollie->balanceReports->getForId('bal_12345', [
'from' => '2024-01-01',
'until' => '2024-01-31',
'grouping' => 'transaction-categories'
]);
```
## Balance Transactions
[Official Documentation](https://docs.mollie.com/reference/v2/balance-transactions-api/list-balance-transactions)
### Balance Transaction Management
```php
// Get transactions for a balance
$transactions = $mollie->balanceTransactions->pageFor($balance);
// Use iterator for all transactions
foreach ($mollie->balanceTransactions->iteratorFor($balance) as $transaction) {
echo $transaction->id;
}
```
## Chargebacks
[Official Documentation](https://docs.mollie.com/reference/v2/chargebacks-api/get-chargeback)
### Chargeback Management
```php
// Get all chargebacks
$chargebacks = $mollie->chargebacks->page();
// Use iterator for all chargebacks
foreach ($mollie->chargebacks->iterator() as $chargeback) {
echo $chargeback->id;
}
```
## Clients
[Official Documentation](https://docs.mollie.com/reference/v2/clients-api/get-client)
### Client Management
```php
// Get a specific client
$client = $mollie->clients->get('org_12345678', [
'testmode' => true
]);
// List all clients
$clients = $mollie->clients->page(
from: 'org_12345678',
limit: 50
);
```
## Customers
[Official Documentation](https://docs.mollie.com/reference/v2/customers-api/create-customer)
### Customer Management
```php
// Create a customer
$customer = $mollie->customers->create([
'name' => 'John Doe',
'email' => 'john@example.org',
]);
// Get a customer
$customer = $mollie->customers->get('cst_8wmqcHMN4U');
// Update a customer
$customer = $mollie->customers->update('cst_8wmqcHMN4U', [
'name' => 'Updated Name'
]);
// Delete a customer
$mollie->customers->delete('cst_8wmqcHMN4U');
// List customers
$customers = $mollie->customers->page();
```
## Invoices
[Official Documentation](https://docs.mollie.com/reference/v2/invoices-api/get-invoice)
### Invoice Management
```php
// Get a specific invoice
$invoice = $mollie->invoices->get('inv_xBEbP9rvAq');
// List all invoices
$invoices = $mollie->invoices->page(
from: 'inv_xBEbP9rvAq',
limit: 50
);
```
## Mandates
[Official Documentation](https://docs.mollie.com/reference/v2/mandates-api/create-mandate)
### Mandate Management
```php
// Create a mandate for a customer
$mandate = $mollie->mandates->createFor($customer, [
'method' => \Mollie\Api\Types\PaymentMethod::Directdebit,
'consumerName' => 'John Doe',
'consumerAccount' => 'NL55INGB0000000000',
'consumerBic' => 'INGBNL2A',
'signatureDate' => '2024-01-01',
'mandateReference' => 'YOUR-COMPANY-MD13804'
]);
// Get a mandate
$mandate = $mollie->mandates->getFor($customer, 'mdt_h3gAaD5zP');
// Revoke a mandate
$mollie->mandates->revokeFor($customer, 'mdt_h3gAaD5zP');
// List mandates
$mandates = $mollie->mandates->pageFor($customer);
```
## Methods
[Official Documentation](https://docs.mollie.com/reference/v2/methods-api/get-method)
### Payment Methods
```php
// Get a method
$method = $mollie->methods->get(\Mollie\Api\Types\PaymentMethod::Ideal);
// List all methods
$methods = $mollie->methods->all();
// List enabled methods
$methods = $mollie->methods->allEnabled([
'amount' => [
'currency' => 'EUR',
'value' => '100.00'
]
]);
```
### Method Issuers
```php
// Enable an issuer
$issuer = $mollie->methodIssuers->enable(
'pfl_v9hTwCvYqw',
\Mollie\Api\Types\PaymentMethod::Ideal,
'ideal_INGBNL2A'
);
// Disable an issuer
$mollie->methodIssuers->disable(
'pfl_v9hTwCvYqw',
\Mollie\Api\Types\PaymentMethod::Ideal,
'ideal_INGBNL2A'
);
```
## Onboarding
[Official Documentation](https://docs.mollie.com/reference/v2/onboarding-api/get-onboarding-status)
### Onboarding Management
```php
// Get onboarding status
$onboarding = $mollie->onboarding->status();
```
## Organizations
[Official Documentation](https://docs.mollie.com/reference/v2/organizations-api/get-organization)
### Organization Management
```php
// Get an organization
$organization = $mollie->organizations->get('org_12345678');
// Get current organization
$organization = $mollie->organizations->current();
// Get partner status
$partner = $mollie->organizations->partnerStatus();
```
## Permissions
[API Reference](https://docs.mollie.com/reference/v2/permissions-api/get-permission) · [Full list of permission scopes](https://docs.mollie.com/docs/permissions)
### Permission Management
```php
// Get a permission
$permission = $mollie->permissions->get('payments.read');
// List all permissions
$permissions = $mollie->permissions->list();
```
## Payments
[Official Documentation](https://docs.mollie.com/reference/v2/payments-api/create-payment)
### Payment Management
```php
// Create a payment
$payment = $mollie->payments->create([
'description' => 'Order #12345',
'amount' => [
'currency' => 'EUR',
'value' => '10.00'
],
'redirectUrl' => 'https://webshop.example.org/order/12345/',
'webhookUrl' => 'https://webshop.example.org/mollie-webhook/'
]);
// Get a payment
$payment = $mollie->payments->get('tr_7UhSN1zuXS');
// Update a payment
$payment = $mollie->payments->update('tr_7UhSN1zuXS', [
'description' => 'Updated description'
]);
// Cancel a payment
$mollie->payments->cancel('tr_7UhSN1zuXS');
// List payments
$payments = $mollie->payments->page();
```
### Payment Links
[Official Documentation](https://docs.mollie.com/reference/v2/payment-links-api/create-payment-link)
### Payment Captures
[Official Documentation](https://docs.mollie.com/reference/v2/captures-api/get-capture)
### Payment Chargebacks
```php
// Get a chargeback
$chargeback = $mollie->paymentChargebacks->getFor($payment, 'chb_n9z0tp');
// List chargebacks for payment
$chargebacks = $mollie->paymentChargebacks->pageFor($payment);
```
### Payment Routes
```php
// Create a delayed route
$route = $mollie->paymentRoutes->createFor(
$payment,
['value' => '10.00', 'currency' => 'EUR'],
['type' => 'organization', 'organizationId' => 'org_12345'],
'2025-01-01' // optional release date
);
// List payment routes
$routes = $mollie->paymentRoutes->listFor($payment);
// Update release date for a route
$route = $mollie->paymentRoutes->updateReleaseDateFor(
$payment,
'rt_abc123',
'2024-01-01'
);
```
## Profiles
[Official Documentation](https://docs.mollie.com/reference/v2/profiles-api/create-profile)
### Profile Management
```php
// Create a profile
$profile = $mollie->profiles->create([
'name' => 'My Test Profile',
'website' => 'https://example.org',
'email' => 'info@example.org',
'phone' => '+31612345678',
'mode' => 'test'
]);
// Get a profile
$profile = $mollie->profiles->get('pfl_v9hTwCvYqw');
// Get current profile
$profile = $mollie->profiles->getCurrent();
// Update a profile
$profile = $mollie->profiles->update('pfl_v9hTwCvYqw', [
'name' => 'Updated Profile Name'
]);
// Delete a profile
$mollie->profiles->delete('pfl_v9hTwCvYqw');
// List profiles
$profiles = $mollie->profiles->page();
```
### Profile Methods
```php
// Enable a method
$method = $mollie->profileMethods->enable(
'pfl_v9hTwCvYqw',
\Mollie\Api\Types\PaymentMethod::Ideal
);
// Disable a method
$mollie->profileMethods->disable(
'pfl_v9hTwCvYqw',
\Mollie\Api\Types\PaymentMethod::Ideal
);
```
## Refunds
[Official Documentation](https://docs.mollie.com/reference/v2/refunds-api/create-refund)
### Refund Management
```php
// Create a refund for a payment
$refund = $mollie->refunds->createForPayment($paymentId, [
'amount' => [
'currency' => 'EUR',
'value' => '15.00'
],
'description' => 'Refund for returned item'
]);
// List refunds
$refunds = $mollie->refunds->page();
```
## Sales Invoices
[Official Documentation TBA]
### Sales Invoice Management
```php
use Mollie\Api\Types\VatMode;
use Mollie\Api\Types\VatScheme;
use Mollie\Api\Types\PaymentTerm;
use Mollie\Api\Types\RecipientType;
use Mollie\Api\Types\SalesInvoiceStatus;
// Create a sales invoice
$salesInvoice = $mollie->salesInvoices->create([
'currency' => 'EUR',
'status' => SalesInvoiceStatus::Draft,
'vatScheme' => VatScheme::Standard,
'vatMode' => VatMode::Inclusive,
'paymentTerm' => PaymentTerm::Days30,
'recipientIdentifier' => 'XXXXX',
'recipient' => [
'type' => RecipientType::Consumer,
'email' => 'darth@vader.deathstar',
'streetAndNumber' => 'Sample Street 12b',
'postalCode' => '2000 AA',
'city' => 'Amsterdam',
'country' => 'NL',
'locale' => 'nl_NL'
],
'lines' => [
[
'description' => 'Monthly subscription fee',
'quantity' => 1,
'vatRate' => '21',
'unitPrice' => [
'currency' => 'EUR',
'value' => '10,00'
]
]
]
]);
// Get a sales invoice
$salesInvoice = $mollie->salesInvoices->get('invoice_12345');
// Update a sales invoice
$salesInvoice = $mollie->salesInvoices->update('invoice_12345', [
'description' => 'Updated description'
]);
// Delete a sales invoice
$mollie->salesInvoices->delete('invoice_12345');
// List sales invoices
$salesInvoices = $mollie->salesInvoices->page();
```
## Sessions
[Official Documentation](https://docs.mollie.com/reference/v2/sessions-api/create-session)
### Session Management
```php
// Create a session
$session = $mollie->sessions->create([
'amount' => [
'currency' => 'EUR',
'value' => '100.00'
],
'description' => 'Session for service'
]);
// Get a session
$session = $mollie->sessions->get('sessionId');
```
## Settlements
[Official Documentation](https://docs.mollie.com/reference/v2/settlements-api/get-settlement)
### Settlement Management
```php
// Get a settlement
$settlement = $mollie->settlements->get('settlementId');
// List settlements
$settlements = $mollie->settlements->page();
```
### Settlement Captures
```php
// Get captures for a settlement
$captures = $mollie->settlementCaptures->pageFor($settlement);
// Use iterator
foreach ($mollie->settlementCaptures->iteratorFor($settlement) as $capture) {
echo $capture->id;
}
```
### Settlement Chargebacks
```php
// List chargebacks for a settlement
$chargebacks = $mollie->settlementChargebacks->pageFor($settlement);
// Use iterator
foreach ($mollie->settlementChargebacks->iteratorFor($settlement) as $chargeback) {
echo $chargeback->id;
}
```
### Settlement Payments
```php
// List payments in a settlement
$payments = $mollie->settlementPayments->pageFor($settlement);
// Use iterator
foreach ($mollie->settlementPayments->iteratorFor($settlement) as $payment) {
echo $payment->id;
}
```
## Subscriptions
[Official Documentation](https://docs.mollie.com/reference/v2/subscriptions-api/create-subscription)
### Subscription Management
```php
// Create a subscription
$subscription = $mollie->subscriptions->createForCustomer('customerId', [
'amount' => [
'currency' => 'EUR',
'value' => '25.00'
],
'interval' => '1 month',
'description' => 'Monthly subscription'
]);
// List subscriptions
$subscriptions = $mollie->subscriptions->pageForCustomer('customerId');
```
## Terminals
[Official Documentation](https://docs.mollie.com/reference/v2/terminals-api/get-terminal)
### Terminal Management
```php
// Get a terminal
$terminal = $mollie->terminals->get('terminalId');
// List terminals
$terminals = $mollie->terminals->page();
```
## Terminal Pairing Codes
Official Documentation:
[Request pairing code](https://docs.mollie.com/reference/terminals-request-pairing-code),
[Get pairing code](https://docs.mollie.com/reference/terminals-get-pairing-code),
[List pairing codes](https://docs.mollie.com/reference/terminals-list-pairing-codes),
[Revoke pairing code](https://docs.mollie.com/reference/terminals-revoke-pairing-code)
### Terminal Pairing Code Management
```php
// Request a pairing code, including QR code details
$pairingCode = $mollie->terminalPairingCodes->request('profileId', includeQrCode: true);
// Get a pairing code, including QR code details
$pairingCode = $mollie->terminalPairingCodes->get('pairingCodeId', includeQrCode: true);
// List pairing codes
$pairingCodes = $mollie->terminalPairingCodes->page(limit: 50, profileId: 'profileId');
// Use iterator
foreach ($mollie->terminalPairingCodes->iterator(profileId: 'profileId') as $pairingCode) {
echo $pairingCode->id;
}
// Revoke a pairing code
$pairingCode = $mollie->terminalPairingCodes->revoke('pairingCodeId');
// Check pairing code status using helper methods
if ($pairingCode->isActive()) {
echo "Pairing code is active\n";
} elseif ($pairingCode->isRevoked()) {
echo "Pairing code was revoked at: {$pairingCode->revokedAt}\n";
}
```
## Wallets
[Official Documentation](https://docs.mollie.com/reference/v2/wallets-api/request-apple-pay-payment-session)
### Wallet Management
```php
// Request an Apple Pay payment session
$session = $mollie->wallets->requestApplePayPaymentSession([
'domainName' => 'example.com',
'validationUrl' => 'https://apple-pay-gateway.apple.com/paymentservices/startSession'
]);
```
## Webhooks
[Official Documentation](https://docs.mollie.com/reference/v2/webhooks-api/create-webhook)
### Webhook Management
```php
use Mollie\Api\Types\WebhookEventType;
// Create a webhook
$webhook = $mollie->webhooks->create([
'url' => 'https://example.com/webhook',
'description' => 'Payment notifications',
'events' => [
WebhookEventType::PAYMENT_LINK_PAID,
WebhookEventType::PROFILE_VERIFIED
],
'secret' => 'my-secret-key-123'
]);
// Get a webhook
$webhook = $mollie->webhooks->get('wh_4KgGJJSZpH');
// Update a webhook
$webhook = $mollie->webhooks->update('wh_4KgGJJSZpH', [
'url' => 'https://updated-example.com/webhook',
'description' => 'Updated description'
]);
// Delete a webhook
$mollie->webhooks->delete('wh_4KgGJJSZpH');
// Test a webhook
$mollie->webhooks->test('wh_4KgGJJSZpH');
// List webhooks
$webhooks = $mollie->webhooks->page();
// Using convenience methods on webhook resource
$webhook = $mollie->webhooks->get('wh_4KgGJJSZpH');
$webhook->update(['description' => 'New description']);
$webhook->delete();
$webhook->test();
```
### Webhook Events
```php
// Get a webhook event
$webhookEvent = $mollie->webhookEvents->get('whev_abc123');
// Check event status using helper methods
if ($webhookEvent->wasDelivered()) {
echo "Webhook was successfully delivered\n";
} elseif ($webhookEvent->failed()) {
echo "Webhook delivery failed: {$webhookEvent->error}\n";
} elseif ($webhookEvent->hasRetryPending()) {
echo "Retry pending at: {$webhookEvent->nextRetryAt}\n";
}
```
## Common Patterns
### Pagination
Most list methods support pagination:
```php
// Get first page
$payments = $mollie->payments->page();
// Get specific page
$payments = $mollie->payments->page(
from: 'tr_7UhSN1zuXS', // Start from this ID
limit: 50 // Items per page
);
// Get all items using iterator
foreach ($mollie->payments->iterator() as $payment) {
echo $payment->id;
}
```
### Error Handling
Handle errors using `ApiException`:
```php
try {
$payment = $mollie->payments->get('tr_xxx');
} catch (\Mollie\Api\Exceptions\ApiException $e) {
echo "API call failed: {$e->getMessage()}";
}
```
+137
View File
@@ -0,0 +1,137 @@
# Exceptions
This document describes the exceptions that can be thrown by the Mollie API PHP client.
## Exception Hierarchy
### `MollieException`
The abstract base class for **all** exceptions in the Mollie API PHP client.
### `RequestException`
The `RequestException` serves as the base for all request-related exceptions.
### `ApiException`
Extends `RequestException` and serves as the base for all API-related exceptions. This is the parent class for all specific HTTP status code exceptions. This exception is also thrown when the Mollie API returns an error response that doesn't match any of the more specific exceptions below.
Properties and methods:
- `getDocumentationUrl()`: Returns the URL to the documentation for this error, if available
- `getDashboardUrl()`: Returns the URL to the dashboard for this error, if available
- `getRaisedAt()`: Returns the timestamp when the exception was raised
- `getPlainMessage()`: Returns the plain exception message without timestamp and metadata
## HTTP Status Code Exceptions
The following exceptions all extend `ApiException` and are thrown based on specific HTTP status codes returned by the API:
### `UnauthorizedException` (401)
Thrown when authentication fails. This typically happens when using an invalid API key.
### `ForbiddenException` (403)
Thrown when the request is understood but refused due to permission issues.
### `NotFoundException` (404)
Thrown when the requested resource does not exist.
### `MethodNotAllowedException` (405)
Thrown when the HTTP method used is not allowed for the requested endpoint.
### `RequestTimeoutException` (408)
Thrown when the request times out.
### `ValidationException` (422)
Thrown when the request data fails validation. This typically happens when required fields are missing or have invalid values.
### `TooManyRequestsException` (429)
Thrown when rate limiting is applied because too many requests were made in a short period.
### `ServiceUnavailableException` (503)
Thrown when the Mollie API service is temporarily unavailable.
## Network Exceptions
### `NetworkRequestException`
Thrown when a network error occurs during the request.
### `RetryableNetworkRequestException`
Thrown when a network error occurs that might be resolved by retrying the request.
## Other Exceptions
### `ClientException`
Base exception for client-related errors.
### `EmbeddedResourcesNotParseableException`
Thrown when embedded resources cannot be parsed.
### `IncompatiblePlatformException`
Thrown when the platform is incompatible with the Mollie API client.
### `InvalidAuthenticationException`
Thrown when the authentication method is invalid.
### `JsonParseException`
Thrown when JSON parsing fails.
### `LogicException`
Thrown when there is a logical error in the client code.
### `MissingAuthenticationException`
Thrown when no authentication method is provided.
### `ServerException`
Thrown when a server error occurs.
### `UnrecognizedClientException`
Thrown when the client is not recognized by the Mollie API.
## Handling Exceptions
Here's an example of how to handle exceptions:
```php
try {
$payment = $mollie->payments->get("tr_xxx");
} catch (Mollie\Api\Exceptions\UnauthorizedException $e) {
// Invalid API key
echo "Invalid API key: " . $e->getMessage();
} catch (Mollie\Api\Exceptions\NotFoundException $e) {
// Payment not found
echo "Payment not found: " . $e->getMessage();
} catch (Mollie\Api\Exceptions\MollieException $e) {
// Other Mollie error
echo "Mollie error: " . $e->getMessage();
}
```
You can also catch all Mollie exceptions at once:
```php
try {
$payment = $mollie->payments->get("tr_xxx");
} catch (Mollie\Api\Exceptions\MollieException $e) {
// Any Mollie error
echo "Mollie error: " . $e->getMessage();
}
```
+46
View File
@@ -0,0 +1,46 @@
# HTTP Adapters
## Overview
An HTTP adapter is a component that manages the communication between your application and an API. It abstracts the details of making HTTP requests and handling responses, allowing you to use different HTTP clients (like Guzzle, cURL, or custom clients) interchangeably without changing the way you interact with the API.
## MollieHttpAdapterPicker
The `MollieHttpAdapterPicker` is responsible for selecting the appropriate HTTP adapter based on the environment or the provided HTTP client. If no client is specified in the `MollieApiClient` constructor, it picks a default adapter.
### How It Works
1. **No Client Specified**: If no client is provided, it checks if Guzzle is available and picks the appropriate version of the Guzzle adapter.
2. **Custom Client Provided**: If a custom client is provided and it implements the `HttpAdapterContract`, it is used directly. If it's a Guzzle client, it is wrapped in a `GuzzleMollieHttpAdapter`.
3. **Unrecognized Client**: Throws an `UnrecognizedClientException` if the client is not recognized.
## Creating a Custom Adapter
To create a custom HTTP adapter:
1. Implement HttpAdapterContract.
2. Use HasDefaultFactories Trait to simplify adapter implementation.
```php
use Mollie\Api\Contracts\HttpAdapterContract;
use Mollie\Api\Traits\HasDefaultFactories;
class MyCustomHttpAdapter implements HttpAdapterContract {
use HasDefaultFactories;
public function sendRequest(PendingRequest $pendingRequest): Response {
// Implementation for sending HTTP request
}
public function version(): ?string {
return 'my-custom-adapter/1.0';
}
}
```
## Available Adapters
Out of the box, the Mollie API client provides several adapters:
- **GuzzleMollieHttpAdapter**: Wraps a Guzzle HTTP client for sending requests.
- **CurlMollieHttpAdapter**: Uses cURL for sending HTTP requests. This is the default if Guzzle is not available.
- **PSR18MollieHttpAdapter**: [PSR-18](https://www.php-fig.org/psr/psr-18/) compatible HTTP adapter
+60
View File
@@ -0,0 +1,60 @@
# Idempotency
## Overview
Idempotency ensures that multiple identical requests to an API result in the same outcome without creating duplicate resources or effects. This is crucial for operations that involve financial transactions to prevent unintended charges or state changes.
Mollie API supports idempotent requests for critical operations such as creating payments or refunds. This is automatically managed by the API client using the `ApplyIdempotencyKey` middleware.
For more detailed information, refer to the [Mollie API Idempotency Documentation](https://docs.mollie.com/reference/api-idempotency).
> [!Note]
> This package automatically handles idempotency for you. The information below allows you to override the default idempotency behavior.
## Automatic Idempotency Key Handling
The Mollie API client automatically handles idempotency for mutating requests (POST, PATCH, DELETE) through the `ApplyIdempotencyKey` middleware. This middleware checks if the request is a mutating type and applies an idempotency key if one is not already provided.
### How It Works
1. **Check Request Type**: The middleware checks if the request method is POST, PATCH, or DELETE.
2. **Apply Idempotency Key**: If the request is mutating, the middleware will:
- Use a custom idempotency key if provided.
- Otherwise, generate a key using the configured `IdempotencyKeyGenerator` if available.
- If no generator is set and no key is provided, no idempotency key is applied.
### Customizing Idempotency Key
You can customize how idempotency keys are generated or applied in several ways:
- **Provide a Custom Key**: Manually set an idempotency key for a specific request.
- **Use a Custom Generator**: Implement the `IdempotencyKeyGeneratorContract` to provide a custom method of generating idempotency keys.
#### Example: Setting a Custom Key
```php
$mollie->setIdempotencyKey('your_custom_key_here');
```
#### Example: Using a Custom Key Generator
Implement your key generator:
```php
class MyCustomKeyGenerator implements IdempotencyKeyGeneratorContract {
public function generate(): string {
return 'custom_' . bin2hex(random_bytes(10));
}
}
$mollie->setIdempotencyKeyGenerator(new MyCustomKeyGenerator());
```
## Best Practices
- **Unique Keys**: Ensure that each idempotency key is unique to each operation. Typically, UUIDs are used for this purpose.
- **Handling Errors**: Handle errors gracefully, especially when an API call with an idempotency key fails. Check the error message to understand whether you should retry the request with the same key or a new key.
## Conclusionz
Using idempotency keys in your API requests to Mollie can significantly enhance the reliability of your payment processing system, ensuring that payments are not unintentionally duplicated and that your application behaves predictably even in the face of network and service interruptions.
+94
View File
@@ -0,0 +1,94 @@
##### Multicurrency #####
Since API v2.0 it is now possible to create non-EUR payments for your customers.
A full list of available currencies can be found [in our documentation](https://docs.mollie.com/docs/multicurrency).
```php
$payment = $mollie->payments->create([
"amount" => [
"currency" => "USD",
"value" => "10.00"
],
//...
]);
```
_After creation, the `settlementAmount` will contain the EUR amount that will be settled on your account._
##### Create fully integrated iDEAL payments #####
To fully integrate iDEAL payments on your website, follow these additional steps:
1. Retrieve the list of issuers (banks) that support iDEAL.
```php
$method = $mollie->methods->get(\Mollie\Api\Types\PaymentMethod::Ideal, ["include" => "issuers"]);
```
Use the `$method->issuers` list to let the customer pick their preferred issuer.
_`$method->issuers` will be a list of objects. Use the property `$id` of this object in the
API call, and the property `$name` for displaying the issuer to your customer._
2. Create a payment with the selected issuer:
```php
$payment = $mollie->payments->create([
"amount" => [
"currency" => "EUR",
"value" => "10.00"
],
"description" => "My first API payment",
"redirectUrl" => "https://webshop.example.org/order/12345/",
"webhookUrl" => "https://webshop.example.org/mollie-webhook/",
"method" => \Mollie\Api\Types\PaymentMethod::Ideal,
"issuer" => $selectedIssuerId, // e.g. "ideal_INGBNL2A"
]);
```
_The `_links` property of the `$payment` object will contain an object `checkout` with a `href` property, which is a URL that points directly to the online banking environment of the selected issuer.
A short way of retrieving this URL can be achieved by using the `$payment->getCheckoutUrl()`._
For a more in-depth example, see [Example - iDEAL payment](./recipes/payments/create-ideal-payment.md).
#### Retrieving Payments ####
**[Retrieve Payment Documentation](https://docs.mollie.com/reference/v2/payments-api/get-payment)**
We can use the `$payment->id` to retrieve a payment and check if the payment `isPaid`.
```php
$payment = $mollie->payments->get($payment->id);
if ($payment->isPaid())
{
echo "Payment received.";
}
```
Or retrieve a collection of payments.
```php
$payments = $mollie->payments->page();
```
For an extensive example of listing payments with the details and status, see [Example - List Payments](./recipes/payments/list-payments.md).
#### Refunding payments ####
**[Refund Payment Documentation](https://docs.mollie.com/reference/v2/refunds-api/create-payment-refund)**
Our API provides support for refunding payments. It's important to note that there is no confirmation step, and all refunds are immediate and final. Refunds are available for all payment methods except for paysafecard and gift cards.
```php
$payment = $mollie->payments->get($payment->id);
// Refund € 2 of this payment
$refund = $payment->refund([
"amount" => [
"currency" => "EUR",
"value" => "2.00"
]
]);
```
#### Payment webhook ####
When the payment status changes, the `webhookUrl` you specified during payment creation will be called. You can use the `id` from the POST parameters to check the status and take appropriate actions.
For more details, refer to [Example - Webhook](./recipes/payments/handle-webhook.md).
For a working example, see [Example - Refund payment](./recipes/payments/refund-payment.md).
+33
View File
@@ -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
@@ -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)
@@ -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)
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
+185
View File
@@ -0,0 +1,185 @@
# Request Reference
This document provides a quick reference index of all available request classes in the Mollie PHP SDK. For detailed parameter information, see the PHPDoc comments in each request class. Request classes provide a type-safe way to interact with the Mollie API directly, offering better IDE support and type checking compared to using endpoint collections with arrays.
## Payments
- **CreatePaymentRequest** - Create a new payment
- **GetPaymentRequest** - Retrieve a payment by ID
- **UpdatePaymentRequest** - Update an existing payment
- **CancelPaymentRequest** - Cancel a payment
- **CreatePaymentRefundRequest** - Create a refund for a payment
- **GetPaymentRefundRequest** - Retrieve a payment refund
- **CancelPaymentRefundRequest** - Cancel a payment refund
- **GetPaginatedPaymentsRequest** - List payments with pagination
- **ReleasePaymentAuthorizationRequest** - Release payment authorization
## Customers
- **CreateCustomerRequest** - Create a new customer
- **GetCustomerRequest** - Retrieve a customer by ID
- **UpdateCustomerRequest** - Update an existing customer
- **DeleteCustomerRequest** - Delete a customer
- **GetPaginatedCustomerRequest** - List customers with pagination
- **CreateCustomerPaymentRequest** - Create a payment for a customer
- **GetPaginatedCustomerPaymentsRequest** - List customer payments with pagination
## Subscriptions
- **CreateSubscriptionRequest** - Create a subscription for a customer
- **GetSubscriptionRequest** - Retrieve a subscription
- **UpdateSubscriptionRequest** - Update a subscription
- **CancelSubscriptionRequest** - Cancel a subscription
- **GetPaginatedSubscriptionsRequest** - List subscriptions with pagination
- **GetAllPaginatedSubscriptionsRequest** - List all subscriptions (across all customers)
- **GetPaginatedSubscriptionPaymentsRequest** - List subscription payments with pagination
## Mandates
- **CreateMandateRequest** - Create a mandate for a customer
- **GetMandateRequest** - Retrieve a mandate
- **RevokeMandateRequest** - Revoke a mandate
- **GetPaginatedMandateRequest** - List mandates with pagination
## Refunds
- **GetPaginatedRefundsRequest** - List refunds with pagination
## Webhooks
- **CreateWebhookRequest** - Create a webhook
- **GetWebhookRequest** - Retrieve a webhook
- **UpdateWebhookRequest** - Update a webhook
- **DeleteWebhookRequest** - Delete a webhook
- **TestWebhookRequest** - Test a webhook
- **GetPaginatedWebhooksRequest** - List webhooks with pagination
- **GetWebhookEventRequest** - Retrieve a webhook event
## Profiles
- **CreateProfileRequest** - Create a profile
- **GetProfileRequest** - Retrieve a profile
- **GetCurrentProfileRequest** - Retrieve the current profile
- **UpdateProfileRequest** - Update a profile
- **DeleteProfileRequest** - Delete a profile
- **GetPaginatedProfilesRequest** - List profiles with pagination
## Methods
- **GetMethodRequest** - Retrieve a payment method
- **GetAllMethodsRequest** - Retrieve all payment methods
- **GetEnabledMethodsRequest** - Retrieve all enabled payment methods
- **EnableMethodRequest** - Enable a payment method
- **DisableMethodRequest** - Disable a payment method
- **EnableMethodIssuerRequest** - Enable a method issuer
- **DisableMethodIssuerRequest** - Disable a method issuer
## Balances
- **GetBalanceRequest** - Retrieve a balance
- **GetPaginatedBalanceRequest** - List balances with pagination
- **GetBalanceReportRequest** - Retrieve a balance report
- **GetPaginatedBalanceTransactionRequest** - List balance transactions with pagination
## Settlements
- **GetSettlementRequest** - Retrieve a settlement
- **GetPaginatedSettlementsRequest** - List settlements with pagination
- **GetPaginatedSettlementPaymentsRequest** - List settlement payments with pagination
- **GetPaginatedSettlementRefundsRequest** - List settlement refunds with pagination
- **GetPaginatedSettlementCapturesRequest** - List settlement captures with pagination
- **GetPaginatedSettlementChargebacksRequest** - List settlement chargebacks with pagination
## Payment Links
- **CreatePaymentLinkRequest** - Create a payment link
- **GetPaymentLinkRequest** - Retrieve a payment link
- **UpdatePaymentLinkRequest** - Update a payment link
- **DeletePaymentLinkRequest** - Delete a payment link
- **GetPaginatedPaymentLinksRequest** - List payment links with pagination
- **GetPaginatedPaymentLinkPaymentsRequest** - List payment link payments with pagination
## Sessions
- **CreateSessionRequest** - Create a checkout session
- **GetSessionRequest** - Retrieve a session
- **UpdateSessionRequest** - Update a session
- **CancelSessionRequest** - Cancel a session
- **GetPaginatedSessionsRequest** - List sessions with pagination
## Invoices
- **GetInvoiceRequest** - Retrieve an invoice
- **GetPaginatedInvoiceRequest** - List invoices with pagination
## Sales Invoices
- **CreateSalesInvoiceRequest** - Create a sales invoice
- **GetSalesInvoiceRequest** - Retrieve a sales invoice
- **UpdateSalesInvoiceRequest** - Update a sales invoice
- **DeleteSalesInvoiceRequest** - Delete a sales invoice
- **GetPaginatedSalesInvoicesRequest** - List sales invoices with pagination
## Payment Routes
- **CreateDelayedPaymentRouteRequest** - Create a delayed payment route
- **ListPaymentRoutesRequest** - List payment routes
- **UpdatePaymentRouteRequest** - Update a payment route
## Payment Captures
- **CreatePaymentCaptureRequest** - Create a payment capture
- **GetPaymentCaptureRequest** - Retrieve a payment capture
- **GetPaginatedPaymentCapturesRequest** - List payment captures with pagination
## Payment Chargebacks
- **GetPaymentChargebackRequest** - Retrieve a payment chargeback
- **GetPaginatedPaymentChargebacksRequest** - List payment chargebacks with pagination
- **GetPaginatedChargebacksRequest** - List all chargebacks with pagination
## Other Resources
- **GetClientRequest** - Retrieve a client
- **GetPaginatedClientRequest** - List clients with pagination
- **CreateClientLinkRequest** - Create a client link
- **GetCapabilityRequest** - Retrieve a capability
- **ListCapabilitiesRequest** - List capabilities
- **GetPermissionRequest** - Retrieve a permission
- **ListPermissionsRequest** - List permissions
- **GetTerminalRequest** - Retrieve a terminal
- **GetPaginatedTerminalsRequest** - List terminals with pagination
- **GetOrganizationRequest** - Retrieve an organization
- **GetOnboardingStatusRequest** - Get onboarding status
- **GetOrganizationPartnerStatusRequest** - Get organization partner status
- **CreateConnectBalanceTransferRequest** - Create a Connect balance transfer
- **GetConnectBalanceTransferRequest** - Retrieve a Connect balance transfer
- **ListConnectBalanceTransfersRequest** - List Connect balance transfers
- **ApplePayPaymentSessionRequest** - Request Apple Pay payment session
## Using Request Classes
All request classes are located in the `Mollie\Api\Http\Requests` namespace.
**Example:**
```php
use Mollie\Api\Http\Requests\CreatePaymentRequest;
use Mollie\Api\Http\Data\Money;
$request = new CreatePaymentRequest(
description: 'Order #12345',
amount: Money::euro('10.00'),
redirectUrl: 'https://example.com/redirect',
webhookUrl: 'https://example.com/webhook'
);
$payment = $mollie->send($request);
```
For detailed parameter information, use your IDE's autocomplete features, or refer to the [Official API documentation](https://docs.mollie.com/reference/overview).
## See Also
- [Requests Documentation](requests.md) - General information about using requests
- [Endpoint Collections](endpoint-collections.md) - Alternative way to interact with the API
- [Mollie API Reference](https://docs.mollie.com/reference/overview) - Official API documentation
+90
View File
@@ -0,0 +1,90 @@
# Requests
## Overview
The Mollie API client uses request classes to communicate with the Mollie API. Each request class handles specific API endpoints and operations. The response is casted into a dedicated `Mollie\Api\Resources\*` class.
For a complete list of available request classes, see the [Request Reference](request-reference.md).
## Sending a Request
To send a request using the Mollie API client, you typically need to:
1. **Create an instance of the client**:
```php
use Mollie\Api\MollieApiClient;
$mollie = new MollieApiClient();
$mollie->setApiKey('test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM');
```
2. **Create and configure the request**:
Depending on the operation, you might need to create an instance of a specific request class and configure it with necessary parameters.
3. **Send the request**:
Use the client to send the request and handle the response.
## Best Practices: Using Named Parameters (PHP 8.0+)
**Recommended**: Use named parameters for cleaner, more readable code. This approach makes it clear what each parameter represents and avoids issues with optional parameters:
```php
use Mollie\Api\MollieApiClient;
use Mollie\Api\Http\Data\Money;
use Mollie\Api\Http\Requests\CreatePaymentRequest;
$mollie = new MollieApiClient();
$mollie->setApiKey('test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
// Recommended: Use named parameters (PHP 8.0+)
$createPaymentRequest = new CreatePaymentRequest(
description: 'Test payment',
amount: Money::euro('10.00'), // Using convenience method
redirectUrl: 'https://example.org/redirect',
webhookUrl: 'https://example.org/webhook',
locale: 'en_US',
metadata: ['order_id' => '123']
);
// In v4 the return type is inferred from the request class — no @var needed
$payment = $mollie->send($createPaymentRequest);
// $payment is Mollie\Api\Resources\Payment
```
## Adding unsupported properties
If the SDK is not up to date with the API, you can manually add a property to a request via the `query()` or `payload()` methods.
```php
$someRequestUsingPayload = new SomePayloadRequest(...);
$someRequestUsingPayload->payload()->add('foo', 'bar');
$someRequestUsingQueryParams = new SomeQueryRequest(...);
$someRequestUsingQueryParams->query()->add('foo', 'bar');
```
## Parameter Ordering Notes
For legacy reasons, some request classes have optional parameters before required parameters in their constructors. This can trigger PHP 8+ deprecation warnings when using positional arguments. To avoid this:
1. **Use named parameters** (recommended for PHP 8.0+):
```php
use Mollie\Api\Http\Requests\CreatePaymentRefundRequest;
use Mollie\Api\Http\Data\Money;
// Using named parameters avoids deprecation warnings
$request = new CreatePaymentRefundRequest(
paymentId: $paymentId,
amount: Money::euro('10.00'),
description: 'Refund description'
);
```
2. **Use factory methods** where available:
```php
// CreatePaymentRefundRequest has a factory method with correct parameter order
$request = CreatePaymentRefundRequest::for(
$paymentId,
Money::euro('10.00'),
'Refund description'
);
```
+119
View File
@@ -0,0 +1,119 @@
# Responses
Whether you interact with the endpoints using the traditional method (`$mollie->payments->...`) or the new `Request` classes, you can always inspect the raw `Response`.
## Resource Hydration
By default, all responses from are automatically hydrated into the corresponding `Resource` or `ResourceCollection` objects. You can still access the raw response using the `->getResponse()` method.
For example, when retrieving a payment you'll receive a Payment resource object, on which you can still access the raw Response class.
```php
/**
* Legacy approach
*
* @var Mollie\Api\Resources\Payment $payment
*/
$payment = $mollie->payments->get('tr_*********');
/**
* New approach
*
* @var Mollie\Api\Resources\Payment $payment
*/
$payment = $mollie->send(new GetPaymentRequest('tr_*********'));
$response = $payment->getResponse();
```
`getResponse()` returns `?Response`. Resources produced by an API call always
carry a non-null `Response`. Resources hydrated from a signed webhook snapshot
return `null` (there was no HTTP call). Null-check before chaining, or use
`getOrigin()` for origin-agnostic metadata — see [`docs/webhooks.md`](webhooks.md).
## Resource Wrappers
Sometimes it's useful to hydrate a class of your own with the information returned by the API. A wrapper can expose a subset of the resource's properties or cast them into your own objects, while retaining access to the underlying `Resource` it wraps.
### Define a Wrapper
```php
use Mollie\Api\Http\Data\Money;
use Mollie\Api\Resources\Payment;
use Mollie\Api\Resources\ResourceWrapper;
class PaymentWrapper extends ResourceWrapper
{
public function __construct(
public Money $amount,
public ?\DateTimeImmutable $createdAt,
) {
}
public static function fromResource($resource): self
{
/** @var Payment $resource */
return (new self(
amount: $resource->amount,
createdAt: $resource->createdAt === null
? null
: new \DateTimeImmutable($resource->createdAt),
))->setWrapped($resource);
}
}
```
### Usage
Call `wrapInto()` on the request. `send()` then returns your wrapper, and PHPStan infers its type without a `@var` annotation:
```php
use Mollie\Api\Http\Requests\GetPaymentRequest;
$paymentWrapper = $mollie->send(
(new GetPaymentRequest('tr_*********'))->wrapInto(PaymentWrapper::class)
);
// $paymentWrapper is PaymentWrapper
```
PHPStan currently honors both the `@phpstan-self-out` and `@psalm-this-out` annotations, and the committed fixture guards their combined inference contract. This repository does not run Psalm, so Psalm behavior is not verified here. PhpStorm does not infer the narrowed type.
To hydrate into a different SDK resource class first, call `hydrateInto()` before `wrapInto()`:
```php
use Mollie\Api\Http\Requests\DynamicGetRequest;
use Mollie\Api\Http\Requests\GetPaginatedPaymentRefundsRequest;
use Mollie\Api\Resources\RefundCollection;
// Payment::$_links is ?stdClass, and a payment only carries a `refunds` link
// when the API includes one — a payment with no refunds has neither. Guard
// both hops in one isset(), the same way Payment::refunds() does internally.
if (! isset($payment->_links->refunds->href)) {
// Fall back to the paginated endpoint, which routes by payment id. Keep
// the same hydrateInto()/wrapInto() chain as the linked branch so both
// branches hand back a RefundsWrapper, not a bare RefundCollection.
$refunds = $mollie->send(
(new GetPaginatedPaymentRefundsRequest(paymentId: $payment->id))
->hydrateInto(RefundCollection::class)
->wrapInto(RefundsWrapper::class)
);
} else {
$refunds = $mollie->send(
(new DynamicGetRequest($payment->_links->refunds->href))
->hydrateInto(RefundCollection::class)
->wrapInto(RefundsWrapper::class)
);
}
```
`RefundsWrapper` is an application wrapper implementing `IsWrapper`, for example by extending `ResourceWrapper` as above. Call request-specific setters first, then `hydrateInto()`, then `wrapInto()` last. Reversing the two named helpers makes static analysis report the hydration target while runtime still returns the wrapper.
`setHydratableResource(new WrapperResource(PaymentWrapper::class))` still works, but it keeps the request's original generic type, so `send()` cannot infer the wrapper.
The original `Payment` resource properties and methods can be accessed through the wrapper class.
```php
// access property
$paymentWrapper->status;
// access method
$paymentWrapper->isPaid();
```
+137
View File
@@ -0,0 +1,137 @@
# Retry strategies
The Mollie PHP client automatically retries requests that fail with retryable network errors. You can customize how many retries are performed and how long to wait between attempts by providing a retry strategy.
## Default behavior
- Strategy: `LinearRetryStrategy`
- Default max retries: `5` (in addition to the initial attempt)
- Default delay: linear backoff with a 1000ms increase per attempt
- Attempt 1 (first retry): 1000ms
- Attempt 2: 2000ms
- Attempt 3: 3000ms
- … up to the configured maximum
If all retries are exhausted, the last `Mollie\Api\Exceptions\RetryableNetworkRequestException` is thrown. Fatal middleware hooks, if configured, run once after retries are exhausted.
## Changing the defaults
To change the retry behavior, provide your own strategy instance to the client:
```php
use Mollie\Api\MollieApiClient;
use Mollie\Api\Http\Retry\LinearRetryStrategy;
$client = new MollieApiClient();
// Example: 2 retries with no delay (useful in tests)
$client->setRetryStrategy(new LinearRetryStrategy(2, 0));
// Example: 3 retries with 500ms linear increase (0.5s, 1.0s, 1.5s)
$client->setRetryStrategy(new LinearRetryStrategy(3, 500));
```
To effectively disable retries, set the max retries to `0`:
```php
$client->setRetryStrategy(new LinearRetryStrategy(0, 0));
```
## Exponential backoff with 429 / Retry-After
`ExponentialRetryStrategy` does exponential backoff with optional jitter, and additionally retries `TooManyRequestsException` (HTTP 429). A numeric `Retry-After` is honoured when it fits within `maxDelayMs`. With jitter enabled, the strategy adds up to 10% (capped at 1000ms) so throttled clients do not retry simultaneously. It never retries early: if `Retry-After` exceeds `maxDelayMs`, the exception is thrown immediately.
```php
use Mollie\Api\Http\ExponentialRetryStrategy;
$client->setRetryStrategy(new ExponentialRetryStrategy(
maxRetries: 5,
baseDelayMs: 500,
multiplier: 2.0,
maxDelayMs: 30_000,
jitter: true,
));
```
Use this strategy when you want graceful handling of 429 rate limits — the linear strategy only retries network errors.
### Inspecting rate-limit headers
Every response exposes Mollie's `RateLimit` and `RateLimit-Policy` values:
```php
$rateLimit = $response->rateLimit();
$rateLimit?->policy;
$rateLimit?->remaining;
$rateLimit?->restoreSeconds;
$rateLimit?->burst;
$rateLimit?->quota;
$rateLimit?->windowSeconds;
```
Missing headers or parameters produce `null` values. API exceptions retain their response, so the same data is available on a 429 through `$exception->getResponse()->rateLimit()`.
## Creating your own strategy
Custom strategies implement the `Mollie\Api\Contracts\RetryStrategyContract` interface:
```php
namespace Mollie\Api\Contracts;
use Throwable;
interface RetryStrategyContract
{
// Maximum number of retries after the initial attempt
public function maxRetries(): int;
// Whether this exception should be retried
public function shouldRetry(Throwable $exception): bool;
// Delay in milliseconds before performing the given retry attempt
// $attempt starts at 1 for the first retry
public function delayBeforeAttemptMs(int $attempt, ?Throwable $exception = null): int;
}
```
### Example: Fixed delay strategy
```php
use Mollie\Api\Contracts\RetryStrategyContract;
use Mollie\Api\Exceptions\RetryableNetworkRequestException;
use Throwable;
class FixedDelayRetryStrategy implements RetryStrategyContract
{
public function __construct(
private int $maxRetries = 3,
private int $delayMs = 1000,
) {}
public function maxRetries(): int
{
return max(0, $this->maxRetries);
}
public function shouldRetry(Throwable $exception): bool
{
return $exception instanceof RetryableNetworkRequestException;
}
public function delayBeforeAttemptMs(int $attempt, ?Throwable $exception = null): int
{
// Same delay for every retry
return max(0, $this->delayMs);
}
}
// Usage
$client->setRetryStrategy(new FixedDelayRetryStrategy(3, 250));
```
You can implement any retry timing and retryability rules you prefer (e.g., exponential backoff with jitter, capped delays, retrying 429 responses, etc.) as long as you adhere to the contract.
## When retries happen
Retries are performed only when the configured retry strategy returns `true` from `shouldRetry()`. The default `LinearRetryStrategy` retries `Mollie\Api\Exceptions\RetryableNetworkRequestException` only, matching the v3 default behavior. `ExponentialRetryStrategy` also retries `TooManyRequestsException` for HTTP 429 responses when `Retry-After` is absent or fits within `maxDelayMs`.
+267
View File
@@ -0,0 +1,267 @@
# Testing with Mollie API Client
## Test Mode Configuration
### Key Concepts
- Test mode is automatically determined by API key prefix (`test_` or `live_`)
- Explicit `testmode` parameter available for OAuth scenarios
- Configure at global client level or per individual request
### Global Configuration
```php
use Mollie\Api\MollieApiClient;
$mollie = new MollieApiClient();
$mollie->setApiKey("test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM");
$mollie->test(true); // Applies to all subsequent requests
```
### Per-Request Configuration
```php
// Payment request with test mode
$createPaymentRequest = new CreatePaymentRequest(/* ... */);
$mollie->send($createPaymentRequest->test(true));
// Endpoint collection example
$customer = $mollie->customers->get('cust_12345678', testmode: true);
```
## API Mocking
### Typed Mock Responses
The fastest path is the typed `MockResponse` factories — they merge a fixture base with the typed overrides you pass:
```php
use Mollie\Api\Fake\MockResponse;
use Mollie\Api\Http\Data\Money;
use Mollie\Api\Http\Requests\GetPaymentRequest;
use Mollie\Api\MollieApiClient;
use Mollie\Api\Types\PaymentStatus;
$client = MollieApiClient::fake([
GetPaymentRequest::class => MockResponse::payment(
id: 'tr_xxxxxxxxxxxx',
status: PaymentStatus::Paid,
amount: new Money(currency: 'EUR', value: '20.00'),
description: 'Test',
),
]);
$payment = $client->send(new GetPaymentRequest('tr_xxxxxxxxxxxx'));
$client->assertSent(GetPaymentRequest::class);
```
Available typed factories: `payment`, `customer`, `subscription`, `mandate`, `refund`, `chargeback`, `method`, `paymentLink`, `invoice`, `capture`. Each accepts a `$overrides` array for fields not covered by named arguments.
### Basic Usage
API responses can be simulated without network calls by using the `MollieApiClient::fake()` method. Each Request/Response pair passed to the fake method is consumed after a matching request.
> [!NOTE]
> To keep pairs available for reuse after they've been matched, use the `retainRequests` parameter: `MollieApiClient::fake([...], retainRequests: true)`
```php
use Mollie\Api\MollieApiClient;
use Mollie\Api\Fake\MockResponse;
use Mollie\Api\Http\Requests\GetPaymentRequest;
$client = MollieApiClient::fake([
GetPaymentRequest::class => new MockResponse(
body: [
'resource' => 'payment',
'id' => 'tr_xxxxxxxxxxxx',
'mode' => 'test',
'amount' => [
'value' => '20.00',
'currency' => 'EUR'
],
'description' => 'Test',
'status' => 'open',
// ...
],
status: 200
)
]);
$payment = $client->send(new GetPaymentRequest('tr_xxxxxxxxxxxx'));
```
### Sequence Mock Responses
To return different responses for the same request type, use `SequenceMockResponse` and pass `MockResponse` or `Closure` (which return `MockResponse` instances) in the order they should occur.
```php
$client = MollieApiClient::fake([
DynamicGetRequest::class => new SequenceMockResponse(
MockResponse::ok(['first' => 'response']),
MockResponse::ok(['second' => 'response']),
function (PendingRequest $pendingRequest) {
//...
return MockResponse::ok(['third' => 'response']);
}
)
]);
```
To verify that a request was sent, use `assertSent` or `assertSentCount`.
```php
$client->send(new GetPaymentRequest('tr_xxxxxxxxxxxx', embedRefunds: true));
$client->assertSent(GetPaymentRequest::class);
$client->assertSent(function (PendingRequest $pendingRequest, Response $response) {
return $pendingRequest->query()->get('embed') === 'refunds';
});
$client->assertSentCount(1);
```
### MockResponse Options
Configure responses using:
- **Arrays**: Direct data structure
- **Strings**: JSON payloads or predefined fixture names
- **Callables**: Dynamic response generation *or* intercepting assertions
```php
// Array response
MockResponse::created([
'id' => 'tr_xxxxxxxxxxxx',
'amount' => ['value' => '20.00', 'currency' => 'EUR']
]);
// Fixture response
MockResponse::created('payment');
// Dynamic response
MockResponse::created(function (PendingRequest $request) {
return ['amount' => $request->hasParameter('amount') ? 10 : 20];
});
// Intercepting assertions
function (PendingRequest $request) use ($idempotencyKey) {
$this->assertEquals($idempotencyKey, $request->headers()->get('Idempotency-Key'));
return MockResponse::created('payment');
};
```
### Working with Collections
Create paginated list responses:
```php
use Mollie\Api\Resources\PaymentCollection;
$client = MollieApiClient::fake([
GetPaginatedPaymentsRequest::class => MockResponse::list(PaymentCollection::class)
->add([
'resource' => 'payment',
'id' => 'tr_xxxxxxxxxxxx',
'mode' => 'test',
'amount' => [
'value' => '20.00',
'currency' => 'EUR'
],
'description' => 'Test',
'status' => 'open',
// ...
])
->create()
]);
```
### Handling Embedded Resources
Simulate HAL+JSON embedded resources using the `_embedded` property:
**Key Concepts**
- Use `MockResponse::resource()` to start building a resource response
- Chain `embed()` calls to add related collections
- Maintain resource relationships with a fluent interface
```php
use Mollie\Api\Resources\Payment;
use Mollie\Api\Resources\RefundCollection;
use Mollie\Api\Resources\ChargebackCollection;
$client = MollieApiClient::fake([
GetPaymentRequest::class => MockResponse::resource(Payment::class)
->with([ // Main resource properties
'resource' => 'payment',
'id' => 'tr_xxxxxxxxxxxx',
'amount' => [
'value' => '20.00',
'currency' => 'EUR'
]
])
->embed(RefundCollection::class) // First embedded collection
->add([
'resource' => 'refund',
'id' => 're_12345',
'amount' => [
'value' => '10.00',
'currency' => 'EUR'
]
])
->embed(ChargebackCollection::class) // Second embedded collection
->add([
'resource' => 'chargeback',
'id' => 'chb_12345',
'amount' => [
'value' => '20.00',
'currency' => 'EUR'
]
])
->create()
]);
// Resulting response will contain:
// - Payment details in main body
// - Refunds in _embedded.refunds
// - Chargebacks in _embedded.chargebacks
```
### Error Response Mocking
Simulate API error responses using dedicated helper methods or the generic error builder:
**Common Error Shortcuts**
```php
use Mollie\Api\Fake\MockResponse;
// 404 Not Found
$client = MollieApiClient::fake([
GetPaymentRequest::class => MockResponse::notFound('No payment exists with token tr_xxxxxxxxxxx')
]);
// 422 Validation Error (with optional field reference)
$client = MollieApiClient::fake([
CreatePaymentRequest::class => MockResponse::unprocessableEntity(
detail: 'Amount must be at least €1.00',
field: 'amount'
)
]);
```
**Generic Error Builder**
```php
// Custom status code example
$response = MockResponse::error(
status: 403,
title: 'Forbidden',
detail: 'Insufficient permissions to access this resource'
);
// Special characters handling
$detail = 'Invalid parameter "recurringType" - did you mean "sequenceType"?';
$response = MockResponse::unprocessableEntity($detail, 'field');
```
**Error Response Structure**
All errors follow Mollie's standardized format:
```json
{
"status": 404,
"title": "Not Found",
"detail": "No payment exists with token tr_xxxxxxxxxxx",
"field": "amount" // Only present for validation errors
}
```
+257
View File
@@ -0,0 +1,257 @@
# Webhooks
Mollie uses webhooks to notify your application about events that occur in your Mollie account. This guide explains how to work with Mollie webhooks in your application securely and efficiently. Mollie currently supports two types of webhooks: the (soon to be labeled) "legacy webhooks" and "next-gen webhooks". This guide is about the next-gen webhooks.
## Overview
Webhooks are HTTP POST requests that Mollie sends to your application when specific events occur, such as when a payment is completed, failed, or refunded. This allows your application to respond to these events in real-time without constantly polling the Mollie API.
## Security
### Signature Verification
**Important**: Always verify webhook signatures to ensure requests come from Mollie and haven't been tampered with.
Mollie signs all webhook requests with an HMAC-SHA256 signature sent in the `X-Mollie-Signature` header. The SDK provides built-in signature verification:
```php
use Mollie\Api\Webhooks\SignatureValidator;
use Mollie\Api\Exceptions\InvalidSignatureException;
$signingSecret = "your_webhook_signing_secret_from_dashboard";
try {
$validator = new SignatureValidator($signingSecret);
/**
* Validate the webhook signature
*
* This method will throw an InvalidSignatureException if:
* - A signature header is present but doesn't contain a valid signature
* - The payload has been tampered with
*
* For PSR-7 requests, you can also use validateRequest($psr7Request)
*/
$isValid = $validator->validatePayload($requestBody, $signature);
if (!$isValid) {
// Handle invalid signature
http_response_code(400);
exit('Invalid signature');
}
// Signature is valid - proceed with webhook processing
} catch (InvalidSignatureException $e) {
// Log the invalid signature attempt for security monitoring
error_log("Invalid webhook signature: " . $e->getMessage());
http_response_code(400);
exit('Invalid signature');
}
```
#### Key Rotation
During key rotation or migration periods, you can verify signatures against multiple secrets:
```php
$signingSecrets = [
"current_secret",
"previous_secret" // Keep old secret during transition period
];
$validator = new SignatureValidator($signingSecrets);
$isValid = $validator->validatePayload($requestBody, $signature);
```
### Processing Webhook Payloads
Once you've verified the webhook signature, you can safely process the payload:
```php
use Mollie\Api\Webhooks\Events\BalanceTransactionCreated;
use Mollie\Api\Webhooks\Events\PaymentLinkPaid;
use Mollie\Api\Webhooks\WebhookEventMapper;
// Process the webhook payload into an event object. Pass the signature
// (when available) so the resulting resource carries webhook provenance
// — see "Inspecting webhook provenance" below.
$event = (new WebhookEventMapper())->processPayload(
$request->getParsedBody(),
$signature,
);
// Extract the entity ID (e.g., payment ID, customer ID, etc.)
$entityId = $event->entityData('id');
// Hydrate the embedded entity snapshot into a fully typed SDK resource.
// No HTTP call is made — the signed webhook payload is the source of truth.
// If you subscribe to "simple" payloads (entityId only), the $event->entity
// property is null and calling $event->entity() throws. Check the property
// first, or fetch the resource yourself via its Get request using
// $event->entityId.
$resource = $event->asResource($mollie);
// Handle different event types
match (true) {
$event instanceof PaymentLinkPaid => $this->handlePaymentLinkPaid(),
$event instanceof BalanceTransactionCreated => $this->handleBalanceTransactionCreated(),
// ... handle other event types
};
```
#### Using custom webhook Events
If the API is ahead of this SDK's implementation of new Events, you can create your own Events as temporary workaround and pass it into the `WebhookEventMapper`
```php
// Event class
use Mollie\Api\Webhooks\Events\BaseEvent;
class SomeEventHappened extends BaseEvent
{
public static function type(): string
{
return 'some.event_happened'; // needs to match the eventType from the documentation
}
}
// passing into event mapper and processing payload
$event = (new WebhookEventMapper([
'some.event_happened' => SomeEventHappened::class
]))->processPayload($request->getParsedBody());
```
### Inspecting webhook provenance
Resources hydrated from a webhook carry a `WebhookSnapshotOrigin` instead
of an HTTP `Response`. You can inspect the event metadata without hitting
the API:
```php
$resource = $event->asResource($mollie);
$resource->getResponse(); // null — there was no HTTP call
$resource->getOrigin(); // WebhookSnapshotOrigin
$resource->getOrigin()->getEventId(); // 'event_GvJ8WHrp5isUdRub9CJyH'
$resource->getOrigin()->getSignature(); // the X-Mollie-Signature header, or null
$resource->getOrigin()->getReceivedAt(); // DateTimeImmutable
```
Resources fetched via the API (for example via `$mollie->send(new
GetPaymentRequest(...))`) still return a `Response` from `getResponse()`
as before.
Follow-up methods like `$payment->refunds()`, `$profile->methods()`, and
`$subscription->payments()` work the same on webhook-origin resources
as they do on HTTP-origin resources. When the embedded snapshot carries
the link URL, the SDK follows it; when it does not, the SDK routes the
request through the connector using the resource's id. Either way, the
call fires real HTTP to Mollie, which means a valid API key must be
configured on the client. A webhook handler running without an API key
is limited to reading the signed snapshot itself — there is no path
that lets the SDK reach Mollie without credentials.
### Reading from the snapshot vs. fetching fresh data
A complete handler usually combines both. The signed snapshot is enough
to make decisions. When you need data the snapshot doesn't carry
(related resources, the very latest server state), fall back to the
API. The API fallback requires a valid key on the client — the snapshot
path does not.
```php
use Mollie\Api\Exceptions\InvalidSignatureException;
use Mollie\Api\MollieApiClient;
use Mollie\Api\Webhooks\Events\PaymentLinkPaid;
use Mollie\Api\Webhooks\SignatureValidator;
use Mollie\Api\Webhooks\WebhookEventMapper;
$mollie = new MollieApiClient;
$mollie->setApiKey(getenv('MOLLIE_API_KEY')); // only needed for the fetch path
$signingSecret = getenv('MOLLIE_WEBHOOK_SIGNING_SECRET');
$requestBody = (string) $request->getBody();
$signature = $request->getHeaderLine('X-Mollie-Signature');
try {
if (! (new SignatureValidator($signingSecret))->validatePayload($requestBody, $signature)) {
http_response_code(400);
exit('Invalid signature');
}
} catch (InvalidSignatureException $e) {
error_log("Invalid webhook signature: " . $e->getMessage());
http_response_code(400);
exit('Invalid signature');
}
$event = (new WebhookEventMapper)->processPayload(
json_decode($requestBody, true),
$signature,
);
if (! $event instanceof PaymentLinkPaid) {
// Not the event we care about — ack and return.
http_response_code(200);
return;
}
// 1. Snapshot path: no HTTP, no API key required.
// asResource() is typed as BaseResource, so narrow it for static analysis.
/** @var \Mollie\Api\Resources\PaymentLink $paymentLink */
$paymentLink = $event->asResource($mollie);
// PaymentLink::$amount is ?Money. An open-amount link never carried a fixed
// amount, so there is nothing on the link itself to record — the amount that
// was actually charged only exists on the payment that settled it (step 2).
$amount = $paymentLink->amount;
if ($amount === null) {
markOpenAmountOrderPaid(
orderId: $paymentLink->id,
paidAt: $event->createdAt,
);
} else {
markOrderPaid(
orderId: $paymentLink->id,
amount: $amount->value,
paidAt: $event->createdAt,
);
}
// 2. Fetch path: fires HTTP, needs the API key configured above.
// $paymentLink->payments() follows the link from the snapshot when
// present, otherwise routes through $mollie->paymentLinkPayments.
foreach ($paymentLink->payments() as $payment) {
reconcilePaymentLine($paymentLink->id, $payment);
}
http_response_code(200);
```
If your webhook handler runs without an API key (signing-secret-only
deployment), remove the `setApiKey()` call and skip step 2 — you can
still do everything in step 1 from the signed payload alone.
### Testing Webhooks
Testing webhooks is crucial to ensure your application handles all event types correctly. The SDK provides several tools to help you test webhook scenarios.
Use `MockEvent` to create realistic webhook payloads for testing:
```php
use Mollie\Api\Fake\MockEvent;
use Mollie\Api\Webhooks\Events\PaymentLinkPaid;
use Mollie\Api\Webhooks\Events\BalanceTransactionCreated;
// Create a mock PaymentLinkPaid event
$paymentLinkEventPayload = MockEvent::for(PaymentLinkPaid::class)
->entityId('pl_1234567890')
->snapshot() // Include full resource data
->create();
// Create a mock BalanceTransactionCreated event
$balanceEventPayload = MockEvent::for(BalanceTransactionCreated::class)
->entityId('bt_9876543210')
->simple() // Webhook request without any resource data besides entityId
->create();
```
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace Mollie\Api;
use Mollie\Api\Exceptions\IncompatiblePlatformException;
class CompatibilityChecker
{
/**
* @var string
*/
public const MIN_PHP_VERSION = '8.2';
public static function make(): self
{
return new self;
}
/**
* @return void
*
* @throws IncompatiblePlatformException
*/
public function checkCompatibility()
{
if (! $this->satisfiesPhpVersion()) {
throw new IncompatiblePlatformException(
'The client requires PHP version >= '.self::MIN_PHP_VERSION.', you have '.PHP_VERSION.'.',
IncompatiblePlatformException::INCOMPATIBLE_PHP_VERSION
);
}
if (! $this->satisfiesJsonExtension()) {
throw new IncompatiblePlatformException(
"PHP extension json is not enabled. Please make sure to enable 'json' in your PHP configuration.",
IncompatiblePlatformException::INCOMPATIBLE_JSON_EXTENSION
);
}
}
/**
* @return bool
*
* @codeCoverageIgnore
*/
public function satisfiesPhpVersion()
{
return (bool) version_compare(PHP_VERSION, self::MIN_PHP_VERSION, '>=');
}
/**
* @return bool
*
* @codeCoverageIgnore
*/
public function satisfiesJsonExtension()
{
// Check by extension_loaded
if (function_exists('extension_loaded') && extension_loaded('json')) {
return true;
} elseif (function_exists('json_encode')) {
return true;
}
return false;
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Mollie\Api;
use Mollie\Api\Resources\ResourceRegistry;
class Config
{
/**
* Resolver used to fetch the global ResourceRegistry, e.g. from a container.
*
* @var callable():ResourceRegistry|null
*/
private static $resourceRegistryResolver = null;
/**
* Set a resolver that returns a ResourceRegistry instance. Pass null to reset.
*
* @param callable():ResourceRegistry|null $resolver
*/
public static function setResourceRegistryResolver(?callable $resolver): void
{
self::$resourceRegistryResolver = $resolver;
}
/**
* Resolve the ResourceRegistry. Uses the resolver if set, otherwise defaults.
*/
public static function resourceRegistry(): ResourceRegistry
{
$resolver = self::$resourceRegistryResolver;
if (! is_callable($resolver)) {
return ResourceRegistry::default();
}
$registry = call_user_func($resolver);
if (! $registry instanceof ResourceRegistry) {
return ResourceRegistry::default();
}
return $registry;
}
}
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
interface Arrayable
{
public function toArray(): array;
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
interface Authenticatable
{
public function setApiKey(string $apiKey): self;
public function setAccessToken(string $accessToken): self;
public function getAuthenticator(): ?Authenticator;
}
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
use Mollie\Api\Http\PendingRequest;
interface Authenticator
{
public function authenticate(PendingRequest $pendingRequest): void;
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
use Mollie\Api\Http\Middleware;
use Mollie\Api\Http\Request;
interface Connector extends Authenticatable, IdempotencyContract, SupportsDebuggingContract, Testable
{
/**
* @return mixed
*/
public function send(Request $request);
public function resolveBaseUrl(): string;
public function headers(): Repository;
public function query(): Repository;
public function middleware(): Middleware;
public function addVersionString($versionString): self;
public function getVersionStrings(): array;
public function getHttpClient(): HttpAdapterContract;
}
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
interface EmbeddedResourcesContract
{
public function getEmbeddedResourcesMap(): array;
}
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
interface HasPayload
{
public function payload(): PayloadRepository;
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
use Mollie\Api\Http\PendingRequest;
use Mollie\Api\Http\Response;
use Mollie\Api\Utils\Factories;
interface HttpAdapterContract
{
public function factories(): Factories;
/**
* Send a request to the specified Mollie api url.
*
* @throws \Mollie\Api\Exceptions\ApiException
*/
public function sendRequest(PendingRequest $pendingRequest): Response;
/**
* The version number for the underlying http client, if available.
*
* @example Guzzle/6.3
*/
public function version(): ?string;
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
interface IdempotencyContract
{
public function getIdempotencyKey(): ?string;
public function resetIdempotencyKey(): self;
public function getIdempotencyKeyGenerator(): ?IdempotencyKeyGeneratorContract;
}
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
interface IdempotencyKeyGeneratorContract
{
public function generate(): string;
}
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
interface IsIteratable
{
public function iteratorEnabled(): bool;
public function iteratesBackwards(): bool;
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
use Mollie\Api\Http\Response;
interface IsResponseAware extends ViableResponse
{
/**
* Returns the HTTP `Response` this resource was hydrated from, or
* `null` when the resource was hydrated from a non-HTTP origin
* (for example a signed webhook envelope). Use
* {@see \Mollie\Api\Contracts\ResourceOrigin} via
* `$resource->getOrigin()` to inspect provenance across both cases.
*/
public function getResponse(): ?Response;
/**
* @return $this
*/
public function setResponse(Response $response);
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
use Mollie\Api\Http\Response;
use Mollie\Api\Resources\BaseCollection;
use Mollie\Api\Resources\BaseResource;
use Mollie\Api\Resources\LazyCollection;
interface IsWrapper extends ViableResponse
{
/**
* @param Response|BaseResource|BaseCollection|LazyCollection $resource
*/
public static function fromResource($resource): self;
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
interface MollieHttpAdapterPickerContract
{
/**
* @param \GuzzleHttp\ClientInterface|HttpAdapterContract $httpClient
*/
public function pickHttpAdapter($httpClient): HttpAdapterContract;
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\StreamInterface;
interface PayloadRepository extends Repository
{
/**
* Convert the repository contents into a stream
*/
public function toStream(StreamFactoryInterface $streamFactory): StreamInterface;
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
interface Repository
{
/**
* Set the entire repository data
*
* @param mixed $data Array for array repositories, mixed for payload repositories
* @return static
*/
public function set($data);
/**
* Get a value by key
*
* @param mixed $default
* @return mixed
*/
public function get(string $key, $default = null);
/**
* Check if a key exists
*/
public function has(string $key): bool;
/**
* Add a value to the repository
*
* @param mixed $value
* @return static
*/
public function add(string $key, $value);
/**
* Merge data into the repository
*
* @return static
*/
public function merge(array ...$data);
/**
* Remove a key from the repository
*/
public function remove(string $key);
/**
* Get all data from the repository
*
* @return mixed
*/
public function all();
/**
* Check if the repository is empty
*/
public function isEmpty(): bool;
/**
* Check if the repository is not empty
*/
public function isNotEmpty(): bool;
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
use Mollie\Api\Http\PendingRequest;
interface RequestMiddleware
{
/**
* @return PendingRequest|void
*/
public function __invoke(PendingRequest $pendingRequest);
}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
interface Resolvable extends Arrayable
{
}
@@ -0,0 +1,16 @@
<?php
namespace Mollie\Api\Contracts;
/**
* Marker contract for "where did this hydrated resource come from."
*
* Implemented by {@see \Mollie\Api\Http\Response} for HTTP-hydrated
* resources and by {@see \Mollie\Api\Webhooks\WebhookSnapshotOrigin}
* for resources hydrated from a signed webhook envelope. Additional
* implementations can be added without touching the hydrator.
*/
interface ResourceOrigin
{
public function getConnector(): Connector;
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Mollie\Api\Contracts;
use Mollie\Api\Http\Response;
interface ResponseMiddleware
{
/**
* @return Response|void
*/
public function __invoke(Response $response);
}
Loaded 100 of 822 files, more files were not shown because too many files have changed in this diff. Show more