결제 - 키움결제 결제취소 관련 처리

This commit is contained in:
이경숙
2026-04-08 16:47:58 +09:00
parent 0bbd8e3891
commit e648e7462d
6 changed files with 265 additions and 183 deletions

View File

@@ -1553,17 +1553,19 @@ public class BOPayService{
*/
public Map<String, Object> cancelKiwoomPay(BOPayVO payVO) throws Exception {
log.debug("cancelKiwoomPay step1 payVO :::> {}", payVO);
//관련 키값 DB 조회
DataMap resultMap = selectPayLink(payVO.getSopmalCd());
//요청코드
String authKey = resultMap.get("kcpSecretKey").toString();
String cpId = resultMap.get("kcpMid").toString();
String payMethod = ""; //취소결제수단
String cancelReq = "Y"; //취소URL 요청여부
String amount = payVO.getCancelAmount(); //취소금액 //todo :: db연결해서 가져와야 함 nullCheck(request.getParameter("AUTHKEY"));
String trxId = payVO.getTno(); //거래번호
String cancelReason = payVO.getCancelReason(); //취소사유
String payMethod = ""; //취소결제수단
String cancelReq = "Y"; //취소URL 요청여부
//String TAXFREEAMT = nullCheck(request.getParameter("TAXFREEAMT")); //비과세 취소금액
if(payVO.getSetleTyCd().equals("01")) {
@@ -1572,8 +1574,8 @@ public class BOPayService{
//1차 요청코드
JSONObject obj = new JSONObject();
obj.put("cancelReason", payVO.getCancelReason()); //취소사유
obj.put("cancelAmount", payVO.getCancelAmount()); //취소금액 (금액이 없으면 전체취소)
obj.put("cancelReason", cancelReason); //취소사유
obj.put("cancelAmount", amount); //취소금액 (금액이 없으면 전체취소)
JSONObject jsonObj = new JSONObject();
jsonObj.put("CPID", cpId);
@@ -1584,134 +1586,152 @@ public class BOPayService{
jsonObj.put("CANCELREASON",cancelReason);
//jsonObj.put("TAXFREEAMT",TAXFREEAMT);
log.debug("cancelKiwoomPay step3 JSONObject ::: {}", jsonObj.toString());
//로그 저장 셋팅
JSONObject finalJObj = new JSONObject();
DataMap pgApiLogReqVO = new DataMap();
pgApiLogReqVO.put("reqParam", jsonObj.toString());
pgApiLogReqVO.put("ordrInnb", StringUtil.isNullToString(payVO.getOrderId()));
pgApiLogReqVO.put("sopmalCd", StringUtil.isNullToString(payVO.getSopmalCd()));
pgApiLogReqVO.put("pgCmpnyNm", StringUtil.isNullToString(payVO.getPgCmpnyNm()));
pgApiLogReqVO.put("mbrInnb", StringUtil.isNullToString(payVO.getMbrInnb()));
log.debug("cancelKiwoomPay step4 pgApiLogReqVO ::: {}", pgApiLogReqVO);
// ====== step 1. 취소URL 요청 ======
try{
//결제 API URL
String targetURL = "";
if(cpId.equals("CTS18056")) {
targetURL = "https://apitest.kiwoompay.co.kr/pay/ready"; //개발서버
}else{
targetURL = "https://api.kiwoompay.co.kr/pay/ready"; //운영서버
}
URL goUrl = new URL(targetURL);
//결제 API URL
String targetURL = "";
if(cpId.equals("CTS18056")) {
targetURL = "https://apitest.kiwoompay.co.kr/pay/ready"; //개발서버
}else{
targetURL = "https://api.kiwoompay.co.kr/pay/ready"; //운영서버
}
URL goUrl = new URL(targetURL);
HttpURLConnection con = (HttpURLConnection) goUrl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", authKey);
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
HttpURLConnection con = (HttpURLConnection) goUrl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", authKey);
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
writer.write("");
os.write((jsonObj.toString()).getBytes("UTF-8"));
writer.flush();
writer.close();
os.close();
con.connect();
writer.write("");
os.write((jsonObj.toString()).getBytes("UTF-8"));
writer.flush();
writer.close();
os.close();
con.connect();
//호출 결과 값
int responseCode = con.getResponseCode();
String responseMsg = con.getResponseMessage();
//호출 결과 값
int responseCode = con.getResponseCode();
String responseMsg = con.getResponseMessage();
String token = "";
String returnUrl = "";
log.debug("cancelKiwoom STEP1 승인전 responseCode ====={}",responseCode);
log.debug("cancelKiwoom STEP1 승인전 responseMsg ====={}",responseMsg);
//정상 수신 했을경우 (응답코드:200)
if(responseCode == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine = null;
StringBuffer response1 = new StringBuffer();
String token = "";
String returnUrl = "";
while((inputLine = in.readLine()) != null){
response1.append(inputLine);
//정상 수신 했을경우 (응답코드:200)
if(responseCode == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine = null;
StringBuffer response1 = new StringBuffer();
while((inputLine = in.readLine()) != null){
response1.append(inputLine);
}
in.close();
//응답 데이터 처리
String responseBody = response1.toString();
JSONObject jObj = (JSONObject)JSONValue.parse(responseBody);
token = jObj.get("TOKEN").toString();
returnUrl = jObj.get("RETURNURL").toString();
log.debug("cancelKiwoom STEP1 승인 responseBody ====={}", responseBody);
log.debug("cancelKiwoom STEP1 승인 TOKEN200 ====={}",token);
log.debug("cancelKiwoom STEP1 승인 URL200 ====={}",returnUrl);
}
in.close();
con.disconnect();
//응답 데이터 처리
String responseBody = response1.toString();
JSONObject jObj = (JSONObject)JSONValue.parse(responseBody);
token = jObj.get("TOKEN").toString();
returnUrl = jObj.get("RETURNURL").toString();
}
log.debug("cancelKiwoom STEP1 승인 TOKEN ====={}",token);
log.debug("cancelKiwoom STEP1 승인 URL ====={}",returnUrl);
con.disconnect();
// ====== step 2. 취소 승인 요청 ======
log.debug("cancelKiwoom STEP1 승인 URL ====={}",returnUrl);
targetURL = returnUrl;
goUrl = new URL(targetURL);
// ====== step 2. 취소 승인 요청 ======
con = (HttpURLConnection) goUrl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", authKey);
con.setRequestProperty("TOKEN", token);//TOKEN
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
os = con.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(os));
targetURL = returnUrl;
goUrl = new URL(targetURL);
writer.write("");
os.write((jsonObj.toString()).getBytes("EUC-KR"));
writer.flush();
writer.close();
os.close();
con.connect();
con = (HttpURLConnection) goUrl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", authKey);
con.setRequestProperty("TOKEN", token);//TOKEN
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
os = con.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(os));
//호출 결과 값
responseCode = con.getResponseCode();
responseMsg = con.getResponseMessage();
writer.write("");
os.write((jsonObj.toString()).getBytes("EUC-KR"));
writer.flush();
writer.close();
os.close();
con.connect();
//정상 수신 했을경우 (응답코드:200)
if(responseCode == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine = null;
StringBuffer response1 = new StringBuffer();
//호출 결과 값
responseCode = con.getResponseCode();
responseMsg = con.getResponseMessage();
while((inputLine = in.readLine()) != null){
response1.append(inputLine);
}
JSONObject jObj = new JSONObject();
in.close();
//정상 수신 했을경우 (응답코드:200)
if(responseCode == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine = null;
StringBuffer response1 = new StringBuffer();
while((inputLine = in.readLine()) != null){
response1.append(inputLine);
//응답 데이터 처리
String responseBody = response1.toString();
finalJObj = (JSONObject)JSONValue.parse(responseBody);
}
in.close();
con.disconnect();
//응답 데이터 처리
String responseBody = response1.toString();
log.debug("Kiwoom 결제취소 jObj::: {}", finalJObj.toString());
jObj = (JSONObject)JSONValue.parse(responseBody);
/*resultcode = checkObjNull(jObj.get("RESULTCODE")).toString();
errormessage= checkObjNull(jObj.get("ERRORMESSAGE")).toString();
pgApiLogReqVO.put("resParam", finalJObj.toString());
if(resultcode.equals("0000")){
daoutrx = checkObjNull(jObj.get("DAOUTRX")).toString();
amount = checkObjNull(jObj.get("AMOUNT")).toString();
orderno = checkObjNull(jObj.get("ORDERNO")).toString();
canceldate = checkObjNull(jObj.get("CANCELDATE")).toString();
cpname = checkObjNull(jObj.get("CPNAME")).toString();
cpurl = checkObjNull(jObj.get("CPURL")).toString();
cptelno = checkObjNull(jObj.get("CPTELNO")).toString();
}*/
}catch(Exception e){
e.printStackTrace();
} finally {
log.debug("cancelKiwoomPay finally pgApiLogReqVO ::: {}", pgApiLogReqVO);
ordrLogService.insertSetleOrderPgLog(payVO, pgApiLogReqVO);
ordrLogService.insertBOPgApiLogReqRegist(pgApiLogReqVO);
}
con.disconnect();
JSONObject finalJObj = jObj;
return new HashMap<>() {{
put("response", finalJObj);
}};
Map<String, Object> result = new HashMap<>();
result.put("response", finalJObj.toString());
return result;
}
}

View File

@@ -1127,79 +1127,25 @@ public class BORtngudrefndService {
log.info("kiwoom api 전달 파라미터 확인 : {}", payVO);
setleCancelResultMessage = payService.cancelKiwoomPay(payVO);
log.info("결제 취소 API 결과 확인 : {}", setleCancelResultMessage);
log.info("결제 취소 API 결과 확인 : {}", setleCancelResultMessage.get("response"));
log.info("결제 취소 API 결과 확인 RESULTCODE : {}", setleCancelResultMessage.get("RESULTCODE"));
log.info("결제 취소 API 결과 확인 ERRORMESSAGE : {}", setleCancelResultMessage.get("ERRORMESSAGE"));
/*resultcode = checkObjNull(jObj.get("RESULTCODE")).toString();
errormessage= checkObjNull(jObj.get("ERRORMESSAGE")).toString();
if(resultcode.equals("0000")){
daoutrx = checkObjNull(jObj.get("DAOUTRX")).toString();
amount = checkObjNull(jObj.get("AMOUNT")).toString();
orderno = checkObjNull(jObj.get("ORDERNO")).toString();
canceldate = checkObjNull(jObj.get("CANCELDATE")).toString();
cpname = checkObjNull(jObj.get("CPNAME")).toString();
cpurl = checkObjNull(jObj.get("CPURL")).toString();
cptelno = checkObjNull(jObj.get("CPTELNO")).toString();
}*/
responseMap = (Map<String, Object>) setleCancelResultMessage.get("response");
// String jsonString = (String) setleCancelResultMessage.get("response");
// ObjectMapper objectMapper = new ObjectMapper();
// responseMap = objectMapper.readValue(jsonString, Map.class);
log.info("리스펀스 결과 : {}", responseMap);
log.info("리스펀스 결과 값 : {}", responseMap.get("res_cd"));
log.info("결제 취소 API 결과 확인 response : {}", setleCancelResultMessage.get("response"));
String jsonString = (String) setleCancelResultMessage.get("response");
ObjectMapper objectMapper = new ObjectMapper();
responseMap = objectMapper.readValue(jsonString, Map.class);
log.debug("리스펀스 결과 : {}", responseMap);
log.info("리스펀스 결과 값 : {}", responseMap.get("status"));
log.info("리스펀스 결과 값 : {}", responseMap.get("RESULTCODE"));
if ("0000".equals(responseMap.get("res_cd"))) {
// 8729 : 기 취소된 거래
if ("0000".equals(responseMap.get("RESULTCODE"))) {
// 0000 : 취소성공
log.debug("0000");
message.put("setleStatus", responseMap.get("res_cd"));
message.put("setleMessage", responseMap.get("res_msg"));
message = refundCancelCashReceipt(setle, ordrSetleInnb, sopmalCd, receiptCancelAmt, refundModeTypeSales, updusrDvCd, updusr); // 현금영수증 취소
if (!"0000".equals(message.get("cashReceiptStatus"))) {
logDtlCn = "현금영수증 취소에 실패하였습니다.";
// throw new WnbtRestException("현금영수증 취소에 실패하였습니다."); // TODO : 현금영수증 취소 실패해도 트렌젝션 걸러야하는지 확인 필요
}
message.put("setleStatus", responseMap.get("RESULTCODE"));
message.put("setleMessage", responseMap.get("ERRORMESSAGE"));
} else {
if ("8729".equals(responseMap.get("res_cd"))) { // 계좌이체 기 취소된 거래
logDtlCn = String.valueOf(responseMap.get("res_msg"));
// throw new WnbtRestException(logDtlCn);
} else if ("8332".equals(responseMap.get("res_cd"))) { // 이미 사용중지된 가상계좌 사용중지요청
logDtlCn = String.valueOf(responseMap.get("res_msg"));
throw new WnbtRestException(logDtlCn);
} else if ("8133".equals(responseMap.get("res_cd"))) { // 기취소된 신용카드 거래 취소요청
logDtlCn = String.valueOf(responseMap.get("res_msg"));
// throw new WnbtRestException(logDtlCn);
} else if ("8317".equals(responseMap.get("res_cd"))) { // 가상계좌 환불 불가상태
logDtlCn = String.valueOf(responseMap.get("res_msg"));
throw new WnbtRestException(logDtlCn);
} else if ("5002".equals(responseMap.get("res_cd"))) { // 취소 불가 상태 (에스크로일 경우 '구매확인' 이후 처리가 가능해서 5002 에러가 들어옴
if ("05".equals(setle.getSetleTyCd()) || "06".equals(setle.getSetleTyCd())) {
logDtlCn = String.valueOf(responseMap.get("res_msg") + "\n에스크로 결제의 경우, 배송 완료 후 수령자 이메일에 있는 '구매확인' 버튼을 눌러야 취소가 가능합니다.");
} else {
logDtlCn = String.valueOf(responseMap.get("res_msg"));
}
throw new WnbtRestException(logDtlCn);
} else {
log.debug("1111");
message.put("setleStatus", responseMap.get("res_cd"));
message.put("setleMessage", responseMap.get("res_msg"));
logDtlCn = "잘못된 요청입니다. 관리자에게 문의하세요.";
throw new WnbtRestException("잘못된 요청입니다. 관리자에게 문의하세요.");
}
log.debug("1111");
message.put("setleStatus", responseMap.get("RESULTCODE"));
message.put("setleMessage", responseMap.get("ERRORMESSAGE"));
logDtlCn = "잘못된 요청입니다. 관리자에게 문의하세요.";
throw new WnbtRestException("잘못된 요청입니다. 관리자에게 문의하세요.");
}
}

View File

@@ -644,7 +644,7 @@ public class PayController {
}
@Policy(AuthPolicy.RESTRICTED)
@RequestMapping(value="/selectKiwoomSample2")
@RequestMapping(value="/selectKiwoomApiSample")
public String selectKiwoonPay2(ModelMap model) throws Exception {
log.debug("selectKiwoonPay = {}");
return "sopmal/ordr/PayKiwoomPay2C";
@@ -710,9 +710,9 @@ public class PayController {
*/
@Policy(AuthPolicy.RESTRICTED)
@RequestMapping(value="/kiwoomPaySuccss")
public String confirmPaymentkiwoom(HttpServletRequest request, ModelMap model) throws Exception {
public String confirmPaymentKiwoom(HttpServletRequest request, ModelMap model) throws Exception {
System.out.println("콜백 수신 ::: "+request.getQueryString());
System.out.println("성공결과페이지 ::: "+request.getQueryString());
BOPayVO payVO = new BOPayVO();
@@ -722,15 +722,6 @@ public class PayController {
payVO.setPayMethod(request.getParameter("PAYMETHOD"));
Map<String, Object> message = new HashMap<>();
/*String sopmalCd = payVO.getSopmalCd();
try {
message = service.insertKcpPay(payVO);
} catch (Exception e) {
message = new HashMap<>() {{
put("response", "결제를 실패하였습니다.\n관리자에게 문의하시기 바랍니다.");
}};
}*/
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", payVO.getCode());
@@ -740,11 +731,66 @@ public class PayController {
message.put("response",jsonObject.toString());
model.addAttribute("message", message);
// responseHandler.handleResponse(
// sendToResrc.ofPost(RESRC.GCONEBO, "/gcone/ordr/pay/kcpPayProc", payVO),
// model,
// "message"
// );
return "sopmal/ordr/PayKiwoomSucsC";
}
/**
* 키움 결제취소 화면
* @return PayKiwoomModC.jsp
* @author 이경숙
*/
@Policy(AuthPolicy.RESTRICTED)
@RequestMapping(value="/selectKiwoomCancelSample")
public String selectKiwoomCancel(ModelMap model) throws Exception {
log.debug("selectKiwoomCancel = {}");
return "sopmal/ordr/PayKiwoomModC";
}
/**
* 키움 결제 연계처리 - 결체취소결과페이지
* @return PayKiwoomSucsC.jsp
* @author 이경숙
*/
@Policy(AuthPolicy.RESTRICTED)
@RequestMapping(value="/kiwoomPayCancel")
public String confirmCancelKiwoom(HttpServletRequest request, ModelMap model) throws Exception {
System.out.println("취소데이터 수신 ::: "+request.getQueryString());
Map<String, Object> setleCancelResultMessage = new HashMap<>();
Map<String, Object> responseMap = new HashMap<>();
BOPayVO payVO = new BOPayVO();
payVO.setSopmalCd("SK");
payVO.setOrderId(request.getParameter("ORDERNO"));
payVO.setCancelAmount(request.getParameter("AMOUNT"));
payVO.setPayMethod(request.getParameter("PAYMETHOD"));
payVO.setTno(request.getParameter("TRXID"));
payVO.setCancelReason(request.getParameter("CANCELREASON"));
payVO.setSetleTyCd("01");
payVO.setPgCmpnyNm("kiwoom");
log.debug("confirmCancelKiwoom step1 payVO :::> {}", payVO);
Map<String, Object> message = new HashMap<>();
setleCancelResultMessage = service.cancelKiwoomPay(payVO);
String responseStr = (String) setleCancelResultMessage.get("response");
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(responseStr);
jsonObject.put("orderId", payVO.getOrderId());
jsonObject.put("amount", payVO.getAmount());
jsonObject.put("payMethod", payVO.getPayMethod());
jsonObject.put("code", jsonObject.get("RESULTCODE"));
message.put("response",jsonObject.toString());
model.addAttribute("message", message);
return "sopmal/ordr/PayKiwoomSucsC";
}