Midtrans Node.js Client

repository·master·Indexed 42 days ago

https://github.com/midtrans/midtrans-nodejs-client

Official API library for integrating Midtrans Payment API into Node.js applications. Version 1.4.3 provides support for Snap, Core API (VT-Direct), Subscription API, Tokenization API for GoPay, and the Iris Disbursement API for cash management.

Tokens
17.4K
Snippets
60
Records
67
Agent score
52%

What's inside Midtrans

  1. Choose a Midtrans payment product

    master

    Midtrans offers three main integration methods depending on your frontend requirements:

    1. Snap: A customizable payment popup that appears directly on your web or app without redirection.
    2. Snap Redirect: Customers are redirected to a payment URL hosted by Midtrans.
    3. Core API (VT-Direct): A basic backend implementation where you fully customize the frontend embedded in your web or app (no redirection).
  2. Important security note: Do not use this library on the frontend

    master

    The midtrans-client package is designed strictly for backend (Node.js server) usage to facilitate secure server-to-server API calls.

    Do not use this library in a browser/frontend environment because:

    • It will likely cause CORS issues.
    • It exposes your ServerKey to the public, creating a critical security vulnerability.

    If you need to display the Snap payment page on a frontend (e.g., ReactJS):

  3. Initialize Midtrans Client (CoreApi and Snap)

    master

    To use the SDK, you must first initialize the client with your serverKey and clientKey obtained from the Midtrans Dashboard. You can pass these in the constructor or configure them later via apiConfig.

    const midtransClient = require('midtrans-client');
    
    // Initialize Core API
    let coreApi = new midtransClient.CoreApi({
        isProduction : false,
        serverKey : 'YOUR_SERVER_KEY',
        clientKey : 'YOUR_CLIENT_KEY'
    });
    
    // Initialize Snap API
    let snap = new midtransClient.Snap({
        isProduction : false,
        serverKey : 'YOUR_SERVER_KEY',
        clientKey : 'YOUR_CLIENT_KEY'
    });
  4. Initialize Snap JS on the frontend

    master

    After acquiring a transactionToken from your backend using the Snap API, use the Midtrans Snap.js library on your frontend to trigger the payment popup.

    <!-- 1. Include Snap.js with your Client Key -->
    <!-- Note: Remove '.sandbox' from URL for production -->
    <script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="<Set your ClientKey here>"></script>
    
    <script type="text/javascript">
      document.getElementById('pay-button').onclick = function() {
        // 2. Use the token acquired from your backend
        snap.pay('PUT_TRANSACTION_TOKEN_HERE', {
          onSuccess: function(result) { /* Handle success */ },
          onPending: function(result) { /* Handle pending */ },
          onError: function(result) { /* Handle error */ }
        });
      };
    </script>
  5. Initialize the Iris Disbursement API client

    master

    Iris is Midtrans' cash management solution for disbursing payments to Indonesian bank accounts. To use it, initialize the midtransClient.Iris class with your API key (passed as serverKey).

    const midtransClient = require('midtrans-client');
    
    // Create Iris instance
    let iris = new midtransClient.Iris({
            isProduction : false,
            serverKey : 'YOUR_API_KEY'
        });
  6. Configure custom HTTP client settings via Axios

    master

    The Midtrans Node.js client uses Axios under the hood. You can override default configurations such as timeouts or custom headers by accessing the httpClient.http_client.defaults object on your client instance.

    // create instance of api client
    let snap = new midtransClient.Snap({
            isProduction : false,
            serverKey : 'YOUR_SERVER_KEY',
            clientKey : 'YOUR_CLIENT_KEY'
        });
    
    // set Axios timeout config to 2500
    snap.httpClient.http_client.defaults.timeout = 2500; 
    
    // set custom HTTP header for every request from this instance
    snap.httpClient.http_client.defaults.headers.common['My-Header'] = 'my-custom-value';
  7. Handle HTTP Notifications (Webhooks)

    master

    To securely update transaction statuses in your database, do not rely on frontend callbacks. Instead, implement a webhook endpoint that listens for POST notifications from Midtrans. Use the transaction.notification(notificationJson) method to parse and validate the notification.

    const midtransClient = require('midtrans-client');
    let apiClient = new midtransClient.Snap({
        isProduction : false,
        serverKey : 'YOUR_SERVER_KEY',
        clientKey : 'YOUR_CLIENT_KEY'
    });
    
    // This should be called inside your web server's POST route handler
    apiClient.transaction.notification(notificationJson)
        .then((statusResponse) => {
            const { order_id, transaction_status, fraud_status } = statusResponse;
    
            if (transaction_status === 'capture') {
                if (fraud_status === 'challenge') {
                    // Handle challenge
                } else if (fraud_status === 'accept') {
                    // Handle success
                }
            } else if (transaction_status === 'settlement') {
                // Handle success
            } else if (transaction_status === 'pending') {
                // Handle pending
            } else if (transaction_status === 'cancel' || transaction_status === 'expire') {
                // Handle failure
            }
        });
  8. Run the Sample Express App without Docker

    master

    To run the sample application locally using Node.js and npm:

    1. Ensure you have Node.js (v9 or later) and npm installed.
    2. Navigate to the expressApp directory in your terminal.
    3. Install the required dependencies using npm install.
    4. Start the server using one of the following commands:
      • node app.js (Standard execution)
      • npm start (NPM script)
      • npm run start:dev (Development mode)
    npm install
    node app.js
  9. Override or append Midtrans notification URLs

    master

    You can customize the notification URL that Midtrans uses to send transaction updates by adding specific HTTP headers to your client's default headers.

    • To override the notification URL, use the X-Override-Notification header.
    • To append a notification URL, use the X-Append-Notification header.
    // create instance of api client
    let snap = new midtransClient.Snap({
            isProduction : false,
            serverKey : 'YOUR_SERVER_KEY',
            clientKey : 'YOUR_CLIENT_KEY'
    });
    
    // set custom HTTP header that will be used by Midtrans API to override notification url:
    snap.httpClient.http_client.defaults.headers.common['X-Override-Notification'] = 'https://mysite.com/midtrans-notification-handler';
    
    // or append notification:
    snap.httpClient.http_client.defaults.headers.common['X-Append-Notification'] = 'https://mysite.com/midtrans-notification-handler';
  10. Handle Midtrans API errors and exceptions

    master

    When calling methods that trigger Midtrans API requests (e.g., core.charge(...) or snap.createTransaction(...)), the client may throw a MidtransError object. You should catch these errors to access specific details for your error handling logic. The error object contains:

    • message: A basic error message string.
    • httpStatusCode: The HTTP status code returned by the API (e.g., 400, 401).
    • ApiResponse: The JSON object representing the API response.
    • rawHttpClientData: The raw Axios response object.
    snap.createTransaction(parameter)
          .then((res)=>{
          })
          .catch((e)=>{
            e.message // basic error message string
            e.httpStatusCode // HTTP status code e.g: 400, 401, etc.
            e.ApiResponse // JSON of the API response 
            e.rawHttpClientData // raw Axios response object
          })
  11. Use Axios interceptors with Midtrans client

    master

    You can apply Axios interceptors to your Midtrans client instance to manipulate HTTP requests or responses (e.g., modifying headers or request bodies) before they are sent to the Midtrans API.

    // Add a request interceptor
    snap.httpClient.http_client.interceptors.request.use(function (config) {
        // Do something before request is sent
        return config;
      }, function (error) {
        // Do something with request error
        return Promise.reject(error);
      });