Mollie Payments API: hosted checkout, webhooks and refunds

Accept iDEAL, cards, Bancontact and other European methods with Mollie: create a payment, redirect to the hosted checkout, confirm it by re-fetching the payment when the webhook arrives, and issue refunds — in Node, Laravel and Django.

Provider
Mollie
Level
Beginner
Stacks
Node.js (Express), PHP (Laravel), Python (Django)
Code maturity
Sandbox-ready
Last verified
25 Nov 2026

Introduction

Mollie is a European payment service provider with a deliberately small API. You create a payment on your server, send the customer to Mollie's hosted checkout, and Mollie calls your webhook whenever the payment's status changes.

Mollie's classic webhook is unusual: it contains only the payment ID. Your server must fetch the payment from the API to learn its status. That fetch is what makes the webhook trustworthy, and it is the core pattern this guide teaches.

What the Payments API does

  • POST https://api.mollie.com/v2/payments creates a payment with an amount, description, redirectUrl and (recommended) webhookUrl.
  • The response contains _links.checkout.href — redirect the customer there (SDKs expose getCheckoutUrl() / checkout_url).
  • The customer chooses a method and pays on Mollie's page, then returns to your redirectUrl.
  • Mollie POSTs id=tr_... to your webhookUrl on status changes; you GET /v2/payments/{id} and update your order.
  • Statuses: open, pending, authorized, paid, canceled, expired, failed.

Countries

Mollie onboards businesses in a set of European countries and supports local methods such as iDEAL (NL), Bancontact (BE) and others alongside cards. The exact list of merchant countries and methods per country changes; check Mollie's website and Dashboard before committing. This guide does not list countries to avoid stale data.

Payment methods

Methods are enabled per website profile in the Mollie Dashboard. If you omit method when creating a payment, the hosted checkout shows every enabled method valid for the amount and currency. Pass method to skip the selection screen.

Some methods confirm instantly, others (bank transfer, some debits) move through open/pending for days — your webhook handler must cope with late status changes.

When to use Mollie

  • European e-commerce or SaaS that needs local methods (iDEAL, Bancontact, ...) plus cards through one integration.
  • Teams that want a hosted checkout and a small, readable API.
  • Simple recurring payments (Mollie also has customers, mandates and subscriptions — out of scope here).

When not to use it

  • Your business is outside Mollie's onboarding countries.
  • You need local methods outside Europe (mobile money, UPI, Pix, ...): pick a regional provider.
  • You need a merchant of record that files VAT for you.

Example scenarios

  • Dutch webshop: iDEAL + cards, order marked paid from the webhook, customer sees a "thanks, we're confirming your payment" page.
  • Event tickets in Belgium: Bancontact; tickets e-mailed only when the payment reaches paid.
  • Partial refund: customer returns one item; you refund part of the amount via the Refunds API.

Registration

Sign up at mollie.com and create a website profile. You get test API keys immediately; live keys work only after Mollie has reviewed your business (KYC, bank account). You can build and test the whole integration before approval.

Test mode

There is no separate sandbox host: use the test API key (test_...) against the same api.mollie.com. Test-mode data is isolated from live data. In test mode the hosted checkout is replaced by a test checkout screen where you choose the outcome (paid, failed, canceled, expired, ...), so you can exercise every branch of your webhook handler without real money.

Warning: Mollie rejects localhost webhook URLs: the webhookUrl must be reachable from the internet. Use a tunnel (e.g. ngrok) during local development.

Credentials

  • API key per website profile: test_... and live_.... Server-side only.
  • (Optional) organisation access tokens / OAuth for platforms acting on behalf of other merchants — not needed here.

There is no webhook signing secret for classic payment webhooks; security comes from re-fetching the payment with your API key.

Security: Never put the API key in frontend code. The Node client even requires an explicit dangerouslyAllowBrowser flag to run in a browser — do not set it for a secret key.

Environment configuration

Keep keys in environment variables and commit only placeholders.

.env.example · Node.js (Express)

# Mollie — use the test key while developing
MOLLIE_API_KEY=test_replace_me
# Public HTTPS base URL (tunnel URL in development; localhost is rejected for webhooks)
PUBLIC_BASE_URL=https://your-tunnel.example.com

Authentication

Every API call sends Authorization: Bearer <API key>. The key itself decides test vs live mode and the website profile, so you do not pass a testmode flag when using an API key. The SDKs set the header for you.

Backend: create a payment

