Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Theme
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Create API Key
Add Docs
Mollie API Client
https://github.com/mollie/mollie-api-node
Admin
Official Mollie API client for Node.js that enables developers to accept online and mobile payments,
...
Tokens:
13,190
Snippets:
84
Trust Score:
9.9
Update:
1 month ago
Context
Skills
Chat
Benchmark
83.6
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Mollie API Client The Mollie API client for Node.js is the official JavaScript/TypeScript library for integrating with Mollie's payment platform. It provides a comprehensive wrapper around the Mollie REST API, enabling developers to accept online and mobile payments through numerous payment methods including credit cards, iDEAL, PayPal, Klarna, Apple Pay, SEPA Direct Debit, and many more. The client is designed exclusively for server-side Node.js applications to keep API keys secure. The library offers full TypeScript support with strongly-typed interfaces for all API resources including payments, orders, customers, subscriptions, refunds, and settlements. It features both Promise-based and callback-style APIs, automatic pagination with iterator support, and includes helper methods on response objects for common operations like checking payment status. The client handles authentication, request signing, and response transformation automatically. ## Client Initialization Create a Mollie client instance with your API key to start making API calls. The client validates that it's running in a Node.js environment to prevent accidental exposure of API keys in frontend applications. ```typescript import createMollieClient from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // CommonJS style const { createMollieClient } = require('@mollie/api-client'); const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); ``` ## Payments API - Create Payment Create a new payment to initiate the checkout process. After creation, redirect your customer to the checkout URL to complete the payment. ```typescript import createMollieClient, { Payment } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const payment: Payment = await mollieClient.payments.create({ amount: { currency: 'EUR', value: '10.00', // Must be a string with correct decimal places }, description: 'My first payment', redirectUrl: 'https://webshop.example.org/order/12345/', webhookUrl: 'https://webshop.example.org/payments/webhook/', metadata: { order_id: '12345', }, }); // Redirect customer to complete payment const checkoutUrl = payment.getCheckoutUrl(); console.log(`Redirect to: ${checkoutUrl}`); ``` ## Payments API - Get Payment Retrieve a payment by its ID and check its status. The payment object includes helper methods like `isPaid()`, `isOpen()`, `isCanceled()`, and `isExpired()`. ```typescript import createMollieClient, { Payment, PaymentStatus } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const payment: Payment = await mollieClient.payments.get('tr_Eq8xzWUPA4'); if (payment.isPaid()) { console.log('Payment completed successfully'); } else if (payment.status === PaymentStatus.open) { console.log('Payment is still pending'); } else { console.log(`Payment status: ${payment.status}`); } ``` ## Payments API - List Payments with Pagination Retrieve payments with pagination support. Use `page()` for manual pagination or `iterate()` for automatic iteration through all results. ```typescript import createMollieClient from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // Page-based pagination const payments = await mollieClient.payments.page({ limit: 15 }); console.log(`Retrieved ${payments.length} payments`); // Use payments.nextPageCursor for the next page // Retrieve next page using cursor const nextPage = await mollieClient.payments.page({ limit: 15, from: 'tr_8WhJKGmgBy' }); // Automatic iteration through all payments for await (const payment of mollieClient.payments.iterate()) { console.log(`Payment ${payment.id}: ${payment.status}`); } // Filter while iterating const largePayments = mollieClient.payments.iterate() .filter(({ amount }) => amount.currency === 'EUR' && parseFloat(amount.value) > 100) .take(10); for await (const payment of largePayments) { console.log(`Large payment: ${payment.id} - ${payment.amount.value} EUR`); } ``` ## Payments API - Cancel Payment Cancel a payment that is still open. Check the `isCancelable` property before attempting cancellation. ```typescript import createMollieClient, { Payment } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const payment: Payment = await mollieClient.payments.cancel('tr_WDqYK6vllg'); console.log(`Payment ${payment.id} canceled, status: ${payment.status}`); ``` ## Customers API - Create Customer Create a customer record to enable recurring payments and manage payment history through the Mollie Dashboard. ```typescript import createMollieClient, { Customer } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const customer: Customer = await mollieClient.customers.create({ name: 'John Doe', email: 'john.doe@example.org', locale: 'en_US', metadata: { userId: '12345' }, }); console.log(`Created customer: ${customer.id}`); ``` ## Customers API - Manage Customers Retrieve, update, list, and delete customers. ```typescript import createMollieClient, { Customer } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // Get a customer const customer = await mollieClient.customers.get('cst_pzhEvnttJ2'); // Update a customer const updated = await mollieClient.customers.update('cst_pzhEvnttJ2', { name: 'Jane Doe', email: 'jane.doe@example.org', }); // List all customers const customers = await mollieClient.customers.page({ limit: 50 }); // Delete a customer (cancels all mandates and subscriptions) await mollieClient.customers.delete('cst_pzhEvnttJ2'); ``` ## Recurring Payments - First Payment Create a first payment to set up recurring billing. This establishes a mandate for future charges. ```typescript import createMollieClient, { Payment, SequenceType } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // Create a "first" payment to establish recurring mandate const firstPayment: Payment = await mollieClient.customerPayments.create({ amount: { value: '10.00', currency: 'EUR' }, description: 'First payment for subscription', redirectUrl: 'https://example.org/redirect', webhookUrl: 'https://example.org/webhook', customerId: 'cst_pzhEvnttJ2', sequenceType: SequenceType.first, }); console.log(`First payment created: ${firstPayment.id}`); ``` ## Recurring Payments - Subsequent Payment Create a recurring payment that charges a customer without requiring them to complete checkout. ```typescript import createMollieClient, { Payment, SequenceType } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const recurringPayment: Payment = await mollieClient.customerPayments.create({ amount: { value: '10.00', currency: 'EUR' }, description: 'Recurring payment', redirectUrl: 'https://example.org/redirect', webhookUrl: 'https://example.org/webhook', metadata: { orderId: 'Order #23' }, customerId: 'cst_pzhEvnttJ2', sequenceType: SequenceType.recurring, }); console.log(`Recurring payment created: ${recurringPayment.id}`); ``` ## Mandates API - Create Mandate Create a mandate for SEPA Direct Debit to enable recurring payments without initial customer interaction. ```typescript import createMollieClient, { Mandate, MandateMethod } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const mandate: Mandate = await mollieClient.customerMandates.create({ customerId: 'cst_pzhEvnttJ2', method: MandateMethod.directdebit, consumerName: 'John Doe', consumerAccount: 'NL55INGB0000000000', consumerBic: 'INGBNL2A', signatureDate: '2018-05-07', mandateReference: 'YOUR-COMPANY-MD13804', }); console.log(`Mandate created: ${mandate.id}, status: ${mandate.status}`); ``` ## Subscriptions API - Create Subscription Create a subscription for automatic recurring billing at specified intervals. ```typescript import createMollieClient, { Subscription } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const subscription: Subscription = await mollieClient.customerSubscriptions.create({ customerId: 'cst_pzhEvnttJ2', amount: { value: '24.00', currency: 'EUR' }, times: 4, // Number of charges (omit for unlimited) interval: '3 months', // Options: "X days", "X weeks", "X months" description: 'Quarterly payment', webhookUrl: 'https://webshop.example.org/payments/webhook/', startDate: '2024-01-01', // Optional: defaults to now }); console.log(`Subscription created: ${subscription.id}`); ``` ## Orders API - Create Order Create an order with line items for pay-after-delivery methods like Klarna. Required for Klarna Pay Later, Klarna Slice It, in3, and vouchers. ```typescript import createMollieClient, { Order, Locale, PaymentMethod, OrderLineType } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const order: Order = await mollieClient.orders.create({ amount: { value: '1027.99', currency: 'EUR' }, billingAddress: { organizationName: 'Mollie B.V.', streetAndNumber: 'Keizersgracht 313', city: 'Amsterdam', region: 'Noord-Holland', postalCode: '1234AB', country: 'NL', title: 'Dhr.', givenName: 'Piet', familyName: 'Mondriaan', email: 'piet@mondriaan.com', phone: '+31309202070', }, shippingAddress: { streetAndNumber: 'Prinsengracht 313', city: 'Haarlem', postalCode: '5678AB', country: 'NL', givenName: 'Chuck', familyName: 'Norris', email: 'norris@chucknorrisfacts.net', }, metadata: { order_id: '1337', description: 'Lego cars' }, consumerDateOfBirth: '1958-01-31', locale: Locale.nl_NL, orderNumber: '1337', redirectUrl: 'https://example.org/redirect', webhookUrl: 'https://example.org/webhook', method: PaymentMethod.klarnapaylater, lines: [ { type: OrderLineType.physical, sku: '5702016116977', name: 'LEGO 42083 Bugatti Chiron', productUrl: 'https://shop.lego.com/nl-NL/Bugatti-Chiron-42083', imageUrl: 'https://sh-s7-live-s.legocdn.com/is/image//LEGO/42083_alt1', quantity: 2, vatRate: '21.00', unitPrice: { currency: 'EUR', value: '399.00' }, totalAmount: { currency: 'EUR', value: '698.00' }, discountAmount: { currency: 'EUR', value: '100.00' }, vatAmount: { currency: 'EUR', value: '121.14' }, }, { type: OrderLineType.physical, sku: '5702015594028', name: 'LEGO 42056 Porsche 911 GT3 RS', quantity: 1, vatRate: '21.00', unitPrice: { currency: 'EUR', value: '329.99' }, totalAmount: { currency: 'EUR', value: '329.99' }, vatAmount: { currency: 'EUR', value: '57.27' }, }, ], }); console.log(`Order created: ${order.id}`); ``` ## Refunds API - Create Payment Refund Refund a payment, either partially or fully. ```typescript import createMollieClient, { Refund } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // Full or partial payment refund const paymentRefund: Refund = await mollieClient.paymentRefunds.create({ paymentId: 'tr_WDqYK6vllg', amount: { value: '5.95', currency: 'EUR', }, description: 'Refund for returned item', }); console.log(`Refund created: ${paymentRefund.id}, status: ${paymentRefund.status}`); ``` ## Refunds API - Create Order Refund Refund specific order lines from an order. ```typescript import createMollieClient, { Refund } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const orderRefund: Refund = await mollieClient.orderRefunds.create({ orderId: 'ord_stTC2WHAuS', lines: [ { id: 'odl_dgtxyl', quantity: 1, }, ], description: 'Required quantity not in stock, refunding one item.', }); console.log(`Order refund created: ${orderRefund.id}`); ``` ## Methods API - List Payment Methods Retrieve available payment methods for your account, optionally filtered by amount and currency. ```typescript import createMollieClient, { List, Method } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // List all active payment methods const methods: List<Method> = await mollieClient.methods.list(); methods.forEach(method => { console.log(`${method.id}: ${method.description}`); console.log(` Image: ${method.image.svg}`); }); // List methods available for a specific amount const filteredMethods = await mollieClient.methods.list({ amount: { value: '100.00', currency: 'EUR' }, }); ``` ## Methods API - Get Method with Issuers Retrieve a specific payment method with its issuers (e.g., banks for iDEAL). ```typescript import createMollieClient, { Method, MethodInclude } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const ideal: Method = await mollieClient.methods.get('ideal', { include: MethodInclude.issuers, }); console.log(`Method: ${ideal.description}`); if (ideal.issuers) { ideal.issuers.forEach(issuer => { console.log(` Issuer: ${issuer.name} (${issuer.id})`); }); } ``` ## Chargebacks API - List Chargebacks Retrieve chargebacks for your account or a specific payment. ```typescript import createMollieClient, { List, Chargeback } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // List all chargebacks const chargebacks: List<Chargeback> = await mollieClient.chargebacks.page(); chargebacks.forEach(chargeback => { console.log(`Chargeback ${chargeback.id}: ${chargeback.amount.value} ${chargeback.amount.currency}`); }); // List chargebacks for a specific payment const paymentChargebacks = await mollieClient.paymentChargebacks.page({ paymentId: 'tr_WDqYK6vllg', }); ``` ## Settlements API - Get Settlements Retrieve settlement details to see which payments were paid out and when. ```typescript import createMollieClient from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // Get a specific settlement const settlement = await mollieClient.settlements.get('stl_jDk30akdN'); // Get the next scheduled settlement const nextSettlement = await mollieClient.settlements.getNext(); // Get the open (current) balance const openSettlement = await mollieClient.settlements.getOpen(); console.log(`Open balance: ${openSettlement.amount.value} ${openSettlement.amount.currency}`); ``` ## Payment Links API - Create Payment Link Create a shareable payment link that doesn't expire. Useful for invoices and payment requests sent via email. ```typescript import createMollieClient from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const paymentLink = await mollieClient.paymentLinks.create({ amount: { currency: 'EUR', value: '25.00' }, description: 'Invoice #12345', redirectUrl: 'https://example.org/thank-you', webhookUrl: 'https://example.org/webhook', expiresAt: '2024-12-31T23:59:59+00:00', // Optional expiration }); console.log(`Payment link: ${paymentLink.getPaymentUrl()}`); ``` ## Terminals API - List Terminals Retrieve point-of-sale terminals linked to your account. ```typescript import createMollieClient from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); const terminals = await mollieClient.terminals.page({}); terminals.forEach(terminal => { console.log(`Terminal ${terminal.id}: ${terminal.description}`); console.log(` Status: ${terminal.status}`); }); ``` ## Webhook Handling - Express.js Integration Handle Mollie webhooks to receive payment status updates in real-time. ```javascript const express = require('express'); const { createMollieClient } = require('@mollie/api-client'); const app = express(); app.use(express.urlencoded({ extended: true })); const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // Webhook endpoint receives payment ID via POST app.post('/webhook', async (req, res) => { try { const payment = await mollieClient.payments.get(req.body.id); if (payment.isPaid()) { // Payment successful - fulfill the order console.log(`Payment ${payment.id} completed`); // Update order status in your database } else if (!payment.isOpen()) { // Payment failed or was canceled console.log(`Payment ${payment.id} not completed: ${payment.status}`); } res.status(200).send(payment.status); } catch (error) { console.error('Webhook error:', error); res.status(500).send('Error processing webhook'); } }); app.listen(8000, () => console.log('Webhook server listening on port 8000')); ``` ## Express.js - Complete Payment Flow Full example showing payment creation and redirect handling with Express.js. ```javascript const express = require('express'); const { createMollieClient } = require('@mollie/api-client'); const app = express(); const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // Create a new payment and redirect customer app.get('/pay', async (req, res) => { try { const orderId = new Date().getTime(); const payment = await mollieClient.payments.create({ amount: { value: '10.00', currency: 'EUR' }, description: `Order #${orderId}`, redirectUrl: `https://example.org/order/${orderId}/complete`, webhookUrl: `https://example.org/webhook?orderId=${orderId}`, metadata: { orderId }, }); // Redirect customer to Mollie checkout res.redirect(payment.getPaymentUrl()); } catch (error) { console.error('Payment creation failed:', error); res.status(500).send('Could not create payment'); } }); // Handle return from payment app.get('/order/:orderId/complete', async (req, res) => { // Note: Don't rely on this for order fulfillment - use webhooks res.send('Thank you for your order! We will process it shortly.'); }); app.listen(8000); ``` ## OAuth API - Token Management Exchange authorization codes for access tokens and manage OAuth tokens for Mollie Connect integrations. ```typescript import createMollieClient, { OAuthGrantType } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); // Exchange authorization code for tokens const tokens = await mollieClient.oauth.create({ clientId: 'app_xxx', clientSecret: 'secret_xxx', grant_type: OAuthGrantType.authorization_code, code: 'auth_code_from_redirect', redirect_uri: 'https://example.org/oauth/callback', }); console.log(`Access token: ${tokens.access_token}`); console.log(`Refresh token: ${tokens.refresh_token}`); // Refresh an expired access token const refreshedTokens = await mollieClient.oauth.create({ clientId: 'app_xxx', clientSecret: 'secret_xxx', grant_type: OAuthGrantType.refresh_token, refresh_token: tokens.refresh_token, }); // Revoke a token await mollieClient.oauth.revoke({ clientId: 'app_xxx', clientSecret: 'secret_xxx', token: tokens.access_token, token_type_hint: 'access_token', }); ``` ## Error Handling Handle API errors with the MollieApiError class which provides detailed error information. ```typescript import createMollieClient, { MollieApiError } from '@mollie/api-client'; const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); try { const payment = await mollieClient.payments.create({ amount: { value: '10.00', currency: 'EUR' }, description: 'Test payment', redirectUrl: 'https://example.org/redirect', }); } catch (error) { if (error instanceof MollieApiError) { console.error(`API Error: ${error.message}`); console.error(`Status code: ${error.statusCode}`); console.error(`Field: ${error.field}`); // Which field caused the error } else { console.error('Unexpected error:', error); } } ``` ## Summary The Mollie API client for Node.js provides a complete solution for integrating payment processing into e-commerce applications, subscription services, and marketplace platforms. The primary use cases include one-time payments for online purchases, recurring billing for subscriptions, order management for pay-after-delivery methods like Klarna, and multi-party payments through Mollie Connect. The library supports all major European payment methods and provides specialized APIs for managing customers, mandates, refunds, settlements, and point-of-sale terminals. Integration follows a straightforward pattern: initialize the client with your API key, create payments or orders, redirect customers to the checkout URL, and handle status updates via webhooks. For recurring payments, create a customer, capture a first payment to establish a mandate, then charge subsequent payments without customer interaction. The library's TypeScript support, Promise-based API, and automatic pagination make it well-suited for modern Node.js applications, while callback support maintains compatibility with legacy codebases. All payment processing should occur server-side to keep API keys secure.