Mollie API Node.js SDK

repository·master·Indexed 43 days ago

https://github.com/mollie/mollie-api-node

Official Node.js SDK for the Mollie API (v4.6.0), enabling developers to accept payments, manage refunds, and handle webhooks. Supports Node.js, Bun, Deno, and Cloudflare Workers. Features include async iterators for pagination, OAuth access token support, and comprehensive migration guides from v1.x.x through v4.0.0.

Tokens
14.4K
Snippets
42
Records
72
Agent score
52%

What's inside Mollie

  1. Migrate from v3.x.x to v4.0.0

    master

    When upgrading to v4.0.0, several breaking changes must be addressed:

    Node.js Requirement

    Node.js 14+ is officially supported.

    API Changes

    • Remove withParent: Instead of using .withParent(parent), pass the parent ID directly in the options object to the iteration method.
    • Camel Case Properties: Snake case properties (e.g., payments_refunds) have been removed. Use camel case (e.g., paymentRefunds) instead.
    • Endpoint Aliases: Use specific action names. For example, use mollieClient.payments.cancel instead of mollieClient.payments.delete.
    • Helper Functions: Predictable helper functions on models (like .isOpen()) have been removed. Use direct property access and enums (e.g., if (payment.status == PaymentStatus.open)).
    • ApiError Properties: Access error details via properties instead of methods. Use error.message, error.field, and error.statusCode instead of getMessage(), getField(), and getStatusCode().
    • metadata Type: The metadata property is now typed as unknown. You must check its type at runtime or use as any to bypass type checking.
    • Pagination: The count property on pages has been removed; use .length instead.
    • List Return Types: Some list functions now return plain arrays (e.g., mollieClient.methods.list), while others return iterators (e.g., customer.getPayments()).
    • toPlainObject: This method has been removed.

    Deprecations and Removals

    • Giropay and SOFORT: These have been removed from the client.
    • Axios Options: The client no longer uses Axios. Options like adapter, proxy, socketPath, and timeout passed to createMollieClient are ignored.

    Network Errors

    Note that network error message strings may differ from previous versions. Update error handling that relies on exact message matching.

    - const payments = mollieClient.customerPayments.withParent(customer).iterate();
    + const payments = mollieClient.customerPayments.iterate({ customerId: customer.id });
      for await (const payment of payments) {
        …
      }
  2. Migrate from v1.x.x to v2.0.0

    master

    Upgrading from v1.x.x to v2.0.0 involves significant changes due to the transition to the v2 Mollie API.

    Package Renaming

    The NPM package was renamed to @mollie/api-client.

    Initialization

    The client is now initialized via a factory function rather than a constructor:

    const mollie = require('@mollie/api-client')({
      apiKey: 'YOUR_API_KEY',
    });

    Breaking Changes

    • Callback Signature: Callbacks changed from (response) => {} to (error, response) => {}.
    • Amount Format: Amounts must now be passed as an object containing both currency and value (e.g., { currency: 'EUR', value: '10.00' }).
    • Date Formatting: Fields like createdAt now follow strict ISO-8601 formatting.
    • Status Names: The status cancelled was renamed to canceled. Statuses paidout, refunded, and charged_back were removed.
    • Recurring Payments: recurringType was renamed to sequenceType.
    • Pagination: Switched to cursor-based pagination using limit and from instead of offsets.
    • withParent Deprecation: Use parent IDs in parameters instead of the .withParent() method.
    // New amount format
    mollie.payments.create({
      amount: {
        "currency": "EUR",
        "value": "10.00"
      }
    });
    
    // New pagination pattern
    mollie.payments
      .all({
        limit: 15,
        from: 'tr_8WhJKGmgBy'
      })
      .then((payments) => {
        // Returns the list of 15 payments, starting with payment `tr_8WhJKGmgBy`
      });
  3. Migrate from v2.x.x to v3.0.0

    master

    When upgrading to v3.0.0, the primary change is the transition to a named factory function for client initialization.

    CommonJS Initialization

    Use createMollieClient from the package:

    const { createMollieClient } = require('@mollie/api-client');
    const mollieClient = createMollieClient({ apiKey: 'YOUR_API_KEY' });

    ESM/JavaScript Modules Initialization

    import { createMollieClient, PaymentMethod } from '@mollie/api-client';
    
    const mollieClient = createMollieClient({
      apiKey: 'YOUR_API_KEY',
    });
    const { createMollieClient, PaymentMethod } = require('@mollie/api-client');
    
    const mollieClient = createMollieClient({
      apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM',
    });
    
    mollieClient.payments.create({
      amount: {
        currency: 'EUR',
        value: '10.00',
      },
      description: 'Order #478',
      method: PaymentMethod.ideal
    });
  4. Initialize the Mollie client

    master

    To use the library, create a client instance using createMollieClient. You can use either ES Modules or CommonJS syntax. You must provide an apiKey for authentication.

    import createMollieClient from '@mollie/api-client';
    
    const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' });
  5. Access payment-specific details via the details field

    master

    The details property in PaymentData provides specialized information depending on the method used. Common detail structures include:

    • CreditCardDetails: Includes cardHolder, cardNumber (last 4 digits), cardFingerprint, cardLabel, and failureReason for failed payments.
    • IdealDetails: Includes consumerName, consumerAccount (IBAN), and consumerBic.
    • PayPalDetails: Includes consumerName, consumerAccount (email), paypalReference, and sellerProtection status.
    • BankTransferDetails: Includes bankName, bankAccount (IBAN), bankBic, and transferReference.
    • BancontactDetails: Includes consumerName, consumerAccount, and qrCode for mobile scanning.
  6. Understand the PaymentData structure

    master

    The PaymentData interface represents the core data object for a Mollie payment. It contains information about the payment's status, amount, method, and lifecycle timestamps.

    Key properties include:

    • mode: Indicates if the payment is live or test.
    • status: The current state of the payment (e.g., authorized, paid, canceled).
    • amount: An object containing the currency and value.
    • method: The payment method used (e.g., ideal, creditcard, paypal).
    • statusReason: Details about why a payment reached a specific status (primarily for point-of-sale).
    • _links: A collection of URLs for interacting with the payment (e.g., checkout, dashboard, refunds).
    • details: A polymorphic object containing method-specific information (e.g., CreditCardDetails, IdealDetails).
  7. How to embed related resources in Captures

    master

    When fetching capture data, you can embed related resources using the embed query parameter. Use the CaptureEmbed enum to specify which resources to include.

    Note: The CaptureInclude enum is deprecated. Use CaptureEmbed instead. Passing include to the Captures API has no effect.

    // Use CaptureEmbed to include related resources like the payment
    // Example usage in an API call (conceptual):
    // client.captures.get('cap_123', { embed: CaptureEmbed.payment });
  8. Run the client in a browser environment

    master

    By default, the client throws an error if it detects a browser-like environment to prevent accidental credential exposure. If you have appropriate mitigations in place (such as using a short-lived, narrowly-scoped access token), you can bypass this check using the dangerouslyAllowBrowser: true option.

    const mollieClient = createMollieClient({ apiKey: 'test_...', dangerouslyAllowBrowser: true });
  9. Paginate through API results

    master

    The Mollie API returns results in pages. To implement manual pagination, use the .page() method. This method returns a subset of objects and provides a nextPageCursor which is the ID of the first object on the next page. You can use this cursor in the from parameter of the subsequent call.

    // Retrieve the first 15 payments.
    const payments = mollieClient.payments.page({ limit: 15 });
    
    // payments.nextPageCursor is the cursor: the ID of the first payment on the next page.
    
    // Retrieve the second 15 payments (using the cursor from the previous page).
    const nextPayments = mollieClient.payments.page({ limit: 15, from: 'tr_8WhJKGmgBy' });
  10. Create a new payment

    master

    Use mollieClient.payments.create() to initiate a new payment. You must provide the amount (with value and currency), a description, a redirectUrl (where the customer is sent after payment), and a webhookUrl (where Mollie sends status updates).

    const payment = await mollieClient.payments.create({
      amount: {
        value:    '10.00',
        currency: 'EUR'
      },
      description: 'My first API payment',
      redirectUrl: 'https://yourwebshop.example.org/order/123456',
      webhookUrl:  'https://yourwebshop.example.org/webhook'
    });
    
    // Forward the customer to payment.getCheckoutUrl().