improved the logging and corrected payement start record

This commit is contained in:
Lincpay Tech
2025-12-18 21:57:56 +05:30
parent d34b2e1b84
commit f752ed269f
15 changed files with 417 additions and 609 deletions
@@ -1,116 +0,0 @@
package com.billpaymentservice.bbps.config;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.billpaymentservice.bbps.util.BBPSConstant;
import com.billpaymentservice.bbps.dto.ResponseModel;
import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
@Order(1)
public class RateLimitingFilter extends OncePerRequestFilter {
private final RateLimiterRegistry rateLimiterRegistry;
private static final Logger LOGGER = LoggerFactory.getLogger(RateLimitingFilter.class);
// Har MID ke liye alag limiter
private final Map<String, RateLimiter> limiterCache = new ConcurrentHashMap<>();
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public RateLimitingFilter(RateLimiterRegistry rateLimiterRegistry) {
this.rateLimiterRegistry = rateLimiterRegistry;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
String mid = request.getHeader("mid");
if(mid == null) {
mid = "GLOBAL";
}
// Validate MID
if (mid == null || mid.isBlank()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("application/json");
ResponseModel<Object> apiResponse = new ResponseModel<>("mid cannot be null or blank", "FAILURE", HttpServletResponse.SC_BAD_REQUEST, null);
response.getWriter().write(OBJECT_MAPPER.writeValueAsString(apiResponse));
return;
}
try {
RateLimiter rateLimiter = limiterCache.computeIfAbsent(
mid,
key -> rateLimiterRegistry.rateLimiter("default")
);
// Rate limit check
if (!rateLimiter.acquirePermission()) {
// Prefer existing constant if it maps to 429, otherwise fallback to literal 429
int tooManyRequestsStatus =429;
response.setStatus(tooManyRequestsStatus);
response.setContentType("application/json");
ResponseModel<Object> apiResponse = new ResponseModel<>("Rate limit exceeded for MID: " + mid, "FAILURE", tooManyRequestsStatus, null);
response.getWriter().write(OBJECT_MAPPER.writeValueAsString(apiResponse));
return;
}
// Proceed with the chain and catch downstream exceptions to return consistent model
try {
filterChain.doFilter(request, response);
} catch (Exception ex) {
LOGGER.error("Unhandled exception in filter chain for MID: {}", mid, ex);
if (!response.isCommitted()) {
response.reset();
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("application/json");
ResponseModel<Object> apiResponse = new ResponseModel<>("Internal server error", "FAILURE", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
response.getWriter().write(OBJECT_MAPPER.writeValueAsString(apiResponse));
}
}
} catch (Exception e) {
LOGGER.error("Error while rate limiting request", e);
if (!response.isCommitted()) {
response.reset();
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("application/json");
ResponseModel<Object> apiResponse = new ResponseModel<>("Internal server error", "FAILURE", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
response.getWriter().write(OBJECT_MAPPER.writeValueAsString(apiResponse));
}
return;
}
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
String path = request.getRequestURI();
return path.startsWith("/swagger")
|| path.startsWith("/v3/api-docs")
|| path.startsWith("/actuator");
}
}
@@ -26,7 +26,7 @@ import jakarta.persistence.FetchType;
public class PaymentStartRecord extends Auditable {
@Id
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@@ -47,7 +47,7 @@ public class PaymentStartRecord extends Auditable {
@Column(name = "amount", nullable = false)
private String amount;
@Column(name = "txn_id", unique = true, nullable = false)
@Column(name = "txn_id")
private String txnId;
@Column(name = "qr_string", columnDefinition = "TEXT")
@@ -9,6 +9,8 @@ import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
@@ -28,23 +30,21 @@ import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
public class TransactionMaster extends Auditable {
// 👇 JSON me "txn_id" aayega, ye DB me bank_txn_id column me save hoga
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@JsonProperty("txn_id")
@Column(name = "bank_txn_id", nullable = false, unique = true)
@Column(name = "bank_txn_id",unique = true)
private String bankTxnId;
// 👇 Apna internal transaction id, manually generate or system ke through
@Column(name = "txn_id")
private String txnId;
// 👇 New: txn id generated at the time of initiatePayment
@Id
@Column(name = "initiator_txn_id")
private String initiatorTxnId;
// 👇 New: txn id generated during internal check transaction status
@Column(name = "checker_txn_id")
private String checkerTxnId;
@@ -1,6 +1,7 @@
package com.billpaymentservice.bbps.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
@@ -10,7 +11,7 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.billpaymentservice.bbps.entites.TransactionMaster;
public interface TransactionMasterRepository extends JpaRepository<TransactionMaster, String> {
public interface TransactionMasterRepository extends JpaRepository<TransactionMaster, Long> {
// @Query("SELECT t FROM TransactionMaster t WHERE t.mid = :mid OR t.clientUserId = :clientUserId")
// List<TransactionMaster> findByMidOrClientUserId(@Param("mid") String mid,
@@ -40,4 +41,6 @@ public interface TransactionMasterRepository extends JpaRepository<TransactionMa
// Find by initiatorTxnId so services can look up records created during initiatePayment
TransactionMaster findByInitiatorTxnId(String initiatorTxnId);
Optional<TransactionMaster> findByBankTxnId(String txnId);
}
@@ -468,14 +468,7 @@ public class AgentServiceImpl implements AgentService {
throw new CustomException(BBPSConstant.MSG_INVALID_JSON_FROM_UPSTREAM,BBPSConstant.FAILED_STATUS, BBPSConstant.INVALID_JSON_STATUS_CODE, e.getMessage());
}
}
// ================================== Bill fetch and Bill Validate by Client Req
// Id==================================//
// =======
// ... remaining methods unchanged except where headers/objectMapper were
// previously created (they now use buildHeaders() and the class-level
// objectMapper)
// >>>>>>>d0812656ff2aee80b1eb0c0ab8e29a01d7d66553
@Override
public ResponseModel fetchBillValidateByClientReqId(BillValidateByClientIdRequest billValidateByClientIdRequest) {
@@ -126,7 +126,7 @@ public class ComplainServiceImpl implements ComplainService {
try {
Optional<TransactionMaster> dataById = transactionMasterRepository.findById(complainRequestDTO.getTxnId());
Optional<TransactionMaster> dataById = transactionMasterRepository.findByBankTxnId(complainRequestDTO.getTxnId());
if (dataById == null || dataById.isEmpty()) {
LOGGER.warn("Txn Data Not Found This Txn Id is null");
throw new CustomException(BBPSConstant.USER_Txn_IS_NOT_FOUND, "FAILED", BBPSConstant.BADREQUEST, null);
@@ -181,20 +181,15 @@ public class HttpService {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
log.info("🌐 Sending FORM POST to: {}", url);
log.info("📦 Payload: {}", formBody);
ResponseEntity<String> restResponse = restClient.post()
.uri(url)
.headers(h -> h.addAll(headers))
.body(formBody)
.retrieve()
.toEntity(String.class);
response.put("respCode", String.valueOf(restResponse.getStatusCode().value()));
// HTML RESPONSE directly stored
response.put("data", restResponse.getBody());
log.info("✅ FORM POST Response Status: {}", restResponse.getStatusCode());
@@ -105,75 +105,68 @@ public class PaymentServiceImpl implements PaymentService {
String requestJson = helper.convertObjectToJson(billPaymentRequest);
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnId, apiName, billPaymentRequest.getMid(),
BBPSConstant.HTTP_POST, requestJson);
BBPSConstant.HTTP_POST, requestJson);
LOGGER.debug("Inbound log created for api={} | reqId={} | txnId={}", apiName, requestId, txnId);
OutboundTraceLog outboundLog = helper.createOutboundLog(txnId, requestId, apiName, url, BBPSConstant.HTTP_POST,
forwardjson);
forwardjson);
LOGGER.debug("Outbound log created for api={} | reqId={} | txnId={}", apiName, requestId, txnId);
// Persist a TransactionMaster BEFORE making the external call so we have a DB record
// even if the HTTP call fails later. This is intentionally tolerant: failure to
// save here should not prevent the outgoing request, so we catch and log errors.
try {
TransactionMaster preTransaction = new TransactionMaster();
preTransaction.setBankTxnId(txnId+"bank");
preTransaction.setTxnId(txnId);
preTransaction.setInitiatorTxnId(txnId);
preTransaction.setReqId(requestId);
preTransaction.setMid(billPaymentRequest.getMid());
preTransaction.setClientUserId(billPaymentRequest.getClientUserId());
preTransaction.setClientReqId(billPaymentRequest.getClientReqId());
preTransaction.setUserId(userId);
preTransaction.setStatus("PENDING");
EntityRelationshipUtil.linkTransactionMasterRelationships(preTransaction);
// ensure txnId exists (no uniqueness suffixing)
preTransaction.setTxnId(ensureTxnId(preTransaction.getTxnId()));
transactionMasterRepository.save(preTransaction);
LOGGER.info("Pre-request TransactionMaster saved with status=INITIATED for txnId={}", txnId);
} catch (Exception e) {
LOGGER.warn("Failed to persist pre-request TransactionMaster for txnId={}: {}", txnId, e.getMessage());
}
LOGGER.info("Calling BBPS payment URL: {}", url);
Map<String, String> responseMap = httpService.postRequest(url, forwardjson, headers);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Payment API Response: {}", responseData);
TransactionMaster preTransaction=null;
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for txnId={}", txnId);
preTransaction = new TransactionMaster();
preTransaction.setTxnId(txnId);
preTransaction.setInitiatorTxnId(txnId);
preTransaction.setReqId(requestId);
preTransaction.setMid(billPaymentRequest.getMid());
preTransaction.setClientUserId(billPaymentRequest.getClientUserId());
preTransaction.setClientReqId(billPaymentRequest.getClientReqId());
preTransaction.setUserId(userId);
preTransaction.setStatus("PENDING");
EntityRelationshipUtil.linkTransactionMasterRelationships(preTransaction);
// ensure txnId exists (no uniqueness suffixing)
preTransaction.setTxnId(ensureTxnId(preTransaction.getTxnId()));
transactionMasterRepository.save(preTransaction);
LOGGER.info("Pre-request TransactionMaster saved with status=INITIATED for txnId={}", txnId);
Map<String, Object> dataMap;
try {
dataMap = objectMapper.readValue(responseData,
new TypeReference<Map<String, Object>>() {
});
LOGGER.info("Calling BBPS payment URL: {}", url);
Map<String, String> responseMap = httpService.postRequest(url, forwardjson, headers);
BillPaymentResponse billPaymentResponse = objectMapper.convertValue(dataMap, BillPaymentResponse.class);
GeneralResp generalResponse = billPaymentResponse.getGenericResponse();
LOGGER.info("genric Response" + generalResponse);
BillPayment entity = modelMapper.map(billPaymentResponse, BillPayment.class);
paymentRepository.save(entity);
LOGGER.info("BillPayment entity saved successfully for txnId={}", txnId);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResponse.getStatus());
TransactionStatusRequest transactionStatusRequest = new TransactionStatusRequest();
transactionStatusRequest.setReqId(billPaymentRequest.getReqId());
transactionStatusRequest.setTxnId(entity.getTxnId());
ResponseModel responseModel = checkTrasactionStatus(transactionStatusRequest, inboundLog);
return responseModel;
} catch (JsonProcessingException e) {
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException(BBPSConstant.MSG_INVALID_JSON_FROM_UPSTREAM,BBPSConstant.FAILED_STATUS, BBPSConstant.INVALID_JSON_STATUS_CODE, e.getMessage());
}
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Payment API Response: {}", responseData);
}
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for txnId={}", txnId);
Map<String, Object> dataMap = parseJsonToMap(responseData, inboundLog);
BillPaymentResponse billPaymentResponse = objectMapper.convertValue(dataMap, BillPaymentResponse.class);
GeneralResp generalResponse = billPaymentResponse.getGenericResponse();
LOGGER.info("genric Response" + generalResponse);
BillPayment entity = modelMapper.map(billPaymentResponse, BillPayment.class);
paymentRepository.save(entity);
LOGGER.info("BillPayment entity saved successfully for txnId={}", txnId);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResponse.getStatus());
preTransaction.setBankTxnId(entity.getTxnId());
transactionMasterRepository.save(preTransaction);
LOGGER.info("updated TransactionMaster with bankTxnId for txnId={}", txnId);
TransactionStatusRequest transactionStatusRequest = new TransactionStatusRequest();
transactionStatusRequest.setReqId(billPaymentRequest.getReqId());
transactionStatusRequest.setTxnId(entity.getTxnId());
ResponseModel responseModel = checkTrasactionStatus(transactionStatusRequest, inboundLog);
return responseModel;
}
public ResponseModel checkTrasactionStatus(TransactionStatusRequest transactionStatusRequest,
InboundTraceLog inboundLog) {
@@ -202,101 +195,59 @@ public class PaymentServiceImpl implements PaymentService {
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for internal status check | txnId={}", checkerTxnId);
try {
Map<String, Object> dataMap = objectMapper.readValue(responseData,
new TypeReference<Map<String, Object>>() {
});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_RESPONSE);
LOGGER.warn("Invalid transaction status response for txnId={}", transactionStatusRequest.getTxnId());
throw new CustomException(String.valueOf(dataMap.get("message")), String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks")));
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap,
TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
// Map DTO -> Entity, but explicitly copy bankTxnId from DTO to entity to avoid mapping gaps
TransactionDTO txDao = responseWrapper.getTransactionDAO();
TransactionMaster transactionMaster = modelMapper.map(txDao,
TransactionMaster.class);
LOGGER.info("INBOPUND TRANSACTION ID:{}",inboundLog.getTxnId());
TransactionMaster
existingTransaction=transactionMasterRepository.findByInitiatorTxnId(
inboundLog.getTxnId());
LOGGER.info("existingTransaction :{}",existingTransaction);
if(existingTransaction != null) {
LOGGER.info("Existing TransactionMaster found for bankTxnId");
// Merge incoming non-null fields into the existing DB entity so we preserve DB values
mergeNonNullFields(transactionMaster, existingTransaction);
transactionMaster = existingTransaction;
}
// Ensure bankTxnId from DTO is set if provided
if (txDao != null && txDao.getBankTxnId() != null && !txDao.getBankTxnId().isBlank()) {
transactionMaster.setBankTxnId(txDao.getBankTxnId());
}
// do not overwrite existing txnId if present; set checker txn id when missing
if (transactionMaster.getTxnId() == null || transactionMaster.getTxnId().isBlank()) {
transactionMaster.setTxnId(checkerTxnId);
}
transactionMaster.setCheckerTxnId(checkerTxnId);
transactionMaster.setReqId(transactionStatusRequest.getReqId());
transactionMaster.setMid(transactionStatusRequest.getMid());
transactionMaster.setClientUserId(transactionStatusRequest.getClientUserId());
EntityRelationshipUtil.linkTransactionMasterRelationships(transactionMaster);
// Ensure internal txnId exists
transactionMaster.setTxnId(ensureTxnId(transactionMaster.getTxnId()));
// If bankTxnId (primary key) is missing, assign a placeholder so the entity can be saved
if (transactionMaster.getBankTxnId() == null || transactionMaster.getBankTxnId().isBlank()) {
String placeholderBankId = "GEN_" + transactionMaster.getTxnId();
transactionMaster.setBankTxnId(placeholderBankId);
LOGGER.warn("bankTxnId missing in response; assigning placeholder bankTxnId={} for txnId={}", placeholderBankId, transactionMaster.getTxnId());
}
// Map and persist AgentFundTransfer if present
AgentFundTransfer agentFundTransfer = null;
try {
if (responseWrapper.getAgentFundTransfer() != null) {
agentFundTransfer = modelMapper.map(responseWrapper.getAgentFundTransfer(), AgentFundTransfer.class);
} else {
agentFundTransfer = new AgentFundTransfer();
}
agentFundTransfer.setTxnId(transactionMaster.getTxnId());
agentFundTransfer.setReqId(transactionStatusRequest.getReqId());
agentFundTransfer.setTransactionMasterId(transactionMaster.getBankTxnId());
} catch (Exception e) {
LOGGER.debug("No AgentFundTransfer in response or mapping failed: {}", e.getMessage());
}
// Persist updated transaction master and agent fund transfer so DB reflects merged non-null fields
try {
transactionMasterRepository.save(transactionMaster);
if (agentFundTransfer != null) { agentFundTransferRepository.save(agentFundTransfer); }
LOGGER.info("Persisted TransactionMaster and AgentFundTransfer for txnId={} bankTxnId={}"
, transactionMaster.getTxnId(), transactionMaster.getBankTxnId());
} catch (Exception e) {
LOGGER.warn("Failed to persist TransactionMaster/AgentFundTransfer for txnId={}: {}", transactionMaster.getTxnId(), e.getMessage(), e);
}
ResponseModel responseModel = new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END (internal) | checkTxnId={} | reqId={} | status={}", apiName, checkerTxnId, requestId, generalResp.getStatus());
return responseModel;
} catch (JsonProcessingException e) {
LOGGER.error("Error parsing transaction status JSON: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException(BBPSConstant.MSG_INVALID_JSON_FROM_UPSTREAM, BBPSConstant.FAILED_STATUS, BBPSConstant.INVALID_JSON_STATUS_CODE, e.getMessage());
Map<String, Object> dataMap = parseJsonToMap(responseData, inboundLog);
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_RESPONSE);
LOGGER.warn("Invalid transaction status response for txnId={}", transactionStatusRequest.getTxnId());
throw new CustomException(String.valueOf(dataMap.get("message")), String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks")));
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap,
TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
TransactionDTO txDao = responseWrapper.getTransactionDAO();
TransactionMaster transactionMaster = modelMapper.map(txDao,
TransactionMaster.class);
LOGGER.info("INBOUND TRANSACTION ID:{}",inboundLog.getTxnId());
TransactionMaster
existingTransaction=transactionMasterRepository.findByInitiatorTxnId(
inboundLog.getTxnId());
LOGGER.info("existingTransaction :{}",existingTransaction);
if(existingTransaction != null) {
LOGGER.info("Existing TransactionMaster found for bankTxnId");
// Merge incoming non-null fields into the existing DB entity so we preserve DB values
helper.mergeNonNullFields(transactionMaster, existingTransaction);
transactionMaster = existingTransaction;
}
transactionMaster.setCheckerTxnId(checkerTxnId);
EntityRelationshipUtil.linkTransactionMasterRelationships(transactionMaster);
AgentFundTransfer agentFundTransfer = null;
if (responseWrapper.getAgentFundTransfer() != null) {
agentFundTransfer = modelMapper.map(responseWrapper.getAgentFundTransfer(), AgentFundTransfer.class);
} else {
agentFundTransfer = new AgentFundTransfer();
}
agentFundTransfer.setTxnId(transactionMaster.getTxnId());
agentFundTransfer.setReqId(transactionStatusRequest.getReqId());
agentFundTransfer.setTransactionMasterId(transactionMaster.getBankTxnId());
transactionMasterRepository.save(transactionMaster);
if (agentFundTransfer != null) { agentFundTransferRepository.save(agentFundTransfer); }
LOGGER.info("Persisted TransactionMaster and AgentFundTransfer for txnId={} bankTxnId={}"
, transactionMaster.getTxnId(), transactionMaster.getBankTxnId());
ResponseModel responseModel = new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END (internal) | checkTxnId={} | reqId={} | status={}", apiName, checkerTxnId, requestId, generalResp.getStatus());
return responseModel;
}
@Override
@@ -314,15 +265,10 @@ public class PaymentServiceImpl implements PaymentService {
transactionStatusRequest.getTxnId(), requestId);
// First, attempt to find an existing TransactionMaster by initiatorTxnId and update it
try {
String initiatorTxnId = transactionStatusRequest.getTxnId();
if (initiatorTxnId != null && !initiatorTxnId.isBlank()) {
}
}
catch (Exception e) {
// Log but continue to fallback behavior
LOGGER.warn("Error while updating by initiatorTxnId: {}", e.getMessage());
String initiatorTxnId = transactionStatusRequest.getTxnId();
if (initiatorTxnId != null && !initiatorTxnId.isBlank()) {
// logic intentionally left minimal here — any runtime exception should bubble
// to the global exception handler so failures are visible and handled centrally.
}
LOGGER.info("Falling back to external BBPS status check URL={}", url);
@@ -343,99 +289,37 @@ public class PaymentServiceImpl implements PaymentService {
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for public status check | reqId={} | txnId={}", requestId, txnID);
try {
Map<String, Object> dataMap = objectMapper.readValue(responseData,
new TypeReference<Map<String, Object>>() {
});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData,
String.valueOf(dataMap.get(BBPSConstant.RESPONSE_STATUS_KEY)));
LOGGER.warn("Invalid transaction status response for txnId={} from BBPS",
transactionStatusRequest.getTxnId());
throw new CustomException(String.valueOf(dataMap.get("message")), String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks")));
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap,
TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
String status = generalResp.getStatus();
LOGGER.info("Current transaction status: {}", status);
// --- NEW: attempt to persist/update TransactionMaster so DB reflects new status/bankTxnId ---
try {
TransactionDTO txDao = responseWrapper.getTransactionDAO();
TransactionMaster updatedEntity = null;
// 1) Try to find by initiatorTxnId (client may pass initiator txn id)
if (transactionStatusRequest.getTxnId() != null && !transactionStatusRequest.getTxnId().isBlank()) {
TransactionMaster byInitiator = transactionMasterRepository.findByInitiatorTxnId(transactionStatusRequest.getTxnId());
if (byInitiator != null) {
updatedEntity = byInitiator;
}
}
// 2) If not found, try find by internal txnId (txn_id column)
if (updatedEntity == null && txDao != null && txDao.getBankTxnId() != null && !txDao.getBankTxnId().isBlank()) {
try {
java.util.List<TransactionMaster> byTxnIdList = transactionMasterRepository.findByTxnId(txDao.getBankTxnId());
if (byTxnIdList != null && !byTxnIdList.isEmpty()) {
updatedEntity = byTxnIdList.get(0);
}
} catch (Exception ignore) {
LOGGER.debug("Error while searching by txnId: {}", ignore.getMessage());
}
}
// 3) As a last attempt, if request passed an id that matches internal txnId column
if (updatedEntity == null && transactionStatusRequest.getTxnId() != null && !transactionStatusRequest.getTxnId().isBlank()) {
try {
java.util.List<TransactionMaster> byTxnIdList2 = transactionMasterRepository.findByTxnId(transactionStatusRequest.getTxnId());
if (byTxnIdList2 != null && !byTxnIdList2.isEmpty()) {
updatedEntity = byTxnIdList2.get(0);
}
} catch (Exception ignore) {
LOGGER.debug("Error while searching by txnId (fallback): {}", ignore.getMessage());
}
}
// If we found an entity, merge non-null fields from DTO and save
if (updatedEntity != null) {
TransactionMaster mapped = modelMapper.map(txDao, TransactionMaster.class);
mergeNonNullFields(mapped, updatedEntity);
// ensure internal txnId exists
updatedEntity.setTxnId(ensureTxnId(updatedEntity.getTxnId()));
EntityRelationshipUtil.linkTransactionMasterRelationships(updatedEntity);
try {
transactionMasterRepository.save(updatedEntity);
LOGGER.info("Updated TransactionMaster in DB for initiatorTxnId={} (bankTxnId={})",
updatedEntity.getInitiatorTxnId(), updatedEntity.getBankTxnId());
} catch (Exception e) {
LOGGER.warn("Failed to persist updated TransactionMaster: {}", e.getMessage(), e);
}
} else {
LOGGER.debug("No matching TransactionMaster found to update for txnId={}", transactionStatusRequest.getTxnId());
}
} catch (Exception e) {
LOGGER.warn("Error while attempting to persist transaction status update: {}", e.getMessage());
}
// --- END NEW PERSISTENCE BLOCK ---
ResponseModel responseModel = new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END (public) | reqId={} | txnId={} | status={}", apiName, requestId, txnID,
generalResp.getStatus());
return responseModel;
} catch (JsonProcessingException e) {
LOGGER.error("Error parsing responseData JSON: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException(BBPSConstant.MSG_INVALID_JSON_FROM_UPSTREAM,BBPSConstant.FAILED_STATUS, BBPSConstant.INVALID_JSON_STATUS_CODE, e.getMessage());
Map<String, Object> dataMap = parseJsonToMap(responseData, inboundLog);
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData,
String.valueOf(dataMap.get(BBPSConstant.RESPONSE_STATUS_KEY)));
LOGGER.warn("Invalid transaction status response for txnId={} from BBPS",
transactionStatusRequest.getTxnId());
throw new CustomException(String.valueOf(dataMap.get("message")), String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks")));
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap,
TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
String status = generalResp.getStatus();
LOGGER.info("Current transaction status: {}", status);
// --- NEW: attempt to persist/update TransactionMaster so DB reflects new status/bankTxnId ---
TransactionDTO txDao = responseWrapper.getTransactionDAO();
TransactionMaster updatedEntity = null;
ResponseModel responseModel = new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END (public) | reqId={} | txnId={} | status={}", apiName, requestId, txnID,
generalResp.getStatus());
return responseModel;
}
@Override
@@ -480,62 +364,50 @@ public class PaymentServiceImpl implements PaymentService {
HttpHeaders headers = helper.buildHeaders(headersData);
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnID, apiName,
transactionStatusRequest.getMid(), BBPSConstant.HTTP_POST, requestJson);
transactionStatusRequest.getMid(), BBPSConstant.HTTP_POST, requestJson);
LOGGER.debug("Inbound log created for clientReqId check | reqId={} | txnId={}", requestId, txnID);
OutboundTraceLog outboundLog = helper.createOutboundLog(txnID, requestId, apiName, url, BBPSConstant.HTTP_GET,
null);
null);
LOGGER.debug("Outbound log created for clientReqId check | reqId={} | txnId={}", requestId, txnID);
try {
LOGGER.info("Calling BBPS Transaction Status API URL={}", url);
Map<String, String> responseMap = httpService.getRequest(url, headers);
LOGGER.info("Calling BBPS Transaction Status API URL={}", url);
Map<String, String> responseMap = httpService.getRequest(url, headers);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Transaction Status Response: {}", responseData);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Transaction Status Response: {}", responseData);
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for clientReqId check | reqId={} | txnId={}", requestId, txnID);
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for clientReqId check | reqId={} | txnId={}", requestId, txnID);
Map<String, Object> dataMap = objectMapper.readValue(responseData,
new TypeReference<Map<String, Object>>() {
});
Map<String, Object> dataMap = parseJsonToMap(responseData, inboundLog);
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_RESPONSE);
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_RESPONSE);
LOGGER.warn("Invalid transaction status response for clientReqId={} | Response={}", clientReqId,
responseData);
LOGGER.warn("Invalid transaction status response for clientReqId={} | Response={}", clientReqId,
responseData);
throw new CustomException(String.valueOf(dataMap.get("message")), String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks")));
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap,
TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
LOGGER.info("Transaction Status for clientReqId={} => {}", clientReqId, generalResp.getStatus());
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END | reqId={} | clientReqId={} | status={}", apiName, requestId, clientReqId,
generalResp.getStatus());
return new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
} catch (JsonProcessingException e) {
LOGGER.error("Error parsing JSON in transaction status API: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException(BBPSConstant.MSG_INVALID_JSON_FROM_UPSTREAM,BBPSConstant.FAILED_STATUS, BBPSConstant.INVALID_JSON_STATUS_CODE, e.getMessage());
throw new CustomException(String.valueOf(dataMap.get("message")), String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks")));
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap,
TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
LOGGER.info("Transaction Status for clientReqId={} => {}", clientReqId, generalResp.getStatus());
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END | reqId={} | clientReqId={} | status={}", apiName, requestId, clientReqId,
generalResp.getStatus());
return new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
}
/**
* Return the provided txnId or generate a new one when the provided value is null/blank.
* This intentionally does NOT try to ensure database-level uniqueness (no suffixing or retries).
*/
private String ensureTxnId(String txnId) {
if (txnId == null || txnId.isBlank()) {
return helper.generateTxnId(15);
@@ -543,68 +415,14 @@ public class PaymentServiceImpl implements PaymentService {
return txnId;
}
/**
* Merge non-null fields from src into dest. This keeps existing DB fields when the incoming
* payload doesn't provide them. Only non-null (and for Strings, non-blank) fields from src
* will overwrite dest fields.
*/
private void mergeNonNullFields(TransactionMaster src, TransactionMaster dest) {
/*
* LOGGER.info("TransactionMaster src: {}", src);
*/ // Only copy values that are non-null (and non-blank for Strings)
if (src.getTxnId() != null && !src.getTxnId().isBlank()) dest.setTxnId(src.getTxnId());
if (src.getInitiatorTxnId() != null && !src.getInitiatorTxnId().isBlank()) dest.setInitiatorTxnId(src.getInitiatorTxnId());
if (src.getCheckerTxnId() != null && !src.getCheckerTxnId().isBlank()) dest.setCheckerTxnId(src.getCheckerTxnId());
if (src.getReqId() != null && !src.getReqId().isBlank()) dest.setReqId(src.getReqId());
if (src.getMid() != null && !src.getMid().isBlank()) dest.setMid(src.getMid());
if (src.getClientUserId() != null && !src.getClientUserId().isBlank()) dest.setClientUserId(src.getClientUserId());
if (src.getClientReqId() != null && !src.getClientReqId().isBlank()) dest.setClientReqId(src.getClientReqId());
if (src.getUserId() != null && !src.getUserId().isBlank()) dest.setUserId(src.getUserId());
if (src.getBillerId() != null && !src.getBillerId().isBlank()) dest.setBillerId(src.getBillerId());
if (src.getTxnAmount() != null) dest.setTxnAmount(src.getTxnAmount());
if (src.getStatus() != null && !src.getStatus().isBlank()) dest.setStatus(src.getStatus());
if (src.getPaymentInformation() != null && !src.getPaymentInformation().isBlank()) dest.setPaymentInformation(src.getPaymentInformation());
if (src.getCreationDateBank() != null) dest.setCreationDateBank(src.getCreationDateBank());
if (src.getModifiedDateBank() != null) dest.setModifiedDateBank(src.getModifiedDateBank());
if (src.getCreatedEpochDateBank() != null) dest.setCreatedEpochDateBank(src.getCreatedEpochDateBank());
if (src.getModifiedEpochDateBank() != null) dest.setModifiedEpochDateBank(src.getModifiedEpochDateBank());
/* ---- additional fields ---- */
if (src.getRefId() != null && !src.getRefId().isBlank()) dest.setRefId(src.getRefId());
if (src.getPaymentRefId() != null && !src.getPaymentRefId().isBlank()) dest.setPaymentRefId(src.getPaymentRefId());
if (src.getRemitterName() != null && !src.getRemitterName().isBlank()) dest.setRemitterName(src.getRemitterName());
if (src.getOrderId() != null && !src.getOrderId().isBlank()) dest.setOrderId(src.getOrderId());
if (src.getBillId() != null && !src.getBillId().isBlank()) dest.setBillId(src.getBillId());
if (src.getUserType() != null && !src.getUserType().isBlank()) dest.setUserType(src.getUserType());
if (src.getTotalTxnAmount() != null) dest.setTotalTxnAmount(src.getTotalTxnAmount());
if (src.getBillerCategory() != null && !src.getBillerCategory().isBlank()) dest.setBillerCategory(src.getBillerCategory());
if (src.getBillerName() != null && !src.getBillerName().isBlank()) dest.setBillerName(src.getBillerName());
if (src.getOffUsPay() != null) dest.setOffUsPay(src.getOffUsPay());
if (src.getSplitPay() != null) dest.setSplitPay(src.getSplitPay());
if (src.getQuickPay() != null) dest.setQuickPay(src.getQuickPay());
if (src.getPaymentMode() != null && !src.getPaymentMode().isBlank()) dest.setPaymentMode(src.getPaymentMode());
if (src.getAgentPaymentInformation() != null && !src.getAgentPaymentInformation().isBlank()) dest.setAgentPaymentInformation(src.getAgentPaymentInformation());
if (src.getCustConvFee() != null) dest.setCustConvFee(src.getCustConvFee());
if (src.getCurrency() != null && !src.getCurrency().isBlank()) dest.setCurrency(src.getCurrency());
if (src.getRequestedIp() != null && !src.getRequestedIp().isBlank()) dest.setRequestedIp(src.getRequestedIp());
if (src.getCustomerMobNo() != null && !src.getCustomerMobNo().isBlank()) dest.setCustomerMobNo(src.getCustomerMobNo());
if (src.getMacAddress() != null && !src.getMacAddress().isBlank()) dest.setMacAddress(src.getMacAddress());
if (src.getSplitPayAmount() != null) dest.setSplitPayAmount(src.getSplitPayAmount());
if (src.getCouCustConvFee() != null) dest.setCouCustConvFee(src.getCouCustConvFee());
if (src.getSettlementVerification() != null) dest.setSettlementVerification(src.getSettlementVerification());
if (src.getFundTxnType() != null && !src.getFundTxnType().isBlank()) dest.setFundTxnType(src.getFundTxnType());
if (src.getReason() != null && !src.getReason().isBlank()) dest.setReason(src.getReason());
if (src.getAmountTags() != null && !src.getAmountTags().isBlank()) dest.setAmountTags(src.getAmountTags());
if (src.getPlanId() != null && !src.getPlanId().isBlank()) dest.setPlanId(src.getPlanId());
if (src.getPlanType() != null && !src.getPlanType().isBlank()) dest.setPlanType(src.getPlanType());
if (src.getTxnNpciId() != null && !src.getTxnNpciId().isBlank()) dest.setTxnNpciId(src.getTxnNpciId());
/* ---- lists (direct replace when provided) ---- */
if (src.getDeviceBlockTags() != null && !src.getDeviceBlockTags().isEmpty()) dest.setDeviceBlockTags(src.getDeviceBlockTags());
if (src.getCustomerParams() != null && !src.getCustomerParams().isEmpty()) dest.setCustomerParams(src.getCustomerParams());
LOGGER.info("TransactionMaster dest after merge: {}", dest);
private Map<String, Object> parseJsonToMap(String responseData, InboundTraceLog inboundLog) {
try {
return objectMapper.readValue(responseData, new TypeReference<Map<String, Object>>() {});
} catch (JsonProcessingException e) {
LOGGER.error("Error parsing JSON response: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException(BBPSConstant.MSG_INVALID_JSON_FROM_UPSTREAM, BBPSConstant.FAILED_STATUS, BBPSConstant.INVALID_JSON_STATUS_CODE, e.getMessage());
}
}
}
}
@@ -110,9 +110,13 @@ public class PaymentStartServiceImpl implements PaymentStartService {
LOGGER.info("[startIntentPayment] outbound payload prepared txnId={} orderNo={}", txnId, orderNo);
OutboundTraceLog outboundLog = helper.createOutboundLog(txnId, requestId, apiName, BBPSConstant.UAT_PAYMENT_URL_INTENT, BBPSConstant.HTTP_POST, forwardJson);
PaymentStartRecord paymentRecord=bbpsMapperHelper.savePaymentStartRecord(request, null, txnId, orderNo, requestJson, null, null);
// call external API
Map<String, String> responseMap = httpService.postRequest(BBPSConstant.UAT_PAYMENT_URL_INTENT, forwardJson, null);
LOGGER.debug("[startIntentPayment] raw response map: {}", responseMap);
int httpCode = Integer.parseInt(responseMap.getOrDefault(BBPSConstant.RESP_CODE_KEY, String.valueOf(BBPSConstant.HTTP_INTERNAL_SERVER_ERROR)));
@@ -123,12 +127,15 @@ public class PaymentStartServiceImpl implements PaymentStartService {
if (httpCode != BBPSConstant.HTTP_OK_INT) {
helper.updateInboundLogFailure(inboundLog, respBody, String.valueOf(httpCode));
LOGGER.error("[startIntentPayment] upstream HTTP error txnId={} httpCode={} body={}", txnId, httpCode, respBody);
paymentRecord.setTxnStatus(BBPSConstant.FAILED_STR);
paymentStartRecordRepository.save(paymentRecord);
throw new CustomException(BBPSConstant.MSG_UPSTREAM_HTTP_ERROR, BBPSConstant.FAILED_STR, httpCode, respBody);
}
if (respBody == null || respBody.isEmpty()) {
helper.updateInboundLogFailure(inboundLog, BBPSConstant.MSG_EMPTY_RESPONSE_PROVIDER, String.valueOf(BBPSConstant.HTTP_INTERNAL_SERVER_ERROR));
LOGGER.error("[startIntentPayment] empty response txnId={}", txnId);
paymentRecord.setTxnStatus(BBPSConstant.FAILED_STR);
throw new CustomException(BBPSConstant.MSG_EMPTY_RESPONSE_PROVIDER, BBPSConstant.FAILED_STR, BBPSConstant.HTTP_INTERNAL_SERVER_ERROR, null);
}
@@ -210,78 +217,83 @@ public class PaymentStartServiceImpl implements PaymentStartService {
return sent;
}
@Override
public ResponseModel startWebPayment(PaymentStartUserRequest request) {
String requestId = request.getReqId();
String apiName = BBPSConstant.API_START_PAYMENT;
String txnId = helper.generateTxnId(15);
LOGGER.info("[startWebPayment] enter requestId={} txnId={} mid={}", requestId, txnId, request.getMid());
String requestId = request.getReqId();
String apiName = BBPSConstant.API_START_PAYMENT;
String txnId = helper.generateTxnId(15);
LOGGER.info("[startWebPayment] enter requestId={} txnId={} mid={}", requestId, txnId, request.getMid());
helper.validateMerchant(request.getMid());
helper.validateMerchant(request.getMid());
// inbound log
String requestJson = helper.convertObjectToJson(request);
InboundTraceLog inboundLog =
// inbound log
String requestJson = helper.convertObjectToJson(request);
InboundTraceLog inboundLog =
helper.createInboundLog(requestId, txnId, apiName, request.getMid(),
BBPSConstant.HTTP_POST, requestJson);
LOGGER.debug("[startWebPayment] inbound log created txnId={} requestId={}", txnId, requestId);
LOGGER.debug("[startWebPayment] inbound log created txnId={} requestId={}", txnId, requestId);
// Prepare request payload
PaymentDetailSentRequest sent = createPaymentSentRequest(request);
String orderNo = "ORD" + helper.generateTxnId(12);
sent.setOrderNo(orderNo);
// Prepare request payload
PaymentDetailSentRequest sent = createPaymentSentRequest(request);
String orderNo = "ORD" + helper.generateTxnId(12);
sent.setOrderNo(orderNo);
String plaintext = helper.convertObjectToJson(sent);
String encKey = paymentEncryKey;
sent.setEnckey(encKey);
String plaintext = helper.convertObjectToJson(sent);
String encKey = paymentEncryKey;
sent.setEnckey(encKey);
LOGGER.debug("[startWebPayment] plaintext prepared txnId={} orderNo={}", txnId, orderNo);
LOGGER.debug("[startWebPayment] plaintext prepared txnId={} orderNo={}", txnId, orderNo);
String encrypted = encryptionUtil.encryptMData(plaintext, encKey);
LOGGER.info("[startWebPayment] payload encrypted txnId={} orderNo={}", txnId, orderNo);
String encrypted = encryptionUtil.encryptMData(plaintext, encKey);
LOGGER.info("[startWebPayment] payload encrypted txnId={} orderNo={}", txnId, orderNo);
// ----------- BUILD x-www-form-urlencoded PAYLOAD -----------
String formPayload =
"mid=" + URLEncoder.encode(paymentMid, StandardCharsets.UTF_8) +
"&payload=" + URLEncoder.encode(encrypted, StandardCharsets.UTF_8);
// ----------- BUILD x-www-form-urlencoded PAYLOAD -----------
String formPayload =
"mid=" + URLEncoder.encode(paymentMid, StandardCharsets.UTF_8) +
"&payload=" + URLEncoder.encode(encrypted, StandardCharsets.UTF_8);
LOGGER.info("[startWebPayment] Form Payload: {}", formPayload);
OutboundTraceLog outboundLog =
helper.createOutboundLog(txnId, requestId, apiName, BBPSConstant.UAT_PAYMENT_URL_WEB,
BBPSConstant.HTTP_POST, formPayload);
LOGGER.debug("[startWebPayment] outbound log created txnId={} url={}", txnId, BBPSConstant.UAT_PAYMENT_URL_WEB);
OutboundTraceLog outboundLog =
helper.createOutboundLog(txnId, requestId, apiName, BBPSConstant.UAT_PAYMENT_URL_WEB,
BBPSConstant.HTTP_POST, formPayload);
LOGGER.debug("[startWebPayment] outbound log created txnId={} url={}", txnId, BBPSConstant.UAT_PAYMENT_URL_WEB);
PaymentStartRecord paymentRecord= bbpsMapperHelper.savePaymentStartRecord(request, null, txnId, orderNo, requestJson, null, null);
// ----------- CALL API (FORM URL-ENCODED) -----------
Map<String, String> responseMap =
httpService.postFormRequest(BBPSConstant.UAT_PAYMENT_URL_WEB, formPayload);
// ----------- CALL API (FORM URL-ENCODED) -----------
Map<String, String> responseMap = httpService.postFormRequest(BBPSConstant.UAT_PAYMENT_URL_WEB, formPayload);
LOGGER.info("[startWebPayment] Payment Start Response: {}", responseMap);
LOGGER.info("[startWebPayment] Payment Start Response: {}", responseMap);
// parse http code and response body using centralized keys
int httpCode = Integer.parseInt(responseMap.getOrDefault(BBPSConstant.RESP_CODE_KEY, String.valueOf(BBPSConstant.HTTP_INTERNAL_SERVER_ERROR)));
String respBody = responseMap.getOrDefault(BBPSConstant.RESPONSE_DATA_KEY, "");
helper.updateOutboundLogResponse(outboundLog, respBody);
LOGGER.debug("[startWebPayment] updated outbound log response txnId={} httpCode={}", txnId, httpCode);
// parse http code and response body using centralized keys
int httpCode = Integer.parseInt(responseMap.getOrDefault(BBPSConstant.RESP_CODE_KEY, String.valueOf(BBPSConstant.HTTP_INTERNAL_SERVER_ERROR)));
String respBody = responseMap.getOrDefault(BBPSConstant.RESPONSE_DATA_KEY, "");
helper.updateOutboundLogResponse(outboundLog, respBody);
LOGGER.debug("[startWebPayment] updated outbound log response txnId={} httpCode={}", txnId, httpCode);
// ---- HTTP FAILURE ----
if (httpCode != BBPSConstant.HTTP_OK_INT) {
helper.updateInboundLogFailure(inboundLog, respBody, String.valueOf(httpCode));
LOGGER.error("[startWebPayment] upstream HTTP error txnId={} httpCode={} body={}", txnId, httpCode, respBody);
throw new CustomException("Upstream HTTP Error", BBPSConstant.FAILED_STR, httpCode, respBody);
}
// ---- HTTP FAILURE ----
if (httpCode != BBPSConstant.HTTP_OK_INT) {
helper.updateInboundLogFailure(inboundLog, respBody, String.valueOf(httpCode));
LOGGER.error("[startWebPayment] upstream HTTP error txnId={} httpCode={} body={}", txnId, httpCode, respBody);
paymentRecord.setTxnStatus(BBPSConstant.FAILED_STR);
paymentStartRecordRepository.save(paymentRecord);
throw new CustomException("Upstream HTTP Error", BBPSConstant.FAILED_STR, httpCode, respBody);
}
// ---- EMPTY RESPONSE ----
if (respBody == null || respBody.isEmpty()) {
helper.updateInboundLogFailure(inboundLog, BBPSConstant.MSG_EMPTY_RESPONSE_PG, String.valueOf(BBPSConstant.HTTP_INTERNAL_SERVER_ERROR));
LOGGER.error("[startWebPayment] empty response from PG txnId={}", txnId);
throw new CustomException(BBPSConstant.MSG_EMPTY_RESPONSE_PG, BBPSConstant.FAILED_STR, BBPSConstant.HTTP_INTERNAL_SERVER_ERROR, null);
}
// ---- EMPTY RESPONSE ----
if (respBody == null || respBody.isEmpty()) {
helper.updateInboundLogFailure(inboundLog, BBPSConstant.MSG_EMPTY_RESPONSE_PG, String.valueOf(BBPSConstant.HTTP_INTERNAL_SERVER_ERROR));
LOGGER.error("[startWebPayment] empty response from PG txnId={}", txnId);
paymentRecord.setTxnStatus(BBPSConstant.FAILED_STR);
paymentStartRecordRepository.save(paymentRecord);
throw new CustomException(BBPSConstant.MSG_EMPTY_RESPONSE_PG, BBPSConstant.FAILED_STR, BBPSConstant.HTTP_INTERNAL_SERVER_ERROR, null);
}
// PG RETURNS HTML → NO JSON PARSING REQUIRED
helper.updateInboundLogSuccess(inboundLog, respBody, String.valueOf(BBPSConstant.HTTP_OK_INT));
LOGGER.info("[startWebPayment] received HTML response txnId={} length={}", txnId, respBody.length());
// PG RETURNS HTML → NO JSON PARSING REQUIRED
helper.updateInboundLogSuccess(inboundLog, respBody, String.valueOf(BBPSConstant.HTTP_OK_INT));
LOGGER.info("[startWebPayment] received HTML response txnId={} length={}", txnId, respBody.length());
// Save record with HTML (persist original request and HTML response)
// Save record with HTML (persist original request and HTML response)
String responseTypeWeb = BBPSConstant.RESPONSE_TYPE_HTML;
String rawResponseWeb = respBody == null ? "" : respBody;
@@ -289,8 +301,8 @@ public class PaymentStartServiceImpl implements PaymentStartService {
Map<String, String> parsed = parseHtmlResponse(rawResponseWeb);
// Build a minimal PaymentStartApiResponse so savePaymentStartRecord() can safely read fields
com.billpaymentservice.bbps.dto.response.PaymentStartApiResponse apiResp = new com.billpaymentservice.bbps.dto.response.PaymentStartApiResponse();
com.billpaymentservice.bbps.dto.response.PaymentStartApiResponse.ResponseData rd = new com.billpaymentservice.bbps.dto.response.PaymentStartApiResponse.ResponseData();
PaymentStartApiResponse apiResp = new PaymentStartApiResponse();
PaymentStartApiResponse.ResponseData rd = new PaymentStartApiResponse.ResponseData();
String parsedTxn = parsed.getOrDefault("txnId", "");
String parsedAmount = parsed.getOrDefault("amount", "0.00");
@@ -351,14 +363,8 @@ public class PaymentStartServiceImpl implements PaymentStartService {
LOGGER.info("[{}] Decrypted data for mid={}", apiName, mid);
// Parse decrypted JSON
Map<String, Object> payloadMap;
try {
payloadMap = objectMapper.readValue(decrypted, new TypeReference<Map<String, Object>>(){});
} catch (JsonProcessingException e) {
LOGGER.error("[{}] Failed to parse decrypted callback JSON: {}", apiName, e.getMessage(), e);
return new ResponseModel(BBPSConstant.MSG_INVALID_DECRYPTED_JSON, String.valueOf(BBPSConstant.STATUS_CODE_207), BBPSConstant.HTTP_OK_INT, null);
}
// Parse decrypted JSON (convert checked Jackson exception into unchecked CustomException so global handler can catch it)
Map<String, Object> payloadMap = parseJsonToMap(decrypted, apiName);
String txnId = String.valueOf(payloadMap.getOrDefault("txnId", payloadMap.getOrDefault("txn_id", "")));
String orderNo = String.valueOf(payloadMap.getOrDefault("orderNo", payloadMap.getOrDefault("order_no", "")));
@@ -435,30 +441,44 @@ public class PaymentStartServiceImpl implements PaymentStartService {
return new ResponseModel(BBPSConstant.MSG_CALLBACK_PROCESSED, merchantStatus, BBPSConstant.HTTP_OK_INT, null);
}
public Map<String, String> parseHtmlResponse(String html) {
Map<String, String> map = new HashMap<>();
try {
Document doc = Jsoup.parse(html);
Document doc = Jsoup.parse(html);
Element txnId = doc.selectFirst("input[name=txnId]");
Element amount = doc.selectFirst("input[name=amount]");
Element mid = doc.selectFirst("input[name=mid]");
Element txnId = doc.selectFirst("input[name=txnId]");
Element amount = doc.selectFirst("input[name=amount]");
Element mid = doc.selectFirst("input[name=mid]");
if (txnId != null) map.put("txnId", txnId.attr("value"));
if (amount != null) map.put("amount", amount.attr("value"));
if (mid != null) map.put("mid", mid.attr("value"));
if (txnId != null) map.put("txnId", txnId.attr("value"));
if (amount != null) map.put("amount", amount.attr("value"));
if (mid != null) map.put("mid", mid.attr("value"));
LOGGER.debug("[parseHtmlResponse] parsed txnId={} amount={} mid={}", map.get("txnId"), map.get("amount"), map.get("mid"));
} catch (Exception e) {
LOGGER.error("[parseHtmlResponse] error parsing HTML: {}", e.getMessage(), e);
}
LOGGER.debug("[parseHtmlResponse] parsed txnId={} amount={} mid={}", map.get("txnId"), map.get("amount"), map.get("mid"));
return map;
}
// Helper: parse JSON string into Map and rethrow Jackson checked exceptions as CustomException (unchecked)
private Map<String, Object> parseJsonToMap(String json, String apiName) {
if (json == null || json.trim().isEmpty()) {
LOGGER.error("[{}] Decrypted callback JSON is empty or null (length={})", apiName, json == null ? 0 : json.length());
throw new CustomException(BBPSConstant.MSG_INVALID_DECRYPTED_JSON, BBPSConstant.FAILED_STR, BBPSConstant.HTTP_INTERNAL_SERVER_ERROR, json);
}
// Log a short preview (avoid full sensitive data in logs)
int previewLen = Math.min(120, json.length());
String preview = json.substring(0, previewLen) + (json.length() > previewLen ? "..." : "");
LOGGER.debug("[{}] parsing decrypted JSON preview (len={}): {}", apiName, json.length(), preview);
try {
return objectMapper.readValue(json, new TypeReference<Map<String, Object>>(){});
} catch (Exception e) {
// Jackson throws JsonProcessingException / IOException; catch any parsing error and rethrow as unchecked
LOGGER.error("[{}] Failed to parse decrypted callback JSON (len={}) error={}", apiName, json.length(), e.getMessage(), e);
throw new CustomException(BBPSConstant.MSG_INVALID_DECRYPTED_JSON, BBPSConstant.FAILED_STR, BBPSConstant.HTTP_INTERNAL_SERVER_ERROR, json);
}
}
}
@@ -23,7 +23,6 @@ public class PollBackServiceImpl implements PollBackService {
this.helper = helper;
}
@Override
public ResponseModel managePollBack(PollBackRequest request) {
@@ -109,7 +109,6 @@ public class TxnHistoryServiceImpl implements TxnHistoryService {
String mid = request.getMid();
String clientUserId = request.getClientUserId();
log.info("[{}] START | reqId={} | mid={} | userId={}", apiName, requestId, mid, clientUserId);
String txnId = helper.generateTxnId(15);
String fullUrl = "this api fetch data from DB not BBPS url !";
log.info("[{}] Full URL={}", apiName, fullUrl);
@@ -147,7 +147,6 @@ public class BBPSConstant extends BBPS_RESPONSE_COD_CONSTANT {
public static final String UAT_PAYMENT_URL_WEB = "https://uat.godemo.in/api/UATIntegration/uat/payin/paymentrequest";
public static final String UAT_PAYMENT_URL_INTENT = "https://uat.godemo.in/api/UATIntegration/paymentrequest/seamless";
public static final String RESP_CODE_KEY = "respCode"; // key used by HttpService responses
public static final String RESPONSE_TYPE_HTML = "HTML";
public static final String RESPONSE_TYPE_QR = "QR";
public static final String RESPONSE_TYPE_JSON = "JSON";
@@ -1078,38 +1078,78 @@ public class BillerMapperHelper {
// Map PaymentStartUserRequest + API response into PaymentStartRecord and
// persist
public void savePaymentStartRecord(PaymentStartUserRequest request, PaymentStartApiResponse apiResponse,
String txnId, String orderNo, String requestJson, String rawResponse, String responseType) {
PaymentStartRecord record = new PaymentStartRecord();
record.setOrderNo(orderNo);
record.setRequestId(request.getReqId());
record.setClientMid(request.getMid());
record.setClientUserId(request.getClientUserId());
record.setInternalTxnId(txnId);
public PaymentStartRecord savePaymentStartRecord(
PaymentStartUserRequest request,
PaymentStartApiResponse apiResponse,
String txnId,
String orderNo,
String requestJson,
String rawResponse,
String responseType) {
if (apiResponse != null &&
apiResponse.getResponseData() != null) {
record.setAmount(Optional.ofNullable(apiResponse.getResponseData().getAmount(
)).orElse("0.00"));
record.setTxnId(Optional.ofNullable(apiResponse.getResponseData().getTxnId())
.orElse("DUMMY_TXN"));
record.setQrString(Optional.ofNullable(apiResponse.getResponseData().
getQrString()).orElse("NO_QR")); // parse createdOn string into LocalDateTime and set on Auditable
Date createdOn =parseToDate(apiResponse.getResponseData().getCreatedOn());
record.setTxnStatus("PENDING"); } else { record.setAmount("0.00");
record.setTxnStatus("PENDING"); }
// store the original request body and raw response
record.setRequestBody(requestJson);
record.setResponseBody(rawResponse);
record.setResponseType(responseType);
PaymentStartRecord record;
paymentStartRecordRepository.save(record);
boolean createNewRecord =
apiResponse == null &&
rawResponse == null &&
responseType == null;
if (createNewRecord) {
// 🔒 Duplicate check
if (paymentStartRecordRepository.findByOrderNo(orderNo).isPresent()) {
throw new CustomException(
"Duplicate OrderNo found",
"DUPLICATE_ORDERNO",
400,
"OrderNo already exists"
);
}
record = new PaymentStartRecord();
} else {
record = paymentStartRecordRepository.findByOrderNo(orderNo)
.orElseThrow(() -> new CustomException(
"OrderNo not found",
"ORDERNO_NOT_FOUND",
404,
"No record exists for given orderNo"
));
}
if (orderNo != null) {
record.setOrderNo(orderNo);
record.setRequestId(request.getReqId());
record.setClientMid(request.getMid());
record.setClientUserId(request.getClientUserId());
record.setInternalTxnId(txnId);
}
if (apiResponse != null && apiResponse.getResponseData() != null) {
record.setAmount(Optional.ofNullable(
apiResponse.getResponseData().getAmount()).orElse("0.00"));
record.setTxnId(Optional.ofNullable(
apiResponse.getResponseData().getTxnId()).orElse("DUMMY_TXN"));
record.setQrString(Optional.ofNullable(
apiResponse.getResponseData().getQrString()).orElse("NO_QR"));
Date createdOn = parseToDate(apiResponse.getResponseData().getCreatedOn());
record.setTxnStatus("PENDING");
} else {
record.setAmount("0.00");
record.setTxnStatus("PENDING");
}
// Raw request/response
record.setRequestBody(requestJson);
record.setResponseBody(rawResponse);
record.setResponseType(responseType);
return paymentStartRecordRepository.save(record);
}
// Map ComplaintRequestDTO to forward request for complaint API
public FetchComplaintForwardRequest fetchComplaintForwardRequestMap(ComplaintRequestDTO complainRequestDTO) {
FetchComplaintForwardRequest forward = new FetchComplaintForwardRequest();
@@ -29,7 +29,6 @@ public class EncryptionUtil {
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] ivBytes = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedData = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
@@ -18,6 +18,7 @@ import com.billpaymentservice.bbps.entites.BBPSMastersData;
import com.billpaymentservice.bbps.entites.BharatConnectMaster;
import com.billpaymentservice.bbps.entites.InboundTraceLog;
import com.billpaymentservice.bbps.entites.OutboundTraceLog;
import com.billpaymentservice.bbps.entites.TransactionMaster;
import com.billpaymentservice.bbps.entites.UserEntity;
import com.billpaymentservice.bbps.exception.CustomException;
import com.billpaymentservice.bbps.repository.BBPSMasterDataRepo;
@@ -225,5 +226,63 @@ public class Helper {
return userId;
}
public void mergeNonNullFields(TransactionMaster src, TransactionMaster dest) {
/*
* LOGGER.info("TransactionMaster src: {}", src);
*/ // Only copy values that are non-null (and non-blank for Strings)
if (src.getBankTxnId() != null && !src.getBankTxnId().isBlank()) dest.setBankTxnId(src.getBankTxnId());
if (src.getTxnId() != null && !src.getTxnId().isBlank()) dest.setTxnId(src.getTxnId());
if (src.getInitiatorTxnId() != null && !src.getInitiatorTxnId().isBlank()) dest.setInitiatorTxnId(src.getInitiatorTxnId());
if (src.getCheckerTxnId() != null && !src.getCheckerTxnId().isBlank()) dest.setCheckerTxnId(src.getCheckerTxnId());
if (src.getReqId() != null && !src.getReqId().isBlank()) dest.setReqId(src.getReqId());
if (src.getMid() != null && !src.getMid().isBlank()) dest.setMid(src.getMid());
if (src.getClientUserId() != null && !src.getClientUserId().isBlank()) dest.setClientUserId(src.getClientUserId());
if (src.getClientReqId() != null && !src.getClientReqId().isBlank()) dest.setClientReqId(src.getClientReqId());
if (src.getUserId() != null && !src.getUserId().isBlank()) dest.setUserId(src.getUserId());
if (src.getBillerId() != null && !src.getBillerId().isBlank()) dest.setBillerId(src.getBillerId());
if (src.getTxnAmount() != null) dest.setTxnAmount(src.getTxnAmount());
if (src.getStatus() != null && !src.getStatus().isBlank()) dest.setStatus(src.getStatus());
if (src.getPaymentInformation() != null && !src.getPaymentInformation().isBlank()) dest.setPaymentInformation(src.getPaymentInformation());
if (src.getCreationDateBank() != null) dest.setCreationDateBank(src.getCreationDateBank());
if (src.getModifiedDateBank() != null) dest.setModifiedDateBank(src.getModifiedDateBank());
if (src.getCreatedEpochDateBank() != null) dest.setCreatedEpochDateBank(src.getCreatedEpochDateBank());
if (src.getModifiedEpochDateBank() != null) dest.setModifiedEpochDateBank(src.getModifiedEpochDateBank());
/* ---- additional fields ---- */
if (src.getRefId() != null && !src.getRefId().isBlank()) dest.setRefId(src.getRefId());
if (src.getPaymentRefId() != null && !src.getPaymentRefId().isBlank()) dest.setPaymentRefId(src.getPaymentRefId());
if (src.getRemitterName() != null && !src.getRemitterName().isBlank()) dest.setRemitterName(src.getRemitterName());
if (src.getOrderId() != null && !src.getOrderId().isBlank()) dest.setOrderId(src.getOrderId());
if (src.getBillId() != null && !src.getBillId().isBlank()) dest.setBillId(src.getBillId());
if (src.getUserType() != null && !src.getUserType().isBlank()) dest.setUserType(src.getUserType());
if (src.getTotalTxnAmount() != null) dest.setTotalTxnAmount(src.getTotalTxnAmount());
if (src.getBillerCategory() != null && !src.getBillerCategory().isBlank()) dest.setBillerCategory(src.getBillerCategory());
if (src.getBillerName() != null && !src.getBillerName().isBlank()) dest.setBillerName(src.getBillerName());
if (src.getOffUsPay() != null) dest.setOffUsPay(src.getOffUsPay());
if (src.getSplitPay() != null) dest.setSplitPay(src.getSplitPay());
if (src.getQuickPay() != null) dest.setQuickPay(src.getQuickPay());
if (src.getPaymentMode() != null && !src.getPaymentMode().isBlank()) dest.setPaymentMode(src.getPaymentMode());
if (src.getAgentPaymentInformation() != null && !src.getAgentPaymentInformation().isBlank()) dest.setAgentPaymentInformation(src.getAgentPaymentInformation());
if (src.getCustConvFee() != null) dest.setCustConvFee(src.getCustConvFee());
if (src.getCurrency() != null && !src.getCurrency().isBlank()) dest.setCurrency(src.getCurrency());
if (src.getRequestedIp() != null && !src.getRequestedIp().isBlank()) dest.setRequestedIp(src.getRequestedIp());
if (src.getCustomerMobNo() != null && !src.getCustomerMobNo().isBlank()) dest.setCustomerMobNo(src.getCustomerMobNo());
if (src.getMacAddress() != null && !src.getMacAddress().isBlank()) dest.setMacAddress(src.getMacAddress());
if (src.getSplitPayAmount() != null) dest.setSplitPayAmount(src.getSplitPayAmount());
if (src.getCouCustConvFee() != null) dest.setCouCustConvFee(src.getCouCustConvFee());
if (src.getSettlementVerification() != null) dest.setSettlementVerification(src.getSettlementVerification());
if (src.getFundTxnType() != null && !src.getFundTxnType().isBlank()) dest.setFundTxnType(src.getFundTxnType());
if (src.getReason() != null && !src.getReason().isBlank()) dest.setReason(src.getReason());
if (src.getAmountTags() != null && !src.getAmountTags().isBlank()) dest.setAmountTags(src.getAmountTags());
if (src.getPlanId() != null && !src.getPlanId().isBlank()) dest.setPlanId(src.getPlanId());
if (src.getPlanType() != null && !src.getPlanType().isBlank()) dest.setPlanType(src.getPlanType());
if (src.getTxnNpciId() != null && !src.getTxnNpciId().isBlank()) dest.setTxnNpciId(src.getTxnNpciId());
/* ---- lists (direct replace when provided) ---- */
if (src.getDeviceBlockTags() != null && !src.getDeviceBlockTags().isEmpty()) dest.setDeviceBlockTags(src.getDeviceBlockTags());
if (src.getCustomerParams() != null && !src.getCustomerParams().isEmpty()) dest.setCustomerParams(src.getCustomerParams());
LOGGER.info("TransactionMaster dest after merge: {}", dest);
}
}