Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Make sure all check-out headers are in alphabetical order and
- // all header keys must be in lower case
- // if request contains body - it should be valid JSON and content-type header should be included
- Map<String, String> headersMap = new TreeMap<>();
- headersMap.put("checkout-account", "375917");
- headersMap.put("checkout-algorithm", "sha256");
- headersMap.put("checkout-method", "POST");
- headersMap.put("checkout-nonce", String.valueOf(UUID.randomUUID())); // unique identifier for this request
- headersMap.put("checkout-timestamp", ZonedDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ISO_INSTANT )); // ISO 8601 format date time
- /**
- * All API calls need to be signed using HMAC and SHA-256 or SHA-512
- */
- String headers[] = new String[headersMap.size()];
- int index = 0;
- for(Map.Entry<String, String> headersEntry: headersMap.entrySet()){
- headers[index++] = headersEntry.getKey()+":"+headersEntry.getValue();
- }
- Map<String, Object> requestBody = new HashMap<>();
- requestBody.put("stamp", "29858472952");
- requestBody.put("reference", "9187445");
- requestBody.put("amount", 1500);
- requestBody.put("currency", "EUR");
- requestBody.put("language", "FI");
- List<List<Map<String, Object>>> itemsList = new ArrayList<>();
- List<Map<String, Object>> item = new ArrayList<>();
- Map<String, Object> itemObj = new HashMap<>();
- itemObj.put("unitPrice", 1500);
- itemObj.put("units",1);
- itemObj.put("vatPercentage", 5);
- itemObj.put("productCode", "#1234");
- itemObj.put("deliveryDate", "2018-09-01");
- item.add(itemObj);
- itemsList.add(item);
- requestBody.put("items", itemsList);
- Map<String, Object> customer = new HashMap<>();
- customer.put("email", "test.customer@example.com");
- requestBody.put("customer", customer);
- Map<String, Object> redirectUrls = new HashMap<>();
- redirectUrls.put("success","localhost.copart.com:8080");
- redirectUrls.put("cancel","localhost.copart.com:8080");
- requestBody.put("redirectUrls",redirectUrls);
- String body = new ObjectMapper().writeValueAsString(requestBody);
- String data = String.join("n", ArrayUtils.addAll(headers, body));
- String hmacSha256Hash = calculateHmacSha256("SAIPPUAKAUPPIAS", data);
- if(hmacSha256Hash != null){
- headersMap.put("content-type", "application/json; charset=utf-8");
- headersMap.put("signature", hmacSha256Hash);
- // Make network call checkout api
- }
- private String calculateHmacSha256(String key, String data){
- String resultHash = null;
- try {
- Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
- SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"),"HmacSHA256");
- sha256_HMAC.init(secret_key);
- resultHash = Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes()));
- } catch (Exception e) {
- System.out.println("Error calculating HmacSHA256 hash for data data"+ e);
- }
- return resultHash;
- }
Add Comment
Please, Sign In to add comment