mollie-api-typescript
v1.5.1
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage *mollie-api-typescript* API.
Readme
mollie-api-typescript
Developer-friendly & type-safe Typescript SDK specifically catered to leverage mollie-api-typescript API.
Summary
Table of Contents
- mollie-api-typescript
- SDK Installation
- Requirements
- SDK Example Usage
- Authentication
- Idempotency Key
- Add Custom User-Agent Header
- Add Profile ID and Testmode to Client
- Available Resources and Operations
- Standalone functions
- Global Parameters
- Pagination
- Retries
- Webhook Signature Validation
- Error Handling
- Server Selection
- Custom HTTP Client
- Debugging
- Development
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add mollie-api-typescriptPNPM
pnpm add mollie-api-typescriptBun
bun add mollie-api-typescriptYarn
yarn add mollie-api-typescript[!NOTE] This package is published with CommonJS and ES Modules (ESM) support.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { Client } from "mollie-api-typescript";
const client = new Client({
testmode: false,
security: {
organizationAccessToken: process.env["CLIENT_ORGANIZATION_ACCESS_TOKEN"]
?? "",
},
});
async function run() {
const result = await client.balances.list({
currency: "EUR",
from: "bal_gVMhHKqSSRYJyPsuoPNFH",
limit: 50,
idempotencyKey: "123e4567-e89b-12d3-a456-426",
});
for await (const page of result) {
console.log(page);
}
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security schemes globally:
| Name | Type | Scheme | Environment Variable |
| ------------------------- | ------ | ------------ | ---------------------------------- |
| apiKey | http | HTTP Bearer | CLIENT_API_KEY |
| organizationAccessToken | http | HTTP Bearer | CLIENT_ORGANIZATION_ACCESS_TOKEN |
| oAuth | oauth2 | OAuth2 token | CLIENT_O_AUTH |
You can set the security parameters through the security optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:
import { Client } from "mollie-api-typescript";
const client = new Client({
security: {
apiKey: process.env["CLIENT_API_KEY"] ?? "",
},
testmode: false,
});
async function run() {
const result = await client.balances.list({
currency: "EUR",
from: "bal_gVMhHKqSSRYJyPsuoPNFH",
limit: 50,
idempotencyKey: "123e4567-e89b-12d3-a456-426",
});
for await (const page of result) {
console.log(page);
}
}
run();
Idempotency Key
This SDK supports the usage of Idempotency Keys. See our documentation on how to use it.
import { Client } from "mollie-api-typescript";
let client = new Client({
security: {
apiKey: process.env["CLIENT_API_KEY"] ?? "",
}
})
let idempotencyKey = '<some-idempotency-key>';
let payload = {
description: "Description",
amount: {
currency: "EUR",
value: "5.00",
},
redirectUrl: "https://example.org/redirect",
}
let payment1 = await client.payments.create(
{
paymentRequest: payload,
idempotencyKey: idempotencyKey
}
);
let payment2 = await client.payments.create(
{
paymentRequest: payload,
idempotencyKey: idempotencyKey
}
);
console.log(`Payment with id: ${payment1.id}`);
console.log(`Payment with id: ${payment2.id}`);
console.log(payment1.id === payment2.id ? "Payments are the same" : "Payments are different");Add Custom User-Agent Header
The SDK allows you to append a custom suffix to the User-Agent header for all requests. This can be used to identify
your application or integration when interacting with the API, making it easier to track usage or debug requests. The suffix is automatically added to the default User-Agent string generated by the SDK. You can add it when creating the
client:
let client = new Client({
security: {
apiKey: process.env["CLIENT_API_KEY"] ?? "",
},
customUserAgent: "insert something here"
})Add Profile ID and Testmode to Client
The SDK allows you to define the profileId and testmode in the client. This way, you don't need to add this
information to the payload every time when using OAuth. This will not override the details provided in the individual
requests.
let client = new Client({
security: {
oAuth: process.env["CLIENT_OAUTH_KEY"] ?? "",
},
testmode: false,
profileId: "pfl_..."
})Available Resources and Operations
Accounts
- listAccounts - List business accounts
- getAccount - Get business account
- list - List transactions
- get - Get transaction
BalanceTransfers
- create - Create a Connect balance transfer
- list - List all Connect balance transfers
- get - Get a Connect balance transfer
Balances
- list - List balances
- get - Get balance
- getPrimary - Get primary balance
- getReport - Get balance report
- listTransactions - List balance transactions
Capabilities
- list - List capabilities
Captures
Chargebacks
ClientLinks
- create - Create client link
Clients
Customers
- create - Create customer
- list - List customers
- get - Get customer
- update - Update customer
- delete - Delete customer
- createPayment - Create customer payment
- listPayments - List customer payments
DelayedRouting
Invoices
Mandates
Methods
Onboarding
Organizations
- get - Get organization
- getCurrent - Get current organization
- getPartner - Get partner status
PaymentLinks
- create - Create payment link
- list - List payment links
- get - Get payment link
- update - Update payment link
- delete - Delete payment link
- listPayments - Get payment link payments
Payments
- create - Create payment
- list - List payments
- get - Get payment
- update - Update payment
- cancel - Cancel payment
- releaseAuthorization - Release payment authorization
Permissions
Profiles
- create - Create profile
- list - List profiles
- get - Get profile
- update - Update profile
- delete - Delete profile
- getCurrent - Get current profile
Refunds
- create - Create payment refund
- list - List payment refunds
- get - Get payment refund
- cancel - Cancel payment refund
- all - List all refunds
SalesInvoices
- create - Create sales invoice
- list - List sales invoices
- get - Get sales invoice
- update - Update sales invoice
- delete - Delete sales invoice
Sessions
Settlements
- list - List settlements
- get - Get settlement
- getOpen - Get open settlement
- getNext - Get next settlement
- listPayments - List settlement payments
- listCaptures - List settlement captures
- listRefunds - List settlement refunds
- listChargebacks - List settlement chargebacks
Subscriptions
- create - Create subscription
- list - List customer subscriptions
- get - Get subscription
- update - Update subscription
- cancel - Cancel subscription
- all - List all subscriptions
- listPayments - List subscription payments
Terminals
Transfers
UnmatchedCreditTransfers
- list - List unmatched credit transfers
- get - Get unmatched credit transfer
- match - Match unmatched credit transfer
- return - Return unmatched credit transfer
VerifyPayees
- create - Verify Payee
Wallets
- requestApplePaySession - Request Apple Pay payment session
WebhookEvents
- get - Get a Webhook Event
Webhooks
- create - Create a webhook
- list - List all webhooks
- update - Update a webhook
- get - Get a webhook
- delete - Delete a webhook
- test - Test a webhook
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
accountsGet- Get transactionaccountsGetAccount- Get business accountaccountsList- List transactionsaccountsListAccounts- List business accountsbalancesGet- Get balancebalancesGetPrimary- Get primary balancebalancesGetReport- Get balance reportbalancesList- List balancesbalancesListTransactions- List balance transactionsbalanceTransfersCreate- Create a Connect balance transferbalanceTransfersGet- Get a Connect balance transferbalanceTransfersList- List all Connect balance transferscapabilitiesList- List capabilitiescapturesCreate- Create capturecapturesGet- Get capturecapturesList- List captureschargebacksAll- List all chargebackschargebacksGet- Get payment chargebackchargebacksList- List payment chargebacksclientLinksCreate- Create client linkclientsGet- Get clientclientsList- List clientscustomersCreate- Create customercustomersCreatePayment- Create customer paymentcustomersDelete- Delete customercustomersGet- Get customercustomersList- List customerscustomersListPayments- List customer paymentscustomersUpdate- Update customerdelayedRoutingCreate- Create a delayed routedelayedRoutingGet- Get a delayed routedelayedRoutingList- List payment routesinvoicesGet- Get invoiceinvoicesList- List invoicesmandatesCreate- Create mandatemandatesGet- Get mandatemandatesList- List mandatesmandatesRevoke- Revoke mandatemethodsAll- List all payment methodsmethodsGet- Get payment methodmethodsList- List payment methodsonboardingGet- Get onboarding statusonboardingSubmit- Submit onboarding dataorganizationsGet- Get organizationorganizationsGetCurrent- Get current organizationorganizationsGetPartner- Get partner statuspaymentLinksCreate- Create payment linkpaymentLinksDelete- Delete payment linkpaymentLinksGet- Get payment linkpaymentLinksList- List payment linkspaymentLinksListPayments- Get payment link paymentspaymentLinksUpdate- Update payment linkpaymentsCancel- Cancel paymentpaymentsCreate- Create paymentpaymentsGet- Get paymentpaymentsList- List paymentspaymentsReleaseAuthorization- Release payment authorizationpaymentsUpdate- Update paymentpermissionsGet- Get permissionpermissionsList- List permissionsprofilesCreate- Create profileprofilesDelete- Delete profileprofilesGet- Get profileprofilesGetCurrent- Get current profileprofilesList- List profilesprofilesUpdate- Update profilerefundsAll- List all refundsrefundsCancel- Cancel payment refundrefundsCreate- Create payment refundrefundsGet- Get payment refundrefundsList- List payment refundssalesInvoicesCreate- Create sales invoicesalesInvoicesDelete- Delete sales invoicesalesInvoicesGet- Get sales invoicesalesInvoicesList- List sales invoicessalesInvoicesUpdate- Update sales invoicesessionsCreate- Create sessionsessionsGet- Get sessionsettlementsGet- Get settlementsettlementsGetNext- Get next settlementsettlementsGetOpen- Get open settlementsettlementsList- List settlementssettlementsListCaptures- List settlement capturessettlementsListChargebacks- List settlement chargebackssettlementsListPayments- List settlement paymentssettlementsListRefunds- List settlement refundssubscriptionsAll- List all subscriptionssubscriptionsCancel- Cancel subscriptionsubscriptionsCreate- Create subscriptionsubscriptionsGet- Get subscriptionsubscriptionsList- List customer subscriptionssubscriptionsListPayments- List subscription paymentssubscriptionsUpdate- Update subscriptionterminalsGet- Get terminalterminalsList- List terminalstransfersCreate- Create transfertransfersGet- Get transferunmatchedCreditTransfersGet- Get unmatched credit transferunmatchedCreditTransfersList- List unmatched credit transfersunmatchedCreditTransfersMatch- Match unmatched credit transferunmatchedCreditTransfersReturn- Return unmatched credit transferverifyPayeesCreate- Verify PayeewalletsRequestApplePaySession- Request Apple Pay payment sessionwebhookEventsGet- Get a Webhook EventwebhooksCreate- Create a webhookwebhooksDelete- Delete a webhookwebhooksGet- Get a webhookwebhooksList- List all webhookswebhooksTest- Test a webhookwebhooksUpdate- Update a webhook
Global Parameters
Certain parameters are configured globally. These parameters may be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, These global values will be used as defaults on the operations that use them. When such operations are called, there is a place in each to override the global value, if needed.
For example, you can set profileId to `` at SDK initialization and then you do not have to pass the same value on calls to operations like list. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.
Available Globals
The following global parameters are available. Global parameters can also be set via environment variable.
| Name | Type | Description | Environment |
| --------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
| profileId | string | The identifier referring to the profile you wish toretrieve the resources for.Most API credentials are linked to a single profile. In these cases the profileId must not be sent. Fororganization-level credentials such as OAuth access tokens however, the profileId parameter is required. | CLIENT_PROFILE_ID |
| testmode | boolean | Most API credentials are specifically created for either live mode or test mode. In those cases the testmode queryparameter must not be sent. For organization-level credentials such as OAuth access tokens, you can enable test mode bysetting the testmode query parameter to true.Test entities cannot be retrieved when the endpoint is set to live mode, and vice versa. | CLIENT_TESTMODE |
| customUserAgent | string | Custom user agent string to be appended to the default Mollie SDK user agent. | CLIENT_CUSTOM_USER_AGENT |
Example
import { Client } from "mollie-api-typescript";
const client = new Client({
testmode: false,
profileId: "<id>",
customUserAgent: "<value>",
security: {
organizationAccessToken: process.env["CLIENT_ORGANIZATION_ACCESS_TOKEN"]
?? "",
},
});
async function run() {
const result = await client.balances.list({
currency: "EUR",
from: "bal_gVMhHKqSSRYJyPsuoPNFH",
limit: 50,
idempotencyKey: "123e4567-e89b-12d3-a456-426",
});
for await (const page of result) {
console.log(page);
}
}
run();
Pagination
Some of the endpoints in this SDK support pagination. To use pagination, you
make your SDK calls as usual, but the returned response object will also be an
async iterable that can be consumed using the for await...of
syntax.
Here's an example of one such pagination call:
import { Client } from "mollie-api-typescript";
const client = new Client({
testmode: false,
security: {
organizationAccessToken: process.env["CLIENT_ORGANIZATION_ACCESS_TOKEN"]
?? "",
},
});
async function run() {
const result = await client.balances.list({
currency: "EUR",
from: "bal_gVMhHKqSSRYJyPsuoPNFH",
limit: 50,
idempotencyKey: "123e4567-e89b-12d3-a456-426",
});
for await (const page of result) {
console.log(page);
}
}
run();
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { Client } from "mollie-api-typescript";
const client = new Client({
testmode: false,
security: {
organizationAccessToken: process.env["CLIENT_ORGANIZATION_ACCESS_TOKEN"]
?? "",
},
});
async function run() {
const result = await client.balances.list({
currency: "EUR",
from: "bal_gVMhHKqSSRYJyPsuoPNFH",
limit: 50,
idempotencyKey: "123e4567-e89b-12d3-a456-426",
}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
for await (const page of result) {
console.log(page);
}
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { Client } from "mollie-api-typescript";
const client = new Client({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
testmode: false,
security: {
organizationAccessToken: process.env["CLIENT_ORGANIZATION_ACCESS_TOKEN"]
?? "",
},
});
async function run() {
const result = await client.balances.list({
currency: "EUR",
from: "bal_gVMhHKqSSRYJyPsuoPNFH",
limit: 50,
idempotencyKey: "123e4567-e89b-12d3-a456-426",
});
for await (const page of result) {
console.log(page);
}
}
run();
Webhook Signature Validation
The SDK includes a helper to validate Mollie webhook signatures using HMAC-SHA256.
Use it with the raw request body exactly as received by your framework and the value of the
X-Mollie-Signature header.
import {
InvalidSignatureException,
SignatureValidator,
} from "mollie-api-typescript";
const validator = new SignatureValidator(process.env["MOLLIE_WEBHOOK_SECRET"] ?? "");
async function handleWebhook(rawBody: string, signatureHeader?: string) {
try {
const isVerified = await validator.validatePayload(rawBody, signatureHeader);
if (!isVerified) {
console.log("No signature header was provided; treating it as a legacy webhook");
return;
}
console.log("Webhook signature is valid");
} catch (error) {
if (error instanceof InvalidSignatureException) {
console.log("Webhook signature is invalid");
return;
}
throw error;
}
}You can also use the static helper when you do not want to instantiate the validator yourself:
import { SignatureValidator } from "mollie-api-typescript";
const isVerified = await SignatureValidator.validate(
rawBody,
["current_secret", "previous_secret"],
signatureHeader,
);Notes:
validatePayload()returnstruewhen at least one signature matches.- It returns
falsewhen no signature is present, which lets you support legacy webhooks. - It throws
InvalidSignatureExceptionwhen a signature is present but does not match. - Header values with the
sha256=prefix are supported automatically.
Error Handling
ClientError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
| error.data$ | | Optional. Some errors may contain structured data. See Error Classes. |
Example
import { Client } from "mollie-api-typescript";
import * as errors from "mollie-api-typescript/models/errors";
const client = new Client({
testmode: false,
security: {
organizationAccessToken: process.env["CLIENT_ORGANIZATION_ACCESS_TOKEN"]
?? "",
},
});
async function run() {
try {
const result = await client.balances.list({
currency: "EUR",
from: "bal_gVMhHKqSSRYJyPsuoPNFH",
limit: 50,
idempotencyKey: "123e4567-e89b-12d3-a456-426",
});
for await (const page of result) {
console.log(page);
}
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.ClientError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.ErrorResponse) {
console.log(error.data$.status); // number
console.log(error.data$.title); // string
console.log(error.data$.detail); // string
console.log(error.data$.field); // string
console.log(error.data$.links); // models.ErrorResponseLinks
}
}
}
}
run();
Error Classes
Primary errors:
ClientError: The base class for HTTP error responses.ErrorResponse: An error response object. *
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from ClientError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
Server Selection
Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { Client } from "mollie-api-typescript";
const client = new Client({
serverURL: "https://api.mollie.com/v2",
testmode: false,
security: {
organizationAccessToken: process.env["CLIENT_ORGANIZATION_ACCESS_TOKEN"]
?? "",
},
});
async function run() {
const result = await client.balances.list({
currency: "EUR",
from: "bal_gVMhHKqSSRYJyPsuoPNFH",
limit: 50,
idempotencyKey: "123e4567-e89b-12d3-a456-426",
});
for await (const page of result) {
console.log(page);
}
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to:
- route requests through a proxy server using undici's ProxyAgent
- use the
"beforeRequest"hook to add a custom header and a timeout to requests - use the
"requestError"hook to log errors
import { Client } from "mollie-api-typescript";
import { ProxyAgent } from "undici";
import { HTTPClient } from "mollie-api-typescript/lib/http";
const dispatcher = new ProxyAgent("http://proxy.example.com:8080");
const httpClient = new HTTPClient({
// 'fetcher' takes a function that has the same signature as native 'fetch'.
fetcher: (input, init) =>
// 'dispatcher' is specific to undici and not part of the standard Fetch API.
fetch(input, { ...init, dispatcher } as RequestInit),
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new Client({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { Client } from "mollie-api-typescript";
const sdk = new Client({ debugLogger: console });You can also enable a default debug logger by setting an environment variable CLIENT_DEBUG to true.
Development
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
