Java Sample
This Java example is based on the Sprint framework and uses the RestTemplate to make requests.
Signature implemention
java
import java.util.*;
public class Signature {
public static String sign(Map<String, Object> params, String apiToken) {
StringBuilder str = new StringBuilder(apiToken);
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
for (String key : keys) {
Object value = params.get(key);
if (value != null && !"".equals(value.toString()) && !"sign".equals(key)) {
str.append("&").append(key).append("=").append(value);
}
}
return md5(str.toString());
}
private static String md5(String input) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String h = Integer.toHexString(0xff & b);
if (h.length() == 1) hexString.append('0');
hexString.append(h);
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}Create collection order
The following shows how to create a collection order. The payout request is similar.
java
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.*;
public class OrderRequest {
public static void main(String[] args) {
Map<String, Object> params = new HashMap<>();
params.put("mch_id", 2050); // Merchant ID
params.put("trans_id", "E1763923463"); // Transaction ID of your system
params.put("channel", "bank"); // Channel code
params.put("amount", "200000.00"); // Order amount
params.put("currency", "VND"); // Currency
params.put("callback_url", "https://api.blackhole.com"); // Webhook url
params.put("remarks", "callme"); // Remarks
params.put("nonce", UUID.randomUUID().toString().substring(0, 8)); // Random string
params.put("timestamp", System.currentTimeMillis() / 1000); // UNIX timestamp
String apiToken = "0xFAKE_TOKENx0"; // API Token
params.put("sign", Signature.sign(params, apiToken));
String gateway = "http://domain/api/v1/mch/pmt-orders";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
try {
ResponseEntity<Map> response = restTemplate.postForEntity(gateway, request, Map.class);
if (response.getStatusCode() != HttpStatus.OK) {
// todo: handle failure
} else {
Map<String, Object> body = response.getBody();
if (body != null && !Objects.equals(body.get("code"), 200)) {
String reason = String.valueOf(body.get("message")); // failed reason
// todo: handle failure
} else {
// todo: handle success
}
}
} catch (Exception e) {
// todo: other exception
e.printStackTrace();
}
}
}