Midtrans Payment API Client for Node.js

raw JSON →
1.4.3 verified Sat Apr 25 auth: no javascript

The `midtrans-client` package is the official Node.js API client for integrating with the Midtrans Payment Gateway. It provides a structured interface for interacting with Midtrans' two primary payment products: Snap, which offers a customizable payment popup directly on the merchant's website, and Core API (VT-Direct), which facilitates backend-driven payment flows with full frontend customization. The library is currently at version 1.4.3, with recent updates addressing dependency vulnerabilities and introducing new features such as Snap Bi functionalities (Direct Debit, QRIS, VA) and webhook notification verification. Its release cadence indicates active maintenance, with focus on reliability and feature expansion. As the official client, it provides a well-supported and up-to-date integration path, adhering to Midtrans' specific API requirements and product offerings.

error ReferenceError: SnapBiApiRequestor is not defined
cause This error specifically occurred in versions prior to 1.4.2 due to an internal module resolution issue when attempting to access `SnapBiApiRequestor` for Snap Bi related functionalities.
fix
Upgrade your midtrans-client package to version 1.4.2 or higher. This particular issue was fixed in that release.
error Error: Unauthorized. Access denied for this request.
cause This typically indicates an authentication failure with the Midtrans API, most commonly due to invalid `serverKey` or `clientKey`, or using keys meant for one environment (e.g., sandbox) in another (e.g., production).
fix
Verify that your serverKey and clientKey are correct and correspond to the isProduction setting in your client initialization. Ensure you are not mixing sandbox and production keys/environments.
error Error: Cannot find module 'midtrans-client'
cause The package `midtrans-client` was either not installed in your project, or Node.js cannot resolve its path.
fix
Ensure the package is installed by running npm install midtrans-client. If you're manually including the library, verify the require() path is correct, e.g., require('./path/to/midtrans-client-nodejs/index.js').
error SyntaxError: Named export 'Snap' not found. The requested module 'midtrans-client' does not provide an export named 'Snap'
cause This error occurs when using ES module `import { Snap } from 'midtrans-client';` syntax, but the package primarily exposes its classes as properties of a default or module export using CommonJS.
fix
Refactor your import to use CommonJS require() and access Snap as a property: const midtransClient = require('midtrans-client'); let snap = new midtransClient.Snap(...);
breaking Version 1.4.2 addressed a critical breaking issue where the module could not properly locate 'SnapBiApiRequestor'. This likely caused runtime errors for users attempting to utilize Snap Bi functionalities prior to this fix.
fix Upgrade to `midtrans-client@1.4.2` or a newer version immediately to resolve the 'SnapBiApiRequestor' import problem and ensure the correct operation of Snap Bi features.
gotcha The documentation primarily showcases CommonJS `require()` syntax. Attempting to use ES module `import` statements directly might lead to 'Cannot find module' or 'Named export not found' errors in Node.js environments not configured for ESM or without appropriate transpilation.
fix Adhere to `const midtransClient = require('midtrans-client');` for maximal compatibility. If ESM is required, ensure your project's `package.json` specifies `"type": "module"` and/or use a bundler (like Webpack, Rollup) or transpiler (like Babel, TypeScript).
gotcha Misconfiguration of `isProduction` or providing incorrect `serverKey`/`clientKey` will result in authentication failures or transactions being processed in the unintended environment (sandbox instead of production, or vice-versa).
fix Always cross-reference your API keys with the chosen environment in your Midtrans Dashboard. Set `isProduction: true` for live transactions and `false` for testing/sandbox environments, matching your provided keys.
gotcha Version 1.4.3 included crucial dependency updates to address reported vulnerability warnings. Running older versions of the library may expose your application to known security vulnerabilities originating from its transitive dependencies.
fix Regularly update the `midtrans-client` package to its latest stable version to incorporate security patches and benefit from updated dependencies.
npm install midtrans-client
yarn add midtrans-client
pnpm add midtrans-client

This example demonstrates how to initialize the Midtrans Snap API client and create a new payment transaction, retrieving the transaction token and redirect URL.

const midtransClient = require('midtrans-client');

// Initialize the Snap API client with environment variables for sensitive keys
const snap = new midtransClient.Snap({
    isProduction: process.env.MIDTRANS_IS_PRODUCTION === 'true',
    serverKey: process.env.MIDTRANS_SERVER_KEY ?? '',
    clientKey: process.env.MIDTRANS_CLIENT_KEY ?? ''
});

// Define transaction parameters as per Midtrans Snap API documentation
const parameter = {
    transaction_details: {
        order_id: `ORDER-${Date.now()}`,
        gross_amount: 10000 // Example: 10,000 IDR
    },
    credit_card: {
        secure: true // Ensure 3D Secure is enabled
    },
    customer_details: {
        first_name: 'Budi',
        last_name: 'Pratama',
        email: 'budi.pratama@example.com',
        phone: '08123456789'
    }
};

// Create the transaction and handle the response
snap.createTransaction(parameter)
    .then((transaction) => {
        // The transaction object contains token and redirect_url
        let transactionToken = transaction.token;
        console.log('Snap Transaction Token:', transactionToken);
        let redirectUrl = transaction.redirect_url;
        console.log('Snap Redirect URL:', redirectUrl);
        
        // In a real application, you would send this token or redirectUrl to your frontend
        // to initiate the Snap payment popup or redirect the user.
    })
    .catch((e) => {
        console.error('Error creating Snap transaction:', e.message);
        // Handle error, e.g., log it or return an error response to the client
    });