Midtrans ❤️ Node JS!
This is the Official Node JS API client/library for Midtrans Payment API. Visit https://midtrans.com. More information about the product and see documentation at http://docs.midtrans.com for more technical details.
npm install --save midtrans-client
If you are not using NPM, you can clone or download this repository.
Then require from index.js
file.
let midtransClient = require('./midtrans-client-nodejs/index.js');
We have 2 different products of payment that you can use:
- Snap - Customizable payment popup will appear on your web/app (no redirection). doc ref
- Snap Redirect - Customer need to be redirected to payment url hosted by midtrans. doc ref
- Core API (VT-Direct) - Basic backend implementation, you can customize the frontend embedded on your web/app as you like (no redirection). doc ref
Choose one that you think best for your unique needs.
Get your client key and server key from Midtrans Dashboard
Create API client object
const midtransClient = require('midtrans-client');
// Create Core API instance
let coreApi = new midtransClient.CoreApi({
isProduction : false,
serverKey : 'YOUR_SERVER_KEY',
clientKey : 'YOUR_CLIENT_KEY'
});
const midtransClient = require('midtrans-client');
// Create Snap API instance
let snap = new midtransClient.Snap({
isProduction : false,
serverKey : 'YOUR_SERVER_KEY',
clientKey : 'YOUR_CLIENT_KEY'
});
You can also re-set config using Snap.apiConfig.set( ... )
example:
const midtransClient = require('midtrans-client');
// Create Snap API instance, empty config
let snap = new midtransClient.Snap();
snap.apiConfig.set({
isProduction : false,
serverKey : 'YOUR_SERVER_KEY',
clientKey : 'YOUR_CLIENT_KEY'
});
// You don't have to re-set using all the options,
// i.e. set serverKey only
snap.apiConfig.set({serverKey : 'YOUR_SERVER_KEY'});
You can also set config directly from attribute
const midtransClient = require('midtrans-client');
// Create Snap API instance, empty config
let snap = new midtransClient.Snap();
snap.apiConfig.isProduction = false;
snap.apiConfig.serverKey = 'YOUR_SERVER_KEY';
snap.apiConfig.clientKey = 'YOUR_CLIENT_KEY';
You can see Snap example here.
Available methods for Snap
class
// return Snap API /transaction response as Promise of Object
createTransaction(parameter)
// return Snap API /transaction token as Promise of String
createTransactionToken(parameter)
// return Snap API /transaction redirect_url as Promise of String
createTransactionRedirectUrl(parameter)
parameter
is Object or String of JSON of SNAP Parameter
const midtransClient = require('midtrans-client');
// Create Snap API instance
let snap = new midtransClient.Snap({
isProduction : false,
serverKey : 'YOUR_SERVER_KEY',
clientKey : 'YOUR_CLIENT_KEY'
});
let parameter = {
"transaction_details": {
"order_id": "test-transaction-123",
"gross_amount": 200000
}, "credit_card":{
"secure" : true
}
};
snap.createTransaction(parameter)
.then((transaction)=>{
// transaction token
let transactionToken = transaction.token;
console.log('transactionToken:',transactionToken);
})
// alternative way to create transactionToken
// snap.createTransactionToken(parameter)
// .then((transactionToken)=>{
// console.log('transactionToken:',transactionToken);
// })
On frontend / html:
Replace PUT_TRANSACTION_TOKEN_HERE
with transactionToken
acquired above
<html>
<body>
<button id="pay-button">Pay!</button>
<pre><div id="result-json">JSON result will appear here after payment:<br></div></pre>
<!-- TODO: Remove ".sandbox" from script src URL for production environment. Also input your client key in "data-client-key" -->
<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(){
// SnapToken acquired from previous step
snap.pay('PUT_TRANSACTION_TOKEN_HERE', {
// Optional
onSuccess: function(result){
/* You may add your own js here, this is just example */ document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
},
// Optional
onPending: function(result){
/* You may add your own js here, this is just example */ document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
},
// Optional
onError: function(result){
/* You may add your own js here, this is just example */ document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
}
});
};
</script>
</body>
</html>
Also available as examples here.
const midtransClient = require('midtrans-client');
// Create Snap API instance
let snap = new midtransClient.Snap({
isProduction : false,
serverKey : 'YOUR_SERVER_KEY',
clientKey : 'YOUR_CLIENT_KEY'
});
let parameter = {
"transaction_details": {
"order_id": "test-transaction-123",
"gross_amount": 200000
}, "credit_card":{
"secure" : true
}
};
snap.createTransaction(parameter)
.then((transaction)=>{
// transaction redirect_url
let redirectUrl = transaction.redirect_url;
console.log('redirectUrl:',redirectUrl);
})
// alternative way to create redirectUrl
// snap.createTransactionRedirectUrl(parameter)
// .then((redirectUrl)=>{
// console.log('redirectUrl:',redirectUrl);
// })
You can see some Core API examples here.
Available methods for CoreApi
class
/**
* Do `/charge` API request to Core API
* @param {Object} parameter - object of Core API JSON body as parameter, will be converted to JSON (more params detail refer to: https://api-docs.midtrans.com)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
charge(parameter={})
/**
* Do `/capture` API request to Core API
* @param {Object} parameter - object of Core API JSON body as parameter, will be converted to JSON (more params detail refer to: https://api-docs.midtrans.com)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
capture(parameter={})
/**
* Do `/card/register` API request to Core API
* @param {Object} parameter - object of Core API JSON body as parameter, will be converted to JSON (more params detail refer to: https://api-docs.midtrans.com)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
cardRegister(parameter={})
/**
* Do `/token` API request to Core API
* @param {Object} parameter - object of Core API JSON body as parameter, will be converted to JSON (more params detail refer to: https://api-docs.midtrans.com)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
cardToken(parameter={})
/**
* Do `/point_inquiry/<tokenId>` API request to Core API
* @param {String} tokenId - tokenId of credit card (more params detail refer to: https://api-docs.midtrans.com)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
cardPointInquiry(tokenId)
parameter
is Object or String of JSON of Core API Parameter
Get token should be handled on Frontend please refer to API docs
const midtransClient = require('midtrans-client');
// Create Core API instance
let core = new midtransClient.CoreApi({
isProduction : false,
serverKey : 'YOUR_SERVER_KEY',
clientKey : 'YOUR_CLIENT_KEY'
});
let parameter = {
"payment_type": "credit_card",
"transaction_details": {
"gross_amount": 12145,
"order_id": "test-transaction-54321",
},
"credit_card":{
"token_id": 'CREDIT_CARD_TOKEN' // change with your card token
}
};
// charge transaction
core.charge(parameter)
.then((chargeResponse)=>{
console.log('chargeResponse:');
console.log(chargeResponse);
});
Create separated web endpoint (notification url) to receive HTTP POST notification callback/webhook. HTTP notification will be sent whenever transaction status is changed. Example also available here
const midtransClient = require('midtrans-client');
// Create Core API / Snap instance (both have shared `transactions` methods)
let apiClient = new midtransClient.Snap({
isProduction : false,
serverKey : 'YOUR_SERVER_KEY',
clientKey : 'YOUR_CLIENT_KEY'
});
apiClient.transaction.notification(notificationJson)
.then((statusResponse)=>{
let orderId = statusResponse.order_id;
let transactionStatus = statusResponse.transaction_status;
let fraudStatus = statusResponse.fraud_status;
console.log(`Transaction notification received. Order ID: ${orderId}. Transaction status: ${transactionStatus}. Fraud status: ${fraudStatus}`);
// Sample transactionStatus handling logic
if (transactionStatus == 'capture'){
if (fraudStatus == 'challenge'){
// TODO set transaction status on your databaase to 'challenge'
} else if (fraudStatus == 'accept'){
// TODO set transaction status on your databaase to 'success'
}
} else if (transactionStatus == 'cancel' ||
transactionStatus == 'deny' ||
transactionStatus == 'expire'){
// TODO set transaction status on your databaase to 'failure'
} else if (transactionStatus == 'pending'){
// TODO set transaction status on your databaase to 'pending' / waiting payment
}
});
Also available as examples here
// get status of transaction that already recorded on midtrans (already `charge`-ed)
apiClient.transaction.status('YOUR_ORDER_ID OR TRANSACTION_ID')
.then((response)=>{
// do something to `response` object
});
// get transaction status of VA b2b transaction
apiClient.transaction.statusb2b('YOUR_ORDER_ID OR TRANSACTION_ID')
.then((response)=>{
// do something to `response` object
});
// approve a credit card transaction with `challenge` fraud status
apiClient.transaction.approve('YOUR_ORDER_ID OR TRANSACTION_ID')
.then((response)=>{
// do something to `response` object
});
// deny a credit card transaction with `challenge` fraud status
apiClient.transaction.deny('YOUR_ORDER_ID OR TRANSACTION_ID')
.then((response)=>{
// do something to `response` object
});
apiClient.transaction.cancel('YOUR_ORDER_ID OR TRANSACTION_ID')
.then((response)=>{
// do something to `response` object
});
apiClient.transaction.expire('YOUR_ORDER_ID OR TRANSACTION_ID')
.then((response)=>{
// do something to `response` object
});
let parameter = {
"amount": 5000,
"reason": "Item out of stock"
}
apiClient.transaction.refund('YOUR_ORDER_ID OR TRANSACTION_ID',parameter)
.then((response)=>{
// do something to `response` object
});
Examples are available on /examples folder. There are:
- Core Api examples
- Snap examples
- Express App examples that implement Snap & Core Api
- Midtrans Docs
- Midtrans Dashboard
- SNAP documentation
- Core API documentation
- Can't find answer you looking for? email to support@midtrans.com