Postman Samples / Usages

This includes Pre-request script for easy payload creation

Create a Java Springboot application with the HmacUtil and AesGCM Util shared:

HmacUtil - Sha512 - For Bpay OnlyAES-GCM-Util - For Bpay Only

Example SecurityController.java

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.springframework.web.bind.annotation.*;

import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class SecurityController {

    @PostMapping("/generate-secure-request")
    public Map<String, String> generateSecureRequest(@RequestBody SecureRequest request) throws GeneralSecurityException {
        // Validate input
        if (request.getClientId() == null || request.getSecretKey() == null || request.getAesKey() == null || request.getRequestPayload() == null) {
            throw new IllegalArgumentException("Missing required fields in request.");
        }

        // Encrypt request payload
        String encRequestMsg = AESGCMUtil.encrypt(request.getRequestPayload(), request.getAesKey(), request.iv);

        // Generate timestamp
        String dateTime = String.valueOf(System.currentTimeMillis());

        Map<String, String> hmacTemp = new HashMap<>();
        hmacTemp.put("clientId", request.getClientId());
        hmacTemp.put("encRequestMsg", encRequestMsg);

        ObjectMapper objectMapper = new ObjectMapper();
        String hmacMessage = "";

        try {
            String jsonString = objectMapper.writeValueAsString(hmacTemp);
            hmacMessage = request.getClientId() + dateTime + jsonString;
            hmacMessage = hmacMessage.replace(":", ": ").replace(",", ", ");
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }


        String hmac = HMACUtil.calculateHMAC(request.getSecretKey(), hmacMessage);

        System.out.println("HMAC Input final (Java): " + hmacMessage);


        // Prepare response
        Map<String, String> response = new HashMap<>();
        response.put("clientId", request.getClientId());
        response.put("dateTime", dateTime);
        response.put("hmac", hmac);
        response.put("encRequestMsg", encRequestMsg);

        return response;
    }

    @Data
    public static class SecureRequest {
        private String clientId;
        private String secretKey;
        private String aesKey;
        private String iv;
        private String requestPayload;
    }


}

and ofcourse:

@SpringBootApplication
public class CampaignApiPayloadGenApplication {

    public static void main(String[] args) {
        SpringApplication.run(CampaignApiPayloadGenApplication.class, args);
    }

}

then the gradle dependencies:

implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'

Run the app, should run on 8080 port.

then the Postman Pre-Request script


// ✅ Step 1: The API that generates secure headers & encrypted payload - Springboot app
const secureRequestUrl = "http://localhost:8080/api/generate-secure-request";

// ✅ Step 2: Define the original JSON payload
const requestPayload = JSON.stringify({
  "event_instance_id": "uniqueAlphaNumericIdPerAPICall",
  "event_type": "STATIC_QR_REFRESH",
  "target_devices": {
    "target_list_type": "MID_BASED",
    "tsp_mids": [
      "M1",
      "M2"
    ]
  },
  "event_broadcast_schedule": "IMMEDIATE",
  "event_data": {
    "action_delay_seconds": "60",
    "is_silent": true
  }
});

// ✅ Step 3: Define secret keys for HMAC and AES-GCM
const secretKey = "[RECEIVED_FROM_MOSAMBEE]";  
const aesKey = "[RECEIVED_FROM_MOSAMBEE]";  

// ✅ Step 4: Call Java API to generate secure request
pm.sendRequest({
    url: secureRequestUrl,
    method: "POST",
    header: {
        "Content-Type": "application/json"
    },
    body: {
        mode: "raw",
        raw: JSON.stringify({
            clientId: "BHARATPE",  
            secretKey: secretKey,
            aesKey: aesKey,
            requestPayload: requestPayload
        })
    }
}, function (err, res) {
    if (err) {
        console.error("❌ Failed to fetch secure request:", err);
    } else {
        console.log("✅ Secure Request Generated:", res.json());

        // ✅ Extract secure headers & encrypted payload from response
        const responseData = res.json();
        const clientId = responseData.clientId;
        const dateTime = responseData.dateTime;
        const hmac = responseData.hmac;
        const encRequestMsg = responseData.encRequestMsg;

        // ✅ Store values as Postman variables
        pm.variables.set("clientId", clientId);
        pm.variables.set("dateTime", dateTime);
        pm.variables.set("hmac", hmac);
        pm.variables.set("encRequestMsg", encRequestMsg);

        pm.environment.set("clientId", clientId);
        pm.environment.set("dateTime", dateTime);
        pm.environment.set("hmac", hmac);
        pm.environment.set("encRequestMsg", encRequestMsg);



        // ✅ Step 5: Force Headers to be Set Before Execution
        pm.request.headers.add({ key: "clientId", value: clientId });
        pm.request.headers.add({ key: "dateTime", value: dateTime });
        pm.request.headers.add({ key: "hmac", value: hmac });

        console.log("🔹 Final Headers Set:");
        console.log(`clientId: ${clientId}`);
        console.log(`dateTime: ${dateTime}`);
        console.log(`hmac: ${hmac}`);

        // ✅ Step 6: Update Request Body with Encrypted Data
        const finalRequestBody = JSON.stringify({
            clientId: clientId,
            encRequestMsg: encRequestMsg
        });

        pm.variables.set("finalRequestBody", finalRequestBody);
        pm.environment.set("finalRequestBody", finalRequestBody);

    
        console.log("🔹 Final Request Body:", finalRequestBody);
    }
});

in the body section of Postman , add:

{{finalRequestBody}}

Cheers! 🥳

This helps you debug / test faster!

Shared with ❤️ by Satyajit

Last updated

Was this helpful?