· 7 years ago · Oct 18, 2018, 07:14 PM
1// Make sure all check-out headers are in alphabetical order and
2 // all header keys must be in lower case
3 // if request contains body - it should be valid JSON and content-type header should be included
4 Map<String, String> headersMap = new TreeMap<>();
5 headersMap.put("checkout-account", "375917");
6 headersMap.put("checkout-algorithm", "sha256");
7 headersMap.put("checkout-method", "POST");
8 headersMap.put("checkout-nonce", String.valueOf(UUID.randomUUID())); // unique identifier for this request
9 headersMap.put("checkout-timestamp", ZonedDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ISO_INSTANT )); // ISO 8601 format date time
10
11 /**
12 * All API calls need to be signed using HMAC and SHA-256 or SHA-512
13 */
14 String headers[] = new String[headersMap.size()];
15
16 int index = 0;
17 for(Map.Entry<String, String> headersEntry: headersMap.entrySet()){
18 headers[index++] = headersEntry.getKey()+":"+headersEntry.getValue();
19 }
20
21 Map<String, Object> requestBody = new HashMap<>();
22 requestBody.put("stamp", "29858472952");
23 requestBody.put("reference", "9187445");
24 requestBody.put("amount", 1500);
25 requestBody.put("currency", "EUR");
26 requestBody.put("language", "FI");
27 List<List<Map<String, Object>>> itemsList = new ArrayList<>();
28 List<Map<String, Object>> item = new ArrayList<>();
29 Map<String, Object> itemObj = new HashMap<>();
30 itemObj.put("unitPrice", 1500);
31 itemObj.put("units",1);
32 itemObj.put("vatPercentage", 5);
33 itemObj.put("productCode", "#1234");
34 itemObj.put("deliveryDate", "2018-09-01");
35 item.add(itemObj);
36 itemsList.add(item);
37 requestBody.put("items", itemsList);
38 Map<String, Object> customer = new HashMap<>();
39 customer.put("email", "test.customer@example.com");
40 requestBody.put("customer", customer);
41 Map<String, Object> redirectUrls = new HashMap<>();
42 redirectUrls.put("success","localhost.copart.com:8080");
43 redirectUrls.put("cancel","localhost.copart.com:8080");
44 requestBody.put("redirectUrls",redirectUrls);
45
46 String body = new ObjectMapper().writeValueAsString(requestBody);
47
48 String data = String.join("n", ArrayUtils.addAll(headers, body));
49
50 String hmacSha256Hash = calculateHmacSha256("SAIPPUAKAUPPIAS", data);
51
52 if(hmacSha256Hash != null){
53 headersMap.put("content-type", "application/json; charset=utf-8");
54 headersMap.put("signature", hmacSha256Hash);
55
56 // Make network call checkout api
57 }
58
59private String calculateHmacSha256(String key, String data){
60 String resultHash = null;
61 try {
62 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
63 SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"),"HmacSHA256");
64 sha256_HMAC.init(secret_key);
65
66 resultHash = Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes()));
67
68 } catch (Exception e) {
69 System.out.println("Error calculating HmacSHA256 hash for data data"+ e);
70 }
71
72 return resultHash;
73}