The steps for technical integration of Snap are explained below.
?>Note: In this section, Midtrans Sandbox environment is used to test the integration process.
Sign up for a Midtrans Merchant Administration Portal (MAP) account, to get your API Keys for Sandbox environment and to test integration.
Retrieve Sandbox mode API keys that will be used for this guide.
- Acquire Snap transaction token on your backend
- Display Snap payment page on frontend
- Customer perform payment on payment page
- Handling payment status update on your backend
Sequence Diagram
The overall Snap end-to-end payment process is illustrated in following sequence diagram:
API request should be done from merchant backend to acquire Snap transaction token
by providing payment information and Server Key. There are at least three components that are required to obtain the Snap token which are explained in the table given below.
Element | Description |
---|---|
Server Key |
API server key. For more details, refer to Retrieving API Access Keys |
order_id |
Unique transaction order ID, defined from your side. One ID could be used only once for the order of the material. Allowed character are Alphanumeric, dash(-), underscore(_), tilde (~), and dot (.) String, max 50. |
gross_amount |
Total amount of transaction, defined from your side. Integer. |
The sample request for Charge API is given below. Choose your preferred programming language on the "tab" below.
Environment | Method | URL |
---|---|---|
Sandbox | POST | https://app.sandbox.midtrans.com/snap/v1/transactions |
Production | POST | https://app.midtrans.com/snap/v1/transactions |
Accept: application/json
Content-Type: application/json
Authorization: Basic AUTH_STRING
AUTH_STRING: Base64Encode("YourServerKey"+":"
)
?> Midtrans API validates HTTP request by using Basic Authentication method. The username is your Server Key while the password is empty. The authorization header value is represented by AUTH_STRING. AUTH_STRING is base-64 encoded string of your username and password separated by colon symbol (:). For more details, refer to API Authorization and Headers.
The example below shows a sample code to obtain transaction token.
Sample request in CURL:
curl -X POST \
https://app.sandbox.midtrans.com/snap/v1/transactions \
-H 'Accept: application/json'\
-H 'Authorization: Basic U0ItTWlkLXNlcnZlci1UT3ExYTJBVnVpeWhoT2p2ZnMzVV7LZU87' \
-H 'Content-Type: application/json' \
-d '{
"transaction_details": {
"order_id": "YOUR-ORDERID-123456",
"gross_amount": 10000
},
"credit_card":{
"secure" : true
},
"customer_details": {
"first_name": "budi",
"last_name": "pratama",
"email": "budi.pra@example.com",
"phone": "08111222333"
}
}'
Install midtrans-php library.
composer require midtrans/midtrans-php
Alternatively, if you are not using Composer, you can download midtrans-php library, and then require the file manually
require_once dirname(__FILE__) . '/pathofproject/Midtrans.php';
Sample Request
// Set your Merchant Server Key
\Midtrans\Config::$serverKey = 'YOUR_SERVER_KEY';
// Set to Development/Sandbox Environment (default). Set to true for Production Environment (accept real transaction).
\Midtrans\Config::$isProduction = false;
// Set sanitization on (default)
\Midtrans\Config::$isSanitized = true;
// Set 3DS transaction for credit card to true
\Midtrans\Config::$is3ds = true;
$params = array(
'transaction_details' => array(
'order_id' => rand(),
'gross_amount' => 10000,
),
'customer_details' => array(
'first_name' => 'budi',
'last_name' => 'pratama',
'email' => 'budi.pra@example.com',
'phone' => '08111222333',
),
);
$snapToken = \Midtrans\Snap::getSnapToken($params);
Install midtrans-client NPM package.
npm install --save midtrans-client
Sample Request
const midtransClient = require('midtrans-client');
// Create Snap API instance
let snap = new midtransClient.Snap({
// Set to true if you want Production Environment (accept real transaction).
isProduction : false,
serverKey : 'YOUR_SERVER_KEY'
});
let parameter = {
"transaction_details": {
"order_id": "YOUR-ORDERID-123456",
"gross_amount": 10000
},
"credit_card":{
"secure" : true
},
"customer_details": {
"first_name": "budi",
"last_name": "pratama",
"email": "budi.pra@example.com",
"phone": "08111222333"
}
};
snap.createTransaction(parameter)
.then((transaction)=>{
// transaction token
let transactionToken = transaction.token;
console.log('transactionToken:',transactionToken);
})
Install midtrans-java library.
Maven
If you are using Maven as the build tool for your project, please add the following dependency to your project's build definition (pom.xml).
<dependencies>
<dependency>
<groupId>com.midtrans</groupId>
<artifactId>java-library</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
Gradle
If you are using Gradle as the build tool for your project, please add the following dependency to your project's build definition (build.gradle):
dependencies {
implementation 'com.midtrans:java-library:3.0.0'
}
Sample Request
You can also check the functional tests for more examples.
import com.midtrans.Midtrans;
import com.midtrans.httpclient.SnapApi;
import com.midtrans.httpclient.error.MidtransError;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.json.JSONObject;
public class MidtransExample {
public static void main(String[] args) throws MidtransError {
// Set serverKey to Midtrans global config
Midtrans.serverKey = "YOUR_SERVER_KEY";
// Set value to true if you want Production Environment (accept real transaction).
Midtrans.isProduction = false;
// Create params JSON Raw Object request
public Map<String, Object> requestBody() {
UUID idRand = UUID.randomUUID();
Map<String, Object> params = new HashMap<>();
Map<String, String> transactionDetails = new HashMap<>();
transactionDetails.put("order_id", idRand);
transactionDetails.put("gross_amount", "265000");
Map<String, String> creditCard = new HashMap<>();
creditCard.put("secure", "true");
params.put("transaction_details", transactionDetails);
params.put("credit_card", creditCard);
return params;
}
// Create Token and then you can send token variable to FrontEnd,
// to initialize Snap JS when customer click pay button
String transactionToken = SnapApi.createTransactionToken(requestBody())
}
}
Install midtransclient PIP package.
pip install midtransclient
Sample Request
import midtransclient
# Create Snap API instance
snap = midtransclient.Snap(
# Set to true if you want Production Environment (accept real transaction).
is_production=False,
server_key='YOUR_SERVER_KEY'
)
# Build API parameter
param = {
"transaction_details": {
"order_id": "test-transaction-123",
"gross_amount": 200000
}, "credit_card":{
"secure" : True
}, "customer_details":{
"first_name": "budi",
"last_name": "pratama",
"email": "budi.pra@example.com",
"phone": "08111222333"
}
}
transaction = snap.create_transaction(param)
transaction_token = transaction['token']
Import Midtrans Go module package to your project. Via terminal:
go get -u github.com/midtrans/midtrans-go
and/or on your project code:
import (
"github.com/midtrans/midtrans-go"
"github.com/midtrans/midtrans-go/coreapi"
"github.com/midtrans/midtrans-go/snap"
"github.com/midtrans/midtrans-go/iris"
)
Sample request
// 1. Initiate Snap client
var s = snap.Client
s.New("YOUR-SERVER-KEY", midtrans.Sandbox)
// Use to midtrans.Production if you want Production Environment (accept real transaction).
// 2. Initiate Snap request param
req := & snap.RequestParam{
TransactionDetails: midtrans.TransactionDetails{
OrderID: "YOUR-ORDER-ID-12345",
GrossAmt: 100000,
},
CreditCard: &snap.CreditCardDetails{
Secure: true,
},
CustomerDetail: &midtrans.CustomerDetails{
FName: "John",
LName: "Doe",
Email: "john@doe.com",
Phone: "081234567890",
},
}
// 3. Execute request create Snap transaction to Midtrans Snap API
snapResp, _ := s.CreateTransaction(req)
Postman is an API development tool which is used to build, test and modify APIs. You can view our Postman Collection with the steps given below.
- Download and open Postman.
- Use this button to import our Postman Collection.
- Navigate to
1.a. SNAP transaction token request (minimum)
. - For more details, refer to Postman Collection.
- Please check Midtrans available language libraries
?>Tips: You can include more information such as customer_details
, item_details
, and so on. It is recommended to send more details regarding the transaction, so that these details will be captured on the transaction record. Which can be viewed on the Midtrans Dashboard.
Learn more on why this API request should be securely managed from your backend.
The API response for a successful API request is shown below.
{
"token":"66e4fa55-fdac-4ef9-91b5-733b97d1b862",
"redirect_url":"https://app.sandbox.midtrans.com/snap/v2/vtweb/66e4fa55-fdac-4ef9-91b5-733b97d1b862"
}
Status Codes and Errors
Status Code | Description | Example |
---|---|---|
201 | Successful creation of Snap token. | "token":"66e4fa55-fdac-4ef9-91b5-733b97d1b862" |
401 | Failed to create a token, as wrong authorization is sent. | "Access denied, please check client or server key" |
4xx | Failed to create a token, as wrong parameter is sent. Follow the error_message and check your parameter. | "transaction_details.gross_amount is not equal to the sum of item_details" |
5xx | Failed to create a token, because of Midtrans internal error. Most of the time this is temporary, you can retry later. | "Sorry, we encountered internal server error. We will fix this soon." |
To display Snap payment page within your site, there are two methods to choose.
Proceed reading this section below.
Alternatively, you can use redirect_url
retrieved from backend in the previous step to redirect customer to url hosted by Midtrans. Useful if you do not want (or unable) to implement via snap.js. Learn more in this alternative section.
You can also use WebView to display Snap payment page within your mobile app.
Include snap.js
library into your payment page HTML. The table given below describes the components which are required to display Snap payment page.
Element | Description |
---|---|
Client Key | The Client Key. For more details refer to Retrieving API Access Keys |
snap.js url |
https://app.sandbox.midtrans.com/snap/snap.js |
transaction token |
Retrieved from backend in previous step |
Enter your Client Key as the value of data-client-key
attribute in snap.js script tag. Start the payment process by calling window.snap.pay
with transaction token
.
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- @TODO: replace SET_YOUR_CLIENT_KEY_HERE with your client key -->
<script type="text/javascript"
src="https://app.sandbox.midtrans.com/snap/snap.js"
data-client-key="SET_YOUR_CLIENT_KEY_HERE"></script>
<!-- Note: replace with src="https://app.midtrans.com/snap/snap.js" for Production environment -->
</head>
<body>
<button id="pay-button">Pay!</button>
<script type="text/javascript">
// For example trigger on button clicked, or any time you need
var payButton = document.getElementById('pay-button');
payButton.addEventListener('click', function () {
// Trigger snap popup. @TODO: Replace TRANSACTION_TOKEN_HERE with your transaction token
window.snap.pay('TRANSACTION_TOKEN_HERE');
// customer will be redirected after completing payment pop-up
});
</script>
</body>
</html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- @TODO: replace SET_YOUR_CLIENT_KEY_HERE with your client key -->
<script type="text/javascript"
src="https://app.sandbox.midtrans.com/snap/snap.js"
data-client-key="SET_YOUR_CLIENT_KEY_HERE"></script>
<!-- Note: replace with src="https://app.midtrans.com/snap/snap.js" for Production environment -->
</head>
<body>
<button id="pay-button">Pay!</button>
<script type="text/javascript">
// For example trigger on button clicked, or any time you need
var payButton = document.getElementById('pay-button');
payButton.addEventListener('click', function () {
// Trigger snap popup. @TODO: Replace TRANSACTION_TOKEN_HERE with your transaction token
window.snap.pay('TRANSACTION_TOKEN_HERE', {
onSuccess: function(result){
/* You may add your own implementation here */
alert("payment success!"); console.log(result);
},
onPending: function(result){
/* You may add your own implementation here */
alert("wating your payment!"); console.log(result);
},
onError: function(result){
/* You may add your own implementation here */
alert("payment failed!"); console.log(result);
},
onClose: function(){
/* You may add your own implementation here */
alert('you closed the popup without finishing the payment');
}
})
});
</script>
</body>
</html>
Learn more about Snap's Javascript Callback here. And about Snap's Javascript optional params here.
Note: If you are using frontend framework such as ReactJS and struggling to include the script tag, please refer to this recommendation.
Tips: To ensure that Snap popup modal is displayed correctly on a mobile device, please include the viewport meta tag inside your
<head>
tag. The most common implementation:<meta name="viewport" content="width=device-width, initial-scale=1">
(included on sample above).
After following the steps given above, the sample Snap page is displayed as shown below.
Or try the demo here:
Preview Snap UI ⎋
After the payment is completed, customer is redirected back to Finish URL
. It is specified on Midtrans Dashboard, under menu Settings > Snap Preference > System Settings > Finish URL
.
?>Tips: Optionally, you can also use JavaScript callbacks to handle payment events triggered from customer finishing interaction with Snap payment page on frontend.
Create a test payment to make sure you have integrated Snap successfully. Following are the test credentials for Card payment.
Name | Value |
---|---|
Card Number | 4811 1111 1111 1114 |
CVV | 123 |
Exp Month | Any month in MM format. For example, 02 |
Exp Year | Any future year, in YYYY format. For example, 2025 |
OTP/3DS | 112233 |
In addition to that, there are various payment methods available on Snap. You can choose any one of them to create a test payment. For more details, refer to Testing Payments on Sandbox.
When the transaction status changes, customer is redirected to Redirect URL and Midtrans sends HTTP notification to the merchant backend. This ensures that you are updated of the transaction status securely.
HTTP POST request with JSON body will be sent to your server's Notification URL configured on dashboard.
Configuring Payment Notification URL
To configure the Payment Notification URL, follow the steps given below.
- Login to your MAP account.
- On the Home page, go to SETTINGS > CONFIGURATION. Configuration page is displayed.
- Enter Payment Notification URL.
- Click Update.
The URL is updated and a confirmation message is displayed.
In this section, you will learn how to handle events of payment completed by customer and other status changes.
In this section, you will learn the various useful features that are provided by Snap API.
In this section, you will learn, how transaction status can change, and what are the available actions to take.
Integration sample codes are also available on our GitHub repos.
Alternatively, you can also use redirect_url
retrieved from backend in the 1st step to redirect customer to payment page hosted by Midtrans. This is useful if you do not want or can not display payment page on your web page via snap.js.
Additionally, you can configure where customer will be redirected after the payment page, by: Login to your MAP/Midtrans Dashboard account, then go to SETTINGS > CONFIGURATION. Then please configure the Finish, Unfinish, Error Redirection URLs.
Learn more here on configuring Snap Redirect url configuration, after clicking that link please choose the Snap Redirect (Alternative)
tab.
Configuring Finish Redirect URL
To configure the Finish Redirect URL, follow the steps given below.Displaying Snap payment page within WebView can be a quick and easy way to get a payment page on your mobile app. Learn more about Displaying Snap via WebView here.
To further minimize implementation, instead of implementing Snap pop-up via snap.js
, you can use Snap's redirect_url
to be displayed within the WebView.
You can check demo of Snap displayed via WebView here.
If you are planning to have BCA KlikPay on Production mode, you will need to additionally meet these requirements.