Create your own order first (status pending), then the Mollie payment. Amounts are strings with the currency's decimals ("10.00" for EUR) — not minor-unit integers. Store the Mollie payment ID (tr_...) on the order. Use the Idempotency-Key header on POSTs you might retry: Mollie caches keys for one hour, returns the original response with Idempotent-Replayed: true, answers 400 if the same key is reused with different parameters and 409 while the first request is still running.

server.js — create payment and redirect · Node.js (Express)

import express from 'express';
import createMollieClient from '@mollie/api-client';
import { orders } from './orders.js'; // your data layer

const mollie = createMollieClient({ apiKey: process.env.MOLLIE_API_KEY });
const app = express();
app.use(express.urlencoded({ extended: false })); // Mollie webhooks are form-encoded
app.use(express.json());

app.post('/checkout', async (req, res) => {
  // Price comes from YOUR catalogue, never from the browser
  const order = await orders.createFromCart(req.session.cartId); // { id, totalCents, currency }
  const value = (order.totalCents / 100).toFixed(2); // "10.00"

  const payment = await mollie.payments.create({
    amount: { currency: order.currency, value },
    description: `Order ${order.id}`,
    redirectUrl: `${process.env.PUBLIC_BASE_URL}/orders/${order.id}/return`,
    webhookUrl: `${process.env.PUBLIC_BASE_URL}/webhooks/mollie`,
    metadata: { orderId: order.id },
  });

  await orders.attachPayment(order.id, payment.id);
  res.redirect(303, payment.getCheckoutUrl());
});

// The customer comes back here — show status from YOUR db, do not mark paid here.
app.get('/orders/:id/return', async (req, res) => {
  const order = await orders.find(req.params.id);
  res.send(order.status === 'paid' ? 'Thanks, payment received.' : 'We are confirming your payment…');
});

app.listen(3000);

app/Http/Controllers/CheckoutController.php (laravel-mollie) · PHP (Laravel)

<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Mollie\Api\Http\Data\Money;
use Mollie\Api\Http\Requests\CreatePaymentRequest;
use Mollie\Laravel\Facades\Mollie;

class CheckoutController extends Controller
{
    public function store()
    {
        // Build the order from your own catalogue prices
        $order = Order::createFromCart(auth()->user());

        $payment = Mollie::send(new CreatePaymentRequest(
            description: 'Order '.$order->id,
            amount: Money::of($order->currency)->fromString(number_format($order->total_cents / 100, 2, '.', '')),
            redirectUrl: route('orders.return', $order),
            webhookUrl: route('webhooks.mollie'),
            metadata: ['order_id' => $order->id],
        ));

        $order->update(['mollie_payment_id' => $payment->id]);

        return redirect($payment->getCheckoutUrl(), 303);
    }
}

shop/views.py — create payment · Python (Django)

import os
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, get_object_or_404, render
from django.views.decorators.http import require_POST
from mollie.api.client import Client
from .models import Order

mollie = Client()
mollie.set_api_key(os.environ['MOLLIE_API_KEY'])
BASE = os.environ['PUBLIC_BASE_URL']

@login_required
@require_POST
def checkout(request):
    order = Order.create_from_cart(request.user)  # prices from your catalogue
    payment = mollie.payments.create({
        'amount': {'currency': order.currency, 'value': f'{order.total_cents / 100:.2f}'},
        'description': f'Order {order.pk}',
        'redirectUrl': f'{BASE}/orders/{order.pk}/return',
        'webhookUrl': f'{BASE}/webhooks/mollie',
        'metadata': {'order_id': order.pk},
    })
    order.mollie_payment_id = payment.id
    order.save(update_fields=['mollie_payment_id'])
    return redirect(payment.checkout_url)

@login_required
def order_return(request, pk):
    order = get_object_or_404(Order, pk=pk, user=request.user)
    return render(request, 'shop/return.html', {'order': order})  # status from YOUR db

Warning: Use integers (cents) internally and format to a two-decimal string only when calling Mollie; never compute money with floats you then round inconsistently. Zero-decimal currencies need a different format — check the currency's decimals.

Frontend

With the hosted checkout, the frontend is a normal form or button that POSTs to your /checkout route; the server answers with a 303 redirect to Mollie. No Mollie script or key is needed in the browser. (Mollie Components for embedding card fields exist but are out of scope.)

resources/views/cart.blade.php (excerpt) · PHP (Laravel)

<form method="POST" action="{{ route('checkout.store') }}">
    @csrf
    <button type="submit">Pay with Mollie</button>
</form>

Payment flow

  • Customer submits the cart; server creates an order and a Mollie payment.
  • Server redirects (303) to _links.checkout.href.
  • Customer pays on Mollie's page and is sent to your redirectUrl — whatever the outcome (paid, canceled, failed).
  • Mollie calls webhookUrl with id=tr_... when the status changes.

Confirmation

The redirectUrl carries no status and anyone can open it, so it is never proof of payment. Mark an order paid only after your server has fetched the payment from the API (in the webhook handler, or on the return page as a fallback) and seen status === "paid" with the expected amount and currency.

Webhooks: fetch, compare, update once

Mollie POSTs a form-encoded body containing only id. Handle it like this:

  • Read id, fetch the payment with your API key. A forged call cannot fake a status because the status comes from Mollie's API.
  • Find the order by the stored payment ID (or metadata), check amount/currency, and apply the status only if it changed (idempotent).
  • Respond 200 — Mollie recommends 200 even for IDs you do not recognise, so attackers learn nothing.
  • Respond within 15 seconds. Non-200 responses are retried up to 10 times over about 26 hours.

webhook route · Node.js (Express)

app.post('/webhooks/mollie', async (req, res) => {
  const id = req.body.id;
  if (typeof id !== 'string' || !/^tr_\w+$/.test(id)) return res.sendStatus(200);

  let payment;
  try {
    payment = await mollie.payments.get(id); // the source of truth
  } catch (err) {
    return res.sendStatus(200); // unknown id (or other profile) — reveal nothing
  }

  const order = await orders.findByPaymentId(payment.id);
  if (!order) return res.sendStatus(200);

  const expected = (order.totalCents / 100).toFixed(2);
  if (payment.amount.value !== expected || payment.amount.currency !== order.currency) {
    await orders.flag(order.id, 'amount_mismatch');
    return res.sendStatus(200);
  }

  // Atomic compare-and-set: only one delivery can move the order to 'paid'
  const changed = await orders.updateStatusIfDifferent(order.id, payment.status);
  if (changed && payment.status === 'paid') await orders.fulfil(order.id);
  res.sendStatus(200);
});

MollieWebhookController.php (exclude the route from CSRF) · PHP (Laravel)

<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mollie\Api\Http\Requests\GetPaymentRequest;
use Mollie\Laravel\Facades\Mollie;
use Throwable;

class MollieWebhookController extends Controller
{
    public function __invoke(Request $request)
    {
        $id = (string) $request->input('id');
        if (! preg_match('/^tr_\w+$/', $id)) return response('', 200);

        try {
            $payment = Mollie::send(new GetPaymentRequest($id));
        } catch (Throwable $e) {
            return response('', 200); // unknown id: reveal nothing
        }

        DB::transaction(function () use ($payment) {
            $order = Order::where('mollie_payment_id', $payment->id)->lockForUpdate()->first();
            if (! $order || $order->status === $payment->status) return; // idempotent
            $expected = number_format($order->total_cents / 100, 2, '.', '');
            if ($payment->amount->value !== $expected) { $order->update(['flag' => 'amount_mismatch']); return; }
            $order->update(['status' => $payment->status]);
            if ($payment->isPaid()) $order->fulfil();
        });

        return response('', 200);
    }
}

shop/webhooks.py · Python (Django)

import re
from django.db import transaction
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .models import Order
from .views import mollie

@csrf_exempt  # Mollie cannot send a CSRF token; trust comes from re-fetching
@require_POST
def mollie_webhook(request):
    payment_id = request.POST.get('id', '')
    if not re.fullmatch(r'tr_\w+', payment_id):
        return HttpResponse(status=200)
    try:
        payment = mollie.payments.get(payment_id)
    except Exception:
        return HttpResponse(status=200)  # unknown id: reveal nothing

    with transaction.atomic():
        order = Order.objects.select_for_update().filter(mollie_payment_id=payment.id).first()
        if order is None or order.status == payment.status:
            return HttpResponse(status=200)  # unknown or already applied
        if payment.amount['value'] != f'{order.total_cents / 100:.2f}':
            order.flag = 'amount_mismatch'
            order.save(update_fields=['flag'])
            return HttpResponse(status=200)
        order.status = payment.status
        order.save(update_fields=['status'])
        if payment.is_paid():
            order.fulfil()
    return HttpResponse(status=200)

Security: Classic Mollie payment webhooks carry no signature — the re-fetch IS the verification. Never read a status from the webhook body or query string. Mollie also offers newer signed webhooks for some resources; their signing scheme was not verified for this guide.

Warning: In Laravel, exclude the webhook route from CSRF verification (where you configure that depends on your Laravel version), otherwise Mollie gets a 419 and keeps retrying.

Checking status on demand

Webhooks can be delayed. On the return page, or from a scheduled reconciliation job for orders stuck in open/pending, call GET /v2/payments/{id} (mollie.payments.get(id) / Mollie::send(new GetPaymentRequest($id)) / mollie.payments.get(id)) and run the same idempotent update function your webhook uses.

Refunds

POST https://api.mollie.com/v2/payments/{paymentId}/refunds with an amount object (same string format) and an optional description/metadata. Refund statuses: queued, pending, processing, refunded, failed, canceled. Record the refund ID and use an Idempotency-Key so a retried click does not refund twice.

Refund via Laravel's HTTP client (REST endpoint) · PHP (Laravel)

<?php

use Illuminate\Support\Facades\Http;

function refundOrder(\App\Models\Order $order, int $cents, string $reason): array
{
    $response = Http::withToken(env('MOLLIE_API_KEY'))
        ->withHeaders(['Idempotency-Key' => 'refund-'.$order->id.'-'.$cents])
        ->post("https://api.mollie.com/v2/payments/{$order->mollie_payment_id}/refunds", [
            'amount' => [
                'currency' => $order->currency,
                'value' => number_format($cents / 100, 2, '.', ''),
            ],
            'description' => $reason,
        ])
        ->throw();

    $refund = $response->json();
    $order->refunds()->create(['mollie_refund_id' => $refund['id'], 'status' => $refund['status']]);
    return $refund;
}

Refund with mollie-api-python · Python (Django)

def refund_order(order, cents, reason):
    payment = mollie.payments.get(order.mollie_payment_id)
    refund = payment.refunds.create({
        'amount': {'currency': order.currency, 'value': f'{cents / 100:.2f}'},
        'description': reason,
    })
    order.refunds.create(mollie_refund_id=refund.id, status=refund.status)
    return refund

Tip: In Laravel, read the key through config() in real code (env() returns null when the config is cached); env() is used here only to keep the snippet short.

Error handling

  • 401 — wrong or missing API key (or a live key in test code).
  • 422 — validation error, e.g. amount.value not a two-decimal string, or a webhookUrl Mollie cannot reach (such as localhost). The response body names the field.
  • 400 with an Idempotency-Key — same key reused with different parameters; 409 — the original request is still in progress.
  • Payments that end canceled, expired or failed should release reserved stock and let the customer retry with a new payment.

Going live

  • Complete Mollie's onboarding and enable the methods you want on the live website profile.
  • Swap MOLLIE_API_KEY to the live_... key; payment IDs from test mode do not exist in live mode.
  • Make sure the webhook route is HTTPS, publicly reachable, CSRF-exempt and fast (< 15 s).
  • Add a reconciliation job for orders stuck in open/pending.

Security checklist

  • API key only in server env vars.
  • Never trust status from the redirect or the webhook body — always fetch the payment.
  • Compare amount and currency with your order before fulfilling.
  • Prices come from your catalogue, not the browser.
  • Validate the incoming id format and return 200 for unknown IDs.

Testing

  • Start a tunnel (e.g. ngrok http 3000) and set PUBLIC_BASE_URL to its HTTPS URL.
  • Use the test_ key and create a payment; on the test checkout screen choose paid and confirm your order flips to paid once.
  • Repeat choosing failed, canceled and expired.
  • Re-POST the same id to your webhook manually (e.g. with curl) and confirm nothing is fulfilled twice.
  • POST a random id and confirm you still answer 200 and change nothing.

Replay a webhook by hand · Node.js (Express)

# Your handler must fetch the payment and change nothing the second time
curl -X POST "$PUBLIC_BASE_URL/webhooks/mollie" -d "id=tr_replace_with_test_payment_id"

Common mistakes

  • Sending amount.value as a number (10) or with one decimal ("10.0").
  • Using http://localhost/... as webhookUrl — Mollie rejects it.
  • Marking orders paid on the redirectUrl page.
  • Reading a status from the webhook request instead of fetching the payment.
  • Forgetting to parse application/x-www-form-urlencoded bodies, so req.body.id is undefined.
  • Laravel webhook blocked by CSRF (HTTP 419) or by auth middleware.

Troubleshooting

  • Webhook never arrives: confirm the URL is public HTTPS and not behind login; check the Dashboard for the payment's webhook attempts; check your tunnel is still running.
  • Webhook arrives but id is empty: missing URL-encoded body parser (Express) or reading JSON instead of request.POST (Django).
  • Order paid twice / emails sent twice: the status update is not atomic — use a row lock or a conditional update.
  • 422 on create: read the field in the error body; most often amount format or redirect/webhook URL.

Further reading

Official documentation

All links checked on 2026-11-25.

Official documentation

Sources

More payment guides