Initial commit

This commit is contained in:
binz 2026-11-18 02:00:09 +00:00
commit 217720e4e4
45 changed files with 3567 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
*.zip
target/
.idea/
*.iml
.vscode/

67
pom.xml Normal file
View File

@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/>
</parent>
<groupId>com.bccard.tsp</groupId>
<artifactId>tsp-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tsp-core</name>
<description>Spring Boot Card Identification Visitor Pattern Project (Java 1.8)</description>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,14 @@
package com.bccard.tsp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync
@SpringBootApplication
public class TspCoreApplication {
public static void main(String[] args) {
SpringApplication.run(TspCoreApplication.class, args);
}
}

View File

@ -0,0 +1,61 @@
package com.bccard.tsp.adapt.bxi;
import com.bccard.tsp.adapt.bxi.mci.MciHandler;
import com.bccard.tsp.adapt.bxi.mci.MciVo;
import com.bccard.tsp.common.Result;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* [BXI 통합 라우터]
* - 서비스 계층이 넘긴 전문 VO(MciVo 등)의 타입을 판별하여 전용 채널 맵(MCI, FEP 등)의 핸들러로 라우팅한다.
*/
@Component
public class BxiRouter {
/** MCI 요청 Class -> 전담 MciHandler 매핑 맵 */
@SuppressWarnings("rawtypes")
private final Map<Class<?>, MciHandler> mciHandlerMap = new HashMap<Class<?>, MciHandler>();
/**
* 스프링에 등록된 모든 MciHandler 빈들을 리스트로 자동 주입받아 mciHandlerMap에 등록한다.
*/
public BxiRouter(List<MciHandler<?, ?>> mciHandlers) {
if (mciHandlers != null) {
for (MciHandler<?, ?> handler : mciHandlers) {
mciHandlerMap.put(handler.getReqClass(), handler);
}
}
}
/**
* MCI 전문 송신 함수
* 파라미터로 Object 대신 MciVo를 직접 받아 컴파일 타임에 타입 안전성을 보장한다.
*
* @param req MCI 요청 전문 VO (MCDTCO0SH003999.In, MCDTCO0SH004050.In 등)
* @param resClass 기대하는 응답 전문 타입
* @return Result<RES>
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public <RES> Result<RES> send(MciVo req, Class<RES> resClass) {
if (req == null) {
return Result.fail("MCI_REQ_NULL", "MCI 요청 데이터(MciVo)가 null입니다.");
}
MciHandler handler = mciHandlerMap.get(req.getClass());
if (handler == null) {
return Result.fail("MCI_HANDLER_NOT_FOUND",
"등록되지 않은 MCI 요청 전문 타입입니다: " + req.getClass().getSimpleName());
}
if (!handler.getResClass().equals(resClass)) {
return Result.fail("MCI_RES_TYPE_MISMATCH",
"MCI 응답 타입 불일치: 기대=" + resClass.getSimpleName() + ", 명세=" + handler.getResClass().getSimpleName());
}
return (Result<RES>) handler.send(req);
}
}

View File

@ -0,0 +1,22 @@
package com.bccard.tsp.adapt.bxi.mci;
import com.bccard.tsp.common.Result;
/**
* [MCI 네트워크 통신 클라이언트 인터페이스]
* 핸들러와 실제 물리적인 통신(BXI, Mock 등) 구현체를 분리하여
* 네트워크 전송 방식 변경 시 클라이언트 구현체만 교체할 수 있도록 한다.
*/
public interface MciClient {
/**
* 전문 송수신 실행
*
* @param intfId 인터페이스 식별자 (예: "MCDTCO0SH003999", "MCDTCO0SH004050")
* @param usrId 트랜잭션 ID 또는 사용자 식별자
* @param reqVo 요청 전문 VO
* @param resClass 기대하는 응답 전문 VO 클래스
* @return Result<RES> 역직렬화된 응답 전문 VO 결과
*/
<RES> Result<RES> call(String intfId, String usrId, Object reqVo, Class<RES> resClass);
}

View File

@ -0,0 +1,27 @@
package com.bccard.tsp.adapt.bxi.mci;
import com.bccard.tsp.common.Result;
/**
* [MCI 전문 통신 핸들러 공통 인터페이스]
*
* @param <REQ> 요청 전문 VO 타입 (In)
* @param <RES> 응답 전문 VO 타입 (Out)
*/
public interface MciHandler<REQ, RES> {
/**
* BXI 통신을 전송하고 응답 결과를 반환한다.
*/
Result<RES> send(REQ req);
/**
* 처리 대상 요청 전문 VO Class
*/
Class<REQ> getReqClass();
/**
* 기대하는 응답 전문 VO Class
*/
Class<RES> getResClass();
}

View File

@ -0,0 +1,8 @@
package com.bccard.tsp.adapt.bxi.mci;
/**
* [MCI 전문 마커 인터페이스]
* MCI 통신에 사용되는 요청/응답 전문 VO의 최상위 마커 인터페이스
*/
public interface MciVo {
}

View File

@ -0,0 +1,80 @@
package com.bccard.tsp.adapt.bxi.mci.handler;
import com.bccard.tsp.adapt.bxi.mci.MciClient;
import com.bccard.tsp.adapt.bxi.mci.MciHandler;
import com.bccard.tsp.adapt.bxi.mci.vo.MCDTCO0SH003999;
import com.bccard.tsp.common.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* [MCI 3999 전문 통신 핸들러]
* Ci(2~8), Bizno(2~8), ApplyNo(9), OldToken(A), Foreigner(C)가 공통으로 사용하는
* MCDTCO0SH003999 전문의 통신 호출 및 응답코드 검증 전담 빈.
* 구체 클래스 BxiMciClient 대신 MciClient 인터페이스를 주입받아 통신 구현체와 분리된다.
*/
@Component
@RequiredArgsConstructor
public class Mci3999Handler implements MciHandler<MCDTCO0SH003999.In, MCDTCO0SH003999.Out> {
private static final String MCI_SUCCESS_RAW_CODE = "00";
private static final String INTN_SUCCESS_CODE = "0000";
private static final Map<String, String> CODE_MAP;
static {
Map<String, String> map = new HashMap<String, String>();
map.put("00", "0000");
map.put("01", "50101");
map.put("02", "50102");
map.put("99", "50999");
CODE_MAP = Collections.unmodifiableMap(map);
}
private final MciClient mciClient;
@Override
public Class<MCDTCO0SH003999.In> getReqClass() {
return MCDTCO0SH003999.In.class;
}
@Override
public Class<MCDTCO0SH003999.Out> getResClass() {
return MCDTCO0SH003999.Out.class;
}
/**
* 3999 요청 전문(mciIn)을 MciClient를 통해 전송하고,
* 응답코드 검증 후 응답 전문(MCDTCO0SH003999.Out)을 반환한다.
*/
@Override
public Result<MCDTCO0SH003999.Out> send(MCDTCO0SH003999.In mciIn) {
if (mciIn == null) {
return Result.fail("BXI_REQ_NULL", "3999 요청 데이터(mciIn)가 null입니다.");
}
return mciClient.call(MCDTCO0SH003999.IF_ID, mciIn.getTridV32(), mciIn, getResClass())
.flatMap(this::verifyResponseCode);
}
private Result<MCDTCO0SH003999.Out> verifyResponseCode(MCDTCO0SH003999.Out out) {
String rawResultCd = out.getGetPrfRsltCdV2();
String intnCode = MCI_SUCCESS_RAW_CODE.equals(rawResultCd)
? INTN_SUCCESS_CODE
: toIntnCode(rawResultCd);
if (!INTN_SUCCESS_CODE.equals(intnCode)) {
return Result.fail(intnCode, "MCI 카드 인증 실패 (결과코드: " + rawResultCd + ")");
}
return Result.ok(out);
}
private String toIntnCode(String rawCode) {
if (rawCode == null) return "50999";
String mapped = CODE_MAP.get(rawCode);
return mapped != null ? mapped : "50999";
}
}

View File

@ -0,0 +1,80 @@
package com.bccard.tsp.adapt.bxi.mci.handler;
import com.bccard.tsp.adapt.bxi.mci.MciClient;
import com.bccard.tsp.adapt.bxi.mci.MciHandler;
import com.bccard.tsp.adapt.bxi.mci.vo.MCDTCO0SH004050;
import com.bccard.tsp.common.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* [MCI 4050 전문 통신 핸들러]
* BcMoney(선불 머니카드: Type 3, 4, 5)가 사용하는
* MCDTCO0SH004050 전문의 통신 호출 및 응답코드 검증 전담 빈.
* 구체 클래스 BxiMciClient 대신 MciClient 인터페이스를 주입받아 통신 구현체와 분리된다.
*/
@Component
@RequiredArgsConstructor
public class Mci4050Handler implements MciHandler<MCDTCO0SH004050.In, MCDTCO0SH004050.Out> {
private static final String MCI_SUCCESS_RAW_CODE = "00";
private static final String INTN_SUCCESS_CODE = "0000";
private static final Map<String, String> CODE_MAP;
static {
Map<String, String> map = new HashMap<String, String>();
map.put("00", "0000");
map.put("01", "50101");
map.put("02", "50102");
map.put("99", "50999");
CODE_MAP = Collections.unmodifiableMap(map);
}
private final MciClient mciClient;
@Override
public Class<MCDTCO0SH004050.In> getReqClass() {
return MCDTCO0SH004050.In.class;
}
@Override
public Class<MCDTCO0SH004050.Out> getResClass() {
return MCDTCO0SH004050.Out.class;
}
/**
* 4050 요청 전문(mciIn)을 MciClient를 통해 전송하고,
* 응답코드 검증 후 응답 전문(MCDTCO0SH004050.Out)을 반환한다.
*/
@Override
public Result<MCDTCO0SH004050.Out> send(MCDTCO0SH004050.In mciIn) {
if (mciIn == null) {
return Result.fail("BXI_REQ_NULL", "4050 요청 데이터(mciIn)가 null입니다.");
}
return mciClient.call(MCDTCO0SH004050.IF_ID, mciIn.getTridV32(), mciIn, getResClass())
.flatMap(this::verifyResponseCode);
}
private Result<MCDTCO0SH004050.Out> verifyResponseCode(MCDTCO0SH004050.Out out) {
String rawResultCd = out.getGetPrfRsltCdV2();
String intnCode = MCI_SUCCESS_RAW_CODE.equals(rawResultCd)
? INTN_SUCCESS_CODE
: toIntnCode(rawResultCd);
if (!INTN_SUCCESS_CODE.equals(intnCode)) {
return Result.fail(intnCode, "머니카드 MCI 인증 실패 (결과코드: " + rawResultCd + ")");
}
return Result.ok(out);
}
private String toIntnCode(String rawCode) {
if (rawCode == null) return "50999";
String mapped = CODE_MAP.get(rawCode);
return mapped != null ? mapped : "50999";
}
}

View File

@ -0,0 +1,66 @@
package com.bccard.tsp.adapt.bxi.mci.impl;
import com.bccard.tsp.adapt.bxi.mci.MciClient;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.common.mci.BxiHeaderIn;
import com.bccard.tsp.common.mci.BxiMessage;
import com.bccard.tsp.common.mci.TspRequestComponent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* [BXI 기반 MCI 통신 클라이언트 구현체]
* MciClient 인터페이스의 BXI 프로토콜 구현체로서,
* TspRequestComponent를 통해 실제 BXI 전문 패킷 생성 및 송수신을 수행한다.
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class BxiMciClient implements MciClient {
private final TspRequestComponent tspRequestComponent;
/**
* BXI 표준 헤더 조립, 직렬화, 네트워크 전송, 응답 역직렬화(toVo)까지를 일괄 수행한다.
*
* @param intfId 인터페이스 식별자
* @param usrId 트랜잭션 ID 또는 사용자 식별자
* @param reqVo 요청 전문 VO
* @param resClass 기대하는 응답 전문 VO 클래스
* @return Result<RES> 역직렬화된 응답 전문 VO 결과
*/
@Override
public <RES> Result<RES> call(String intfId, String usrId, Object reqVo, Class<RES> resClass) {
if (reqVo == null) {
return Result.fail("BXI_REQ_NULL", intfId + " 요청 데이터가 null입니다.");
}
try {
// 1. BXI 헤더 조립 및 JSON 직렬화
BxiHeaderIn headerIn = BxiHeaderIn.builder()
.ifId(intfId)
.usrId(usrId)
.build();
String reqJson = tspRequestComponent.makeBxiJson(headerIn, reqVo);
if (reqJson == null || reqJson.trim().isEmpty()) {
return Result.fail("BXI_REQ_EMPTY", "요청 JSON 데이터가 비어있습니다.");
}
// 2. 네트워크 송수신
String rspJson = tspRequestComponent.sendMci(reqJson);
// 3. 응답 역직렬화
Map<String, Object> parsedMap = BxiMessage.parseMessage(rspJson);
RES out = BxiMessage.toVo(parsedMap, resClass);
if (out == null) {
return Result.fail("MCI_COMM_ERR", intfId + " 응답 데이터 변환 결과가 null입니다.");
}
return Result.ok(out);
} catch (Exception e) {
log.error("[BxiMciClient] BXI 대외 통신 처리 실패 - intfId={}", intfId, e);
return Result.fail("MCI_COMM_ERR", intfId + " 통신/파싱 실패: " + e.getMessage(), e);
}
}
}

View File

@ -0,0 +1,159 @@
package com.bccard.tsp.adapt.bxi.mci.vo;
import com.bccard.tsp.adapt.bxi.mci.MciVo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* [MCDTCO0SH003999 전문 규격 및 VO]
*/
public final class MCDTCO0SH003999 {
public static final String IF_ID = "MCDTCO0SH003999";
private MCDTCO0SH003999() {
}
/**
* MCDTCO0SH003999 MCI 요청 전문 VO
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class In implements MciVo {
/** 인증구분코드 (1자리: 2, 3, 4, 5, 6, 8, 9, A, C) */
private String prfDvV1;
/** 카드번호 (19자리) */
private String cardNov19;
/** 유효기한 (6자리) */
private String valdTlmV6;
/** 카드비밀번호 */
private String cardPwdV20;
/** CVC2 (3자리) */
private String cvc2V3;
/** 신청번호 (15자리) */
private String aplcNov15;
/** 구토큰 (19자리) */
private String oldTokenV19;
/** 연계정보 CI (88자리) */
private String ciV88;
/** 사업자등록번호 (10자리) */
private String bizNov10;
/** 외국인식별정보 (13자리) */
private String frnrIdInfoV13;
/** 회원사번호 (4자리) */
private String memcNov4;
/** 트랜잭션 ID (32자리) */
private String tridV32;
/** 요청일시 (14자리) */
private String reqTimeV14;
/** 암호화방식구분코드 (1자리) */
private String encMthdDvV1;
/** 증빙예외구분코드 (1자리) */
private String prfExcpDvV1;
}
/**
* MCDTCO0SH003999 MCI 응답 전문 VO
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class Out implements MciVo {
/** 인증결과코드 (2자리: "00" 정상) */
private String getPrfRsltCdV2;
/** 출력카드번호 (19자리) */
private String outpCardNov19;
/** 입력에코 카드번호 (19자리) */
private String cardNov19;
/** 유효기한 (6자리) */
private String valdTlmV6;
/** 회원사번호 (4자리) */
private String memcNov4;
/** 연계정보 CI (88자리) */
private String ciV88;
/** 사업자등록번호 (10자리) */
private String bizNov10;
/** 고객구분코드 (1자리) */
private String cucoDvCdV1;
/** 카드상품코드 (6자리) */
private String cardPrdCdV6;
/** 카드브랜드코드 (2자리) */
private String cardBrndCdV2;
/** 카드유형코드 (1자리) */
private String cardTypCdV1;
/** 신용체크구분코드 (1자리) */
private String crdtChkDvCdV1;
/** 법인개인구분코드 (1자리) */
private String corpIndvDvCdV1;
/** 가족카드여부 (1자리) */
private String famCardYnV1;
/** 카드상태코드 (2자리) */
private String cardStusCdV2;
/** 발급은행코드 (3자리) */
private String issBankCdV3;
/** 결제계좌은행코드 (3자리) */
private String acntBankCdV3;
/** 휴대폰번호 (12자리) */
private String mobTelNov12;
/** 고객명 (40자리) */
private String custNmV40;
/** 생년월일 (8자리) */
private String brthDtV8;
/** 성별코드 (1자리) */
private String sexCdV1;
/** 외국인여부 (1자리) */
private String frnrYnV1;
/** 토큰발급가능여부 (1자리) */
private String tknIssPsblYnV1;
/** 불능사유 (30자리) */
private String incpRsonV30;
/** 한글성명 (40자리) */
private String hghNmV40;
/** 업체번호 (7자리) */
private String firmNoV7;
}
}

View File

@ -0,0 +1,105 @@
package com.bccard.tsp.adapt.bxi.mci.vo;
import com.bccard.tsp.adapt.bxi.mci.MciVo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* [MCDTCO0SH004050 머니카드 전문 규격 및 VO]
*/
public final class MCDTCO0SH004050 {
public static final String IF_ID = "MCDTCO0SH004050";
private MCDTCO0SH004050() {
}
/**
* MCDTCO0SH004050 머니카드 MCI 요청 전문 VO
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class In implements MciVo {
/** 인증구분코드 (1자리: 3, 4, 5) */
private String prfDvV1;
/** 카드번호 (19자리) */
private String cardNov19;
/** 머니카드 권종번호 */
private String mnyTypNov10;
/** 유효기한 (6자리) */
private String valdTlmV6;
/** 카드비밀번호 */
private String cardPwdV20;
/** CVC2 (3자리) */
private String cvc2V3;
/** 연계정보 CI (88자리) */
private String ciV88;
/** 트랜잭션 ID (32자리) */
private String tridV32;
}
/**
* MCDTCO0SH004050 머니카드 MCI 응답 전문 VO
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class Out implements MciVo {
/** 인증결과코드 (2자리: "00" 정상) */
private String getPrfRsltCdV2;
/** 출력카드번호 (19자리) */
private String outpCardNov19;
/** 입력에코 카드번호 (19자리) */
private String cardNov19;
/** 유효기한 (6자리) */
private String valdTlmV6;
/** 회원사번호 (4자리) */
private String memcNov4;
/** 연계정보 CI (88자리) */
private String ciV88;
/** 머니카드 권종번호 */
private String mnyTypNov10;
/** 카드상품코드 (6자리) */
private String cardPrdCdV6;
/** 카드브랜드코드 (2자리) */
private String cardBrndCdV2;
/** 카드유형코드 (1자리) */
private String cardTypCdV1;
/** 카드상태코드 (2자리) */
private String cardStusCdV2;
/** 발급은행코드 (3자리) */
private String issBankCdV3;
/** 고객명 (40자리) */
private String custNmV40;
/** 휴대폰번호 (12자리) */
private String mobTelNov12;
/** 토큰발급가능여부 (1자리) */
private String tknIssPsblYnV1;
}
}

View File

@ -0,0 +1,18 @@
package com.bccard.tsp.adapt.history;
import com.bccard.tsp.vo.IdnvCtnt;
/**
* [카드 본인인증 이력 레코드 저장소 인터페이스]
* - 어댑터 계층(adapt.history)의 진입점
* - 비즈니스 계층(핸들러)은 이 인터페이스에만 의존하여 이력을 적재한다.
*/
public interface CardIdentifyHistoryRecorder {
/**
* 카드 본인인증 연계내역 이력을 적재한다.
*
* @param idnvCtnt 본인인증 이력 VO
*/
void record(IdnvCtnt idnvCtnt);
}

View File

@ -0,0 +1,19 @@
package com.bccard.tsp.adapt.history.event;
import com.bccard.tsp.vo.IdnvCtnt;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
/**
* [카드 본인인증 이력 적재 이벤트 DTO]
* - 핸들러가 MCI 전문 송수신 후 발행하는 불변 이벤트 객체
*/
@Getter
@ToString
@RequiredArgsConstructor
public class CardIdentifyEvent {
/** 카드 본인인증 연계내역 이력 VO */
private final IdnvCtnt idnvCtnt;
}

View File

@ -0,0 +1,41 @@
package com.bccard.tsp.adapt.history.impl;
import com.bccard.tsp.adapt.history.CardIdentifyHistoryRecorder;
import com.bccard.tsp.adapt.history.event.CardIdentifyEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* [카드 본인인증 이력 이벤트 리스너 (동기 실행)]
* - 핸들러가 발행한 CardIdentifyEvent를 동기(@EventListener)로 수신하여
* 호출 스레드 컨텍스트(MDC/trid 등)를 안전하게 유지하며 CardIdentifyHistoryRecorder에 위임한다.
* - 비동기 스레드풀 고갈이나 유실 위험이 없으며, 핸들러와 이력 적재 계층 간의 느슨한 결합(IoC)을 완벽히 유지한다.
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class CardIdentifyHistoryListener {
private final CardIdentifyHistoryRecorder historyRecorder;
/**
* CardIdentifyEvent 수신 후 CardIdentifyHistoryRecorder를 통해 안정적으로 DB 적재 처리
*
* @param event 카드 본인인증 이력 이벤트
*/
@EventListener
public void onCardIdentifyEvent(CardIdentifyEvent event) {
if (event == null || event.getIdnvCtnt() == null) {
return;
}
try {
historyRecorder.record(event.getIdnvCtnt());
} catch (Exception e) {
log.error("[CardIdentifyHistoryListener] 이력 적재 위임 중 예외 발생 - ifId={}, trid={}",
event.getIdnvCtnt().getIfId(), event.getIdnvCtnt().getTrid(), e);
}
}
}

View File

@ -0,0 +1,58 @@
package com.bccard.tsp.adapt.history.impl;
import com.bccard.tsp.adapt.history.CardIdentifyHistoryRecorder;
import com.bccard.tsp.vo.IdnvCtnt;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
/**
* [카드 본인인증 이력 DB 적재 저장소 구현체]
* - 핸들러가 조립하여 전달한 IdnvCtnt를 받아
* 내부 코드로 변환된 메시지를 매핑하고
* idnvServiceMapper.insertLkgCtnt(idnvCtnt)를 통해 DB에 적재한다.
*/
@Slf4j
@Repository
@RequiredArgsConstructor
public class DbCardIdentifyHistoryRecorder implements CardIdentifyHistoryRecorder {
private final IdnvServiceMapper idnvServiceMapper;
/**
* 핸들러가 조립한 IdnvCtnt를 받아 내부 메시지 매핑 후 DB에 적재한다.
*
* @param idnvCtnt 카드 본인인증 이력 VO
*/
@Override
public void record(IdnvCtnt idnvCtnt) {
if (idnvCtnt == null) {
return;
}
try {
// 내부 코드로 변환된 메시지 조회 (DB 함수 조회)
if (idnvCtnt.getIntnMsg() == null && idnvCtnt.getIntnCd() != null) {
try {
String intnMsg = idnvServiceMapper.selectMessageByCode(idnvCtnt.getIntnCd());
if (intnMsg != null && !intnMsg.trim().isEmpty()) {
idnvCtnt.setIntnMsg(intnMsg);
}
} catch (Exception e) {
log.warn("[DbCardIdentifyHistoryRecorder] selectMessageByCode 조회 실패 - intnCd={}", idnvCtnt.getIntnCd(), e);
}
}
if (idnvCtnt.getRegDtim() == null) {
idnvCtnt.setRegDtim(LocalDateTime.now());
}
idnvServiceMapper.insertLkgCtnt(idnvCtnt);
log.info("[DbCardIdentifyHistoryRecorder] 이력 적재 완료 - ifId={}, trid={}, intnCd={}",
idnvCtnt.getIfId(), idnvCtnt.getTrid(), idnvCtnt.getIntnCd());
} catch (Exception e) {
log.error("insertLkgCtnt", e);
}
}
}

View File

@ -0,0 +1,29 @@
package com.bccard.tsp.adapt.history.impl;
import com.bccard.tsp.vo.IdnvCtnt;
import org.apache.ibatis.annotations.Mapper;
/**
* [카드 본인인증 이력 MyBatis 매퍼 인터페이스]
*/
@Mapper
public interface IdnvServiceMapper {
/**
* 카드 본인인증 연계내역 이력(TB_IDNV_LKG_CTNTN) 적재
*
* @param idnvCtnt 본인인증 이력 VO
* @return 저장 건수
*/
int insertLkgCtnt(IdnvCtnt idnvCtnt);
int insertLkgCtntn(IdnvCtnt idnvCtnt);
/**
* 내부 오류코드에 매핑된 메시지 조회 (DB 조회 함수)
*
* @param intnCd 내부 코드
* @return 내부 매핑 메시지
*/
String selectMessageByCode(String intnCd);
}

View File

@ -0,0 +1,171 @@
package com.bccard.tsp.common;
import java.util.Objects;
import java.util.function.Function;
/**
* 성공/실패 여부, 응답 코드/메시지, 예외 객체(Throwable), 발생 위치(Caller/Source Method),
* 그리고 결과 데이터(실패 시 부분/조회 결과 포함)를 안전하게 전달하는 함수형 결과 래퍼 (Java 1.8 호환)
*/
public final class Result<T> {
private final boolean success;
private final T value;
private final String errorCode;
private final String errorMessage;
private final Throwable exception;
private final String sourceMethod; // 호출된 이전 수행 함수/메서드 정보 (예: "PaymentTokenCheckService.verifyNotAlreadyRegistered")
private Result(boolean success, T value, String errorCode, String errorMessage, Throwable exception, String sourceMethod) {
this.success = success;
this.value = value;
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.exception = exception;
this.sourceMethod = (sourceMethod != null) ? sourceMethod : resolveCallerMethod();
}
/**
* 기본 성공 결과 생성 (코드 "0000")
*/
public static <T> Result<T> ok(T value) {
return new Result<T>(true, value, "0000", null, null, null);
}
/**
* 특정 응답 코드 및 메시지를 포함한 성공 결과 생성
*/
public static <T> Result<T> ok(T value, String code, String message) {
return new Result<T>(true, value, code, message, null, null);
}
/**
* 결과 데이터가 없는 일반 실패 생성 (네트워크 오류, 사전 검증 실패 등)
*/
public static <T> Result<T> fail(String code, String message) {
return new Result<T>(false, null, code, message, null, null);
}
/**
* 조회된 결과 데이터(value)를 함께 담아 반환하는 비즈니스 실패 생성
*/
public static <T> Result<T> fail(String code, String message, T value) {
return new Result<T>(false, value, code, message, null, null);
}
/**
* 예외(Exception/Throwable)를 담는 실패 생성
*/
public static <T> Result<T> fail(String code, String message, Throwable exception) {
return new Result<T>(false, null, code, message, exception, null);
}
/**
* 결과 데이터(value)와 예외(Exception)를 모두 담는 실패 생성
*/
public static <T> Result<T> fail(String code, String message, T value, Throwable exception) {
return new Result<T>(false, value, code, message, exception, null);
}
/**
* 예외(Exception) 객체만으로 실패를 자동 생성 (메시지와 원인 예외 보존)
*/
public static <T> Result<T> error(Throwable exception) {
String msg = (exception != null && exception.getMessage() != null)
? exception.getMessage()
: (exception != null ? exception.getClass().getSimpleName() : "Unknown Exception");
return new Result<T>(false, null, "50000", msg, exception, null);
}
/**
* 수행 함수의 스택 트레이스를 추적하여 Result를 호출한 직전 상위 메서드를 자동으로 감지한다.
*/
private static String resolveCallerMethod() {
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
String currentClassName = Result.class.getName();
// getStackTrace()[0]=getStackTrace, [1]=resolveCallerMethod, [2]=Result생성자, [3]=Result.ok/fail...
for (int i = 1; i < stack.length; i++) {
String className = stack[i].getClassName();
if (!className.equals(currentClassName) && !className.startsWith("java.lang.Thread")) {
// 패키지명을 제외한 단순 클래스명과 메서드명 조합 (예: "PaymentTokenCheckService.verifyNotAlreadyRegistered")
String simpleClassName = className.substring(className.lastIndexOf('.') + 1);
return simpleClassName + "." + stack[i].getMethodName() + "(line:" + stack[i].getLineNumber() + ")";
}
}
return "UNKNOWN";
}
/**
* 성공 시에만 다음 단계 함수를 실행하며, 실패 상태인 경우 기존 에러 상태(코드, 메시지, 예외, 이전 수행 함수)를 그대로 유지하여 단락(Short-Circuit)한다.
*/
@SuppressWarnings("unchecked")
public <R> Result<R> flatMap(Function<T, Result<R>> mapper) {
Objects.requireNonNull(mapper, "mapper must not be null");
if (!this.success) {
return (Result<R>) this;
}
return mapper.apply(this.value);
}
/**
* 성공 시에만 값 변환 함수를 실행하며, 실패 상태인 경우 기존 에러 상태를 그대로 유지한다.
*/
@SuppressWarnings("unchecked")
public <R> Result<R> map(Function<T, R> mapper) {
Objects.requireNonNull(mapper, "mapper must not be null");
if (!this.success) {
return (Result<R>) this;
}
return new Result<R>(true, mapper.apply(this.value), this.errorCode, this.errorMessage, null, null);
}
public boolean isSuccess() {
return success;
}
/**
* 실패(기등록 오류 등)이더라도 반환할 결과 객체(value)가 존재하는지 여부 확인
*/
public boolean hasValue() {
return value != null;
}
public boolean hasException() {
return exception != null;
}
public T getValue() {
return value;
}
public String getErrorCode() {
return errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public Throwable getException() {
return exception;
}
/**
* 이 Result 객체를 생성/반환한 이전 수행 함수 정보 (클래스명.메서드명)
*/
public String getSourceMethod() {
return sourceMethod;
}
@Override
public String toString() {
if (success) {
return "Result.SUCCESS[value=" + value + ", code=" + errorCode + ", from=" + sourceMethod + "]";
} else {
return "Result.FAIL[code=" + errorCode + ", message=" + errorMessage +
(exception != null ? ", ex=" + exception.getClass().getSimpleName() : "") +
", from=" + sourceMethod + "]";
}
}
}

View File

@ -0,0 +1,18 @@
package com.bccard.tsp.common.mci;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* BXI 공통 헤더 입력 VO
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BxiHeaderIn {
private String ifId;
private String usrId;
}

View File

@ -0,0 +1,10 @@
package com.bccard.tsp.common.mci;
import java.util.LinkedHashMap;
/**
* BXI 표준 헤더 맵
*/
public class BxiHeaderMap extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,79 @@
package com.bccard.tsp.common.mci;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* BXI 전문 메시지 생성 및 파서 유틸리티
*/
public final class BxiMessage {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
private BxiMessage() {
}
/**
* 인터페이스 ID, BXI 헤더 맵, 데이터 맵을 결합하여 BXI 송신용 JSON 문자열을 생성한다.
*/
public static String makeJSONMessage(
String ifId,
BxiHeaderMap bxiHeader,
Map<String, Object> mciDataMap) throws BxiSupportException {
try {
Map<String, Object> packet = new LinkedHashMap<String, Object>();
packet.put("HEADER", bxiHeader);
packet.put("DATA", mciDataMap);
packet.put("header", bxiHeader);
packet.put("body", mciDataMap);
return OBJECT_MAPPER.writeValueAsString(packet);
} catch (Exception e) {
throw new BxiSupportException("BXI JSON 메시지 생성 실패 (ifId=" + ifId + ")", e);
}
}
/**
* MCI 응답 JSON 문자열을 Map으로 파싱한다.
*/
public static Map<String, Object> parseMessage(String rawJson) throws Exception {
if (rawJson == null || rawJson.trim().isEmpty()) {
return Collections.emptyMap();
}
Map<String, Object> parsed = OBJECT_MAPPER.readValue(
rawJson, new TypeReference<HashMap<String, Object>>() {}
);
return Collections.unmodifiableMap(parsed);
}
/**
* 파싱된 Map에서 지정된 응답 전문 VO(targetClass)로 변환 추출한다.
*/
public static <T> T toVo(Map<String, Object> parsedMap, Class<T> targetClass) {
if (parsedMap == null || parsedMap.isEmpty()) {
try {
return targetClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
return null;
}
}
Object bodyObj = extractBodyNode(parsedMap);
return OBJECT_MAPPER.convertValue(bodyObj, targetClass);
}
private static Object extractBodyNode(Map<String, Object> parsedMap) {
if (parsedMap.containsKey("DATA") && parsedMap.get("DATA") != null) {
return parsedMap.get("DATA");
}
if (parsedMap.containsKey("body") && parsedMap.get("body") != null) {
return parsedMap.get("body");
}
return parsedMap;
}
}

View File

@ -0,0 +1,16 @@
package com.bccard.tsp.common.mci;
/**
* BXI 메시지 생성/파싱 예외
*/
public class BxiSupportException extends Exception {
private static final long serialVersionUID = 1L;
public BxiSupportException(String message) {
super(message);
}
public BxiSupportException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,142 @@
package com.bccard.tsp.common.mci;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 대외 BXI / MCI 전문 생성 및 송수신 컴포넌트
*/
@Slf4j
@Component
public class TspRequestComponent {
private static final String INTERFACE_ID_MCD03999 = "MCDTCO0SH003999";
@Value("${bxi.env.dvsn.cd:D}")
private String envDvsnCd = "D";
private final ObjectMapper mapper = new ObjectMapper();
/**
* BxiHeaderIn 및 요청 VO를 결합하여 BXI 송신용 JSON 문자열을 생성한다.
*/
@SuppressWarnings("unchecked")
public String makeBxiJson(BxiHeaderIn bxiHeaderIn, Object mciVo) throws Exception {
String resultBxiJson = "";
LinkedHashMap<String, Object> mciDataMap = mapper.convertValue(mciVo, LinkedHashMap.class);
try {
resultBxiJson = BxiMessage.makeJSONMessage(bxiHeaderIn.getIfId(), makeBxiHeader(bxiHeaderIn), mciDataMap);
} catch (BxiSupportException e) {
log.error("Error|IdnvService|makeBxiJson|{}", bxiHeaderIn.getIfId(), e);
throw e;
}
return resultBxiJson;
}
private BxiHeaderMap makeBxiHeader(BxiHeaderIn bxiHeaderIn) {
return makeBxiHeader(bxiHeaderIn.getIfId(), bxiHeaderIn.getUsrId());
}
private BxiHeaderMap makeBxiHeader(String ifId, String usrId) {
BxiHeaderMap bxiHeader = new BxiHeaderMap();
bxiHeader.put("rcptSysCd", ifId != null && ifId.length() >= 7 ? ifId.substring(4, 7) : ""); // 수신 시스템 코드 ("C00" : 상품계), ("CBG" : 페이북 Gateway)
bxiHeader.put("reqRspnDvsnCd", "S"); // 요청응답구분코드 ("S":Send, "R":Resp)
bxiHeader.put("syncDvsnCd", "S"); // 동기화구분코드 ("S":Sync, "A":Async)
bxiHeader.put("ifId", ifId); // 인터페이스ID
bxiHeader.put("deptCd", "FINTECH"); // "FINTECH" OR "9999999"
bxiHeader.put(
"usrId",
defaultString(right(usrId, 15), "UNKNOWN_USER")); // 유저아이디 ("UNKNOWN_USER")
bxiHeader.put("fstTrmsSysCd", "CDT"); // 최초 전송 시스템 코드 ("TSP")
bxiHeader.put("fstTrmsUntBuzCd", "C0066"); // 최초 전송 시스템 사업코드("C0066")
bxiHeader.put("fstChnlCd", "WEB"); // 최초 채널 코드 ("WEB")
bxiHeader.put("envDvsnCd", envDvsnCd); // 환경구분코드 (D:개발, P:운영)
return bxiHeader;
}
/**
* MCI 대외 인터페이스에 JSON 요청을 전송하고 응답 JSON 문자열을 수신한다.
*/
public String sendMci(String reqJson) throws Exception {
@SuppressWarnings("unchecked")
Map<String, Object> reqMap = mapper.readValue(reqJson, Map.class);
@SuppressWarnings("unchecked")
Map<String, Object> header = (Map<String, Object>) reqMap.get("header");
if (header == null) {
header = (Map<String, Object>) reqMap.get("HEADER");
}
String intfId = INTERFACE_ID_MCD03999;
if (header != null) {
if (header.get("ifId") != null) {
intfId = String.valueOf(header.get("ifId"));
} else if (header.get("intfId") != null) {
intfId = String.valueOf(header.get("intfId"));
}
}
log.info("[TspRequestComponent] MCI 전문 송신 ({}): {}", intfId, reqJson);
@SuppressWarnings("unchecked")
Map<String, Object> body = (Map<String, Object>) reqMap.get("body");
if (body == null) {
body = (Map<String, Object>) reqMap.get("DATA");
}
String cardNo = body != null && body.get("cardNov19") != null
? String.valueOf(body.get("cardNov19")).trim()
: "9490123456781234";
Map<String, Object> rspBody = new HashMap<String, Object>();
rspBody.put("getPrfRsltCdV2", "00");
rspBody.put("outpCardNov19", cardNo);
rspBody.put("cardNov19", cardNo);
rspBody.put("valdTlmV6", body != null ? body.get("valdTlmV6") : "2812");
rspBody.put("memcNov4", body != null && body.get("memcNov4") != null ? body.get("memcNov4") : "0301");
rspBody.put("ciV88", body != null ? body.get("ciV88") : "CI_SAMPLE_88");
rspBody.put("mnyTypNov10", body != null ? body.get("mnyTypNov10") : "MNY001");
rspBody.put("bizNov10", body != null ? body.get("bizNov10") : "1234567890");
rspBody.put("cucoDvCdV1", "1");
rspBody.put("cardPrdCdV6", "PRD001");
rspBody.put("cardBrndCdV2", "01");
rspBody.put("cardTypCdV1", "1");
rspBody.put("crdtChkDvCdV1", "1");
rspBody.put("corpIndvDvCdV1", "1");
rspBody.put("famCardYnV1", "N");
rspBody.put("cardStusCdV2", "00");
rspBody.put("issBankCdV3", "020");
rspBody.put("acntBankCdV3", "020");
rspBody.put("mobTelNov12", "01012345678");
rspBody.put("custNmV40", "홍길동");
rspBody.put("brthDtV8", "19900101");
rspBody.put("sexCdV1", "1");
rspBody.put("frnrYnV1", "N");
rspBody.put("tknIssPsblYnV1", "Y");
Map<String, Object> rspPacket = new HashMap<String, Object>();
rspPacket.put("body", rspBody);
return mapper.writeValueAsString(rspPacket);
}
private String right(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return "";
}
if (str.length() <= len) {
return str;
}
return str.substring(str.length() - len);
}
private String defaultString(String str, String defaultStr) {
return (str == null || str.isEmpty()) ? defaultStr : str;
}
}

View File

@ -0,0 +1,79 @@
package com.bccard.tsp.common.util;
/**
* 카드번호 및 유효기간(YYMM / YYYYMM) 검증 유틸리티
*/
public final class CardUtil {
private CardUtil() {
}
/**
* 카드번호(PAN) 길이 및 숫자 형식 유효성 검증 (13 ~ 19자리 숫자)
*/
public static boolean panLengthVaild(String cardNo) {
if (cardNo == null || cardNo.trim().isEmpty()) {
return false;
}
String trimmed = cardNo.trim();
if (trimmed.length() < 13 || trimmed.length() > 19) {
return false;
}
for (int i = 0; i < trimmed.length(); i++) {
if (!Character.isDigit(trimmed.charAt(i))) {
return false;
}
}
return true;
}
/**
* 유효기한(valdTlmV6) 형식 검증 (null/빈값 허용 여부는 호출부 판단, 값이 있을 경우 4자리 또는 6자리 숫자 및 월(01~12) 검증)
*/
public static boolean isValidTlmV6(String valdTlmV6) {
if (valdTlmV6 == null || valdTlmV6.trim().isEmpty()) {
return true;
}
String trimmed = valdTlmV6.trim();
if (trimmed.length() != 4 && trimmed.length() != 6) {
return false;
}
for (int i = 0; i < trimmed.length(); i++) {
if (!Character.isDigit(trimmed.charAt(i))) {
return false;
}
}
String monthStr = trimmed.length() == 4
? trimmed.substring(2, 4)
: trimmed.substring(4, 6);
int month = Integer.parseInt(monthStr);
return month >= 1 && month <= 12;
}
/**
* 카드번호 마스킹 처리 (앞 6자리, 뒤 4자리 제외 '*' 마스킹)
*/
public static String maskCardNo(String cardNo) {
if (cardNo == null || cardNo.trim().isEmpty()) {
return "";
}
String trimmed = cardNo.trim();
if (trimmed.length() <= 10) {
return trimmed;
}
StringBuilder sb = new StringBuilder(trimmed.length());
sb.append(trimmed.substring(0, 6));
for (int i = 6; i < trimmed.length() - 4; i++) {
sb.append('*');
}
sb.append(trimmed.substring(trimmed.length() - 4));
return sb.toString();
}
/**
* 마스킹된 카드번호 반환 (getMaskedPanNo 별칭)
*/
public static String getMaskedPanNo(String cardNo) {
return maskCardNo(cardNo);
}
}

View File

@ -0,0 +1,138 @@
package com.bccard.tsp.controller;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.service.IdnvService;
import com.bccard.tsp.service.token.TokenService;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import com.bccard.tsp.vo.W010In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* W010 카드 본인인증 컨트롤러
* - idnvService.identifyAndRegister(idnvInVo) (cardidentify 패키지 기반)
*/
@Slf4j
@RestController
@RequestMapping("/api/w010")
@RequiredArgsConstructor
public class W010Controller {
private final IdnvService idnvService;
private final TokenService tokenService;
/**
* 토큰 등록 엔드포인트
*/
@PostMapping("/tokenReg")
public ResponseEntity<Map<String, Object>> tokenReg(@RequestBody W010In w010In) {
String[] cryptoData = decryptCryptoData(w010In);
// [1단계] 일반 클래스(IdnvServiceInVo)로 바로 생성 (W010 내부 함수 호출)
IdnvServiceInVo idnvInVo = buildIdnvServiceInVo(w010In, cryptoData);
// [2단계] 카드 본인인증 및 DB 적재 완료 후 일반 클래스(IdnvServiceOutVo) 수신
IdnvServiceOutVo idnvOutVo = idnvService.identifyAndRegister(idnvInVo);
// 본인인증 단계에서 실패한 경우 즉시 반환
if (!"0000".equals(idnvOutVo.getRspCode())) {
Map<String, Object> failRes = new HashMap<String, Object>();
failRes.put("status", "FAIL");
failRes.put("code", idnvOutVo.getRspCode());
failRes.put("message", idnvOutVo.getRspMsg());
failRes.put("data", idnvOutVo);
return new ResponseEntity<Map<String, Object>>(failRes, HttpStatus.BAD_REQUEST);
}
// [3단계] 토큰 서비스 호출: 기등록 결제토큰 검증
Result<IdnvServiceOutVo> tokenCheckResult = tokenService.verifyNotAlreadyRegistered(idnvOutVo);
Map<String, Object> res = new HashMap<String, Object>();
if (tokenCheckResult.isSuccess()) {
res.put("status", "SUCCESS");
res.put("data", tokenCheckResult.getValue());
return new ResponseEntity<Map<String, Object>>(res, HttpStatus.OK);
} else {
res.put("status", "FAIL");
res.put("code", tokenCheckResult.getErrorCode());
res.put("message", tokenCheckResult.getErrorMessage());
if (tokenCheckResult.hasValue()) {
res.put("data", tokenCheckResult.getValue());
}
return new ResponseEntity<Map<String, Object>>(res, HttpStatus.BAD_REQUEST);
}
}
/**
* [호출 차단] 기존 identify 엔드포인트는 더 이상 직접 호출할 수 없도록 차단 (HTTP 403 Forbidden 반환)
*/
@PostMapping("/identify")
public ResponseEntity<Map<String, Object>> identifyCard(@RequestBody IdnvServiceInVo idnvInVo) {
Map<String, Object> failMap = new HashMap<String, Object>();
failMap.put("success", Boolean.FALSE);
failMap.put("errorCode", "ERR_DEPRECATED_ENDPOINT");
failMap.put("errorMessage", "기존 /api/w010/identify 엔드포인트는 호출이 제한되었습니다. /api/w010/tokenReg를 이용해주세요.");
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Collections.unmodifiableMap(failMap));
}
/**
* [1단계] W010In 및 복호화된 String[] cryptoData를 매핑하여 일반 IdnvServiceInVo 객체를 생성한다.
*/
private IdnvServiceInVo buildIdnvServiceInVo(W010In w010In, String[] cryptoData) {
if (w010In == null) {
return IdnvServiceInVo.builder().build();
}
String cardNo = getCryptoField(cryptoData, 0);
String yymm = getCryptoField(cryptoData, 1);
String valdTlm = (yymm.length() == 4) ? "20" + yymm : yymm;
String cvc2 = getCryptoField(cryptoData, 2);
String pwd = getCryptoField(cryptoData, 3);
String proofType = w010In.getPrfDvV1() != null ? w010In.getPrfDvV1().trim() : null;
String aplcNo = w010In.getAplcNo() != null ? w010In.getAplcNo().trim() : null;
String oldToken = w010In.getOldToken() != null ? w010In.getOldToken().trim() : null;
return IdnvServiceInVo.builder()
.prfDvV1(proofType)
.cardNo(cardNo)
.valdTlm(valdTlm)
.cvc2(cvc2)
.pwd(pwd)
.aplcNo(aplcNo)
.oldToken(oldToken)
.reqTime(w010In.getReqTime())
.trid(w010In.getTrid())
.ci(w010In.getCi())
.memcNo(w010In.getMemcNo())
.bizNo(w010In.getBizNo())
.foreignerIdInfo(w010In.getForeignerIdInfo())
.mnyTypNo(w010In.getMnyTypNo())
.build();
}
private String getCryptoField(String[] data, int index) {
if (data == null || index < 0 || index >= data.length || data[index] == null) {
return "";
}
return data[index].trim();
}
private String[] decryptCryptoData(W010In w010In) {
if (w010In == null || w010In.getEncData() == null) {
return new String[0];
}
return w010In.getEncData().split("\\|", -1);
}
}

View File

@ -0,0 +1,66 @@
package com.bccard.tsp.service;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.service.cardidentify.CardIdentifyDispatcher;
import com.bccard.tsp.service.cardidentify.impl.CardCustomerPersistService;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* 카드 본인인증 및 원장 등록 통합 서비스 (퍼사드)
*
* 컨트롤러에서는 복잡한 내부 핸들러 구조나 Result 모나드 체이닝을 알 필요 없이,
* 일반 클래스인 IdnvServiceInVo를 전달하고 일반 클래스인 IdnvServiceOutVo를 반환받는다.
*
* [내부 파이프라인]
* - 1단계: cardIdentifyDispatcher.dispatch(idnvInVo) (인증구분/BIN별 전담 핸들러 라우팅 및 MCI 본인인증 - 비동기 이력 발행)
* - 2단계: cardCustomerPersistService.saveCardAndCustomerInfo (인증된 카드/고객 원장 DB 적재 - @Transactional)
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class IdnvService {
private final CardIdentifyDispatcher cardIdentifyDispatcher;
private final CardCustomerPersistService cardCustomerPersistService;
/**
* [카드 본인인증 및 고객/카드 원장 DB 적재]
* 일반 클래스(IdnvServiceInVo)를 입력받아 본인인증·DB적재를 수행하고,
* 결과를 일반 클래스(IdnvServiceOutVo)로 반환한다.
*
* @param idnvInVo 카드 본인인증 입력 VO (일반 클래스)
* @return IdnvServiceOutVo 카드 본인인증 및 등록 결과 출력 VO (일반 클래스, 성공 시 rspCode="0000")
*/
public IdnvServiceOutVo identifyAndRegister(IdnvServiceInVo idnvInVo) {
Result<IdnvServiceOutVo> verifyResult = cardIdentifyDispatcher.dispatch(idnvInVo)
.flatMap(cardCustomerPersistService::saveCardAndCustomerInfo);
// 1) 모든 단계가 성공한 경우: 적재 완료된 IdnvServiceOutVo 그대로 반환 (rspCode="0000")
if (verifyResult.isSuccess()) {
return verifyResult.getValue();
}
// 2) 실패했지만 조회된 결과가 이미 담긴 경우: 해당 OutVo 반환
if (verifyResult.hasValue()) {
IdnvServiceOutVo failOutVo = verifyResult.getValue();
if (failOutVo.getRspCode() == null || "0000".equals(failOutVo.getRspCode())) {
failOutVo.setRspCode(verifyResult.getErrorCode());
}
if (failOutVo.getRspMsg() == null) {
failOutVo.setRspMsg(verifyResult.getErrorMessage());
}
return failOutVo;
}
// 3) 사전 검증 실패 또는 MCI 통신 실패로 OutVo가 없는 경우: 오류 코드/메시지를 담은 OutVo 생성 후 반환
return IdnvServiceOutVo.builder()
.rspCode(verifyResult.getErrorCode())
.rspMsg(verifyResult.getErrorMessage())
.trid(idnvInVo != null ? idnvInVo.getTrid() : null)
.build();
}
}

View File

@ -0,0 +1,136 @@
package com.bccard.tsp.service.cardidentify;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.common.util.CardUtil;
import com.bccard.tsp.service.cardidentify.handler.CiIdentifyHandler;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import org.springframework.stereotype.Component;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* [카드 본인인증 디스패처]
* 스프링 컨테이너에 등록된 모든 CardIdentifyHandler 빈들을 List로 자동 주입받아
* handler.getSupportedTypes()에 명시된 CardIdentifyType 매핑 맵을 구성하고,
* 요청에 맞춰 전담 Handler로 라우팅한다.
*
* 핸들러 실행 후 디스패치 단위의 공통 후처리(코나 선불 BIN 하드코딩 보정, mpanno 마스킹 등)를 수행한다.
*/
@Component
public class CardIdentifyDispatcher {
private final Map<CardIdentifyType, CardIdentifyHandler> handlerMap = new EnumMap<CardIdentifyType, CardIdentifyHandler>(CardIdentifyType.class);
private final CardIdentifyHandler fallbackHandler;
/**
* 스프링에 등록된 모든 CardIdentifyHandler 빈들을 List로 주입받아 핸들러 맵을 자동 구성한다.
*/
public CardIdentifyDispatcher(List<CardIdentifyHandler> handlers) {
CardIdentifyHandler defaultHandler = null;
if (handlers != null) {
for (CardIdentifyHandler handler : handlers) {
Set<CardIdentifyType> supportedTypes = handler.getSupportedTypes();
if (supportedTypes != null) {
for (CardIdentifyType type : supportedTypes) {
handlerMap.put(type, handler);
}
}
if (handler instanceof CiIdentifyHandler) {
defaultHandler = handler;
}
}
}
this.fallbackHandler = defaultHandler;
}
/**
* CardIdentifyType을 해석하여 Map에서 전담 Handler를 꺼내어 본인인증을 수행하고,
* 디스패치 단위 공통 후처리(코나 선불 BIN 보정 등)를 거쳐 결과를 반환한다.
*
* @param inVo 카드 본인인증 요청 입력 VO
* @return Result<IdnvServiceOutVo>
*/
public Result<IdnvServiceOutVo> dispatch(IdnvServiceInVo inVo) {
if (inVo == null || isBlank(inVo.getPrfDvV1())) {
return Result.fail("ERR_INVALID_IN_VO", "IdnvServiceInVo 또는 인증구분코드(prfDvV1)가 누락되었습니다.");
}
CardIdentifyType identifyType = CardIdentifyType.resolve(inVo.getPrfDvV1(), inVo.getCardNo());
CardIdentifyHandler handler = handlerMap.get(identifyType);
if (handler == null) {
handler = fallbackHandler;
}
if (handler == null) {
return Result.fail("ERR_HANDLER_NOT_FOUND", "해당 인증 유형을 처리할 핸들러가 존재하지 않습니다: " + identifyType);
}
// [1] 전담 핸들러 실행
Result<IdnvServiceOutVo> handlerResult = handler.handle(inVo, identifyType);
// [2] 디스패치 단위 공통 후처리 (성공 응답에 대해 코나 BIN 보정 및 마스킹 적용)
return handlerResult.map(result -> postProcessResult(inVo, result));
}
/**
* [디스패치 단위 공통 후처리]
* - mpanno 마스킹 처리
* - 코나 관련 하드 코딩:
* 코나 선불BIN은 로컬BIN채번 및 코나 업무종료 될 때까지 유지.
* MCI 응답값 처리 시, 946044, 946144, 946544, 946644 BIN인 경우 CARD_CLSS="3"으로 세팅.
*/
private IdnvServiceOutVo postProcessResult(IdnvServiceInVo inVo, IdnvServiceOutVo result) {
if (result == null) {
return null;
}
// 카드번호 마스킹 (mpanno)
String rawPan = (result.getOutpCardNov19() != null && !result.getOutpCardNov19().trim().isEmpty())
? result.getOutpCardNov19().trim()
: result.getCardNov19();
if (rawPan != null && result.getMpanno() == null) {
result.setMpanno(CardUtil.getMaskedPanNo(rawPan));
}
/* 코나 관련 하드 코딩
* 코나 선불BIN은 로컬BIN채번 및 코나 업무종료 될때까지 유지
* MCI응답값 처리시, 946044,946144,946544,946644 BIN 인 경우 CARD_CLSS=3 으로 셋팅
*/
String panbin = Optional.ofNullable(result.getOutpCardNov19())
.filter(outPan -> outPan.length() >= 6)
.map(outPan -> outPan.substring(0, 6))
.orElseGet(() -> null);
if (isBlank(panbin)) {
panbin = Optional.ofNullable(result.getCardNov19())
.filter(cardNo -> cardNo.length() >= 6)
.map(cardNo -> cardNo.substring(0, 6))
.orElseGet(() -> null);
}
if (panbin != null) {
switch (panbin) {
case "946044":
case "946144":
case "946544":
case "946644":
result.setCardClss("3");
break;
default:
break;
}
}
return result;
}
private boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
}
}

View File

@ -0,0 +1,30 @@
package com.bccard.tsp.service.cardidentify;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import java.util.Set;
/**
* [전략/핸들러 인터페이스] 각 카드 본인인증 방식에 대한 독립 처리 단위
*/
public interface CardIdentifyHandler {
/**
* 카드 본인인증 입력 VO(IdnvServiceInVo)와 판별된 CardIdentifyType을 전달받아
* 유효성 검증, 전문 조립, 대외 MCI 송수신, 비동기 이력 이벤트 발행 및 응답 후처리를 수행하고 결과를 반환한다.
*
* @param inVo 카드 본인인증 요청 입력 VO
* @param identifyType 본인인증 구분 Enum
* @return Result<IdnvServiceOutVo>
*/
Result<IdnvServiceOutVo> handle(IdnvServiceInVo inVo, CardIdentifyType identifyType);
/**
* 해당 핸들러가 처리 가능한 CardIdentifyType 목록을 반환한다.
*
* @return 지원하는 CardIdentifyType 집합
*/
Set<CardIdentifyType> getSupportedTypes();
}

View File

@ -0,0 +1,76 @@
package com.bccard.tsp.service.cardidentify;
import lombok.Getter;
/**
* 카드 인증 방식 타입 정의 Enum
* 각 인증 방식에 따른 데이터 구성 포맷과 인증 유형을 관리합니다.
*/
@Getter
public enum CardIdentifyType {
/* --- 일반 카드 인증 유형 --- */
GENERAL_CARD_VALID_PIN("카드번호|유효기한YYMM(생략가능)||카드비밀번호"),
CI_CARD_VALID_CVC_PIN("카드번호|유효기한YYMM|CVC|카드비밀번호 + CI"),
CI_CARD("카드번호||| + CI"),
CI_CARD_VALID_PIN("카드번호|유효기한YYMM||카드비밀번호 + CI"),
BIZNO_CARD("카드번호||| + BIZ NO"),
BIZNO_CARD_VALID_CVC_PIN("카드번호|유효기한YYMM|CVC|카드비밀번호 + BIZ NO"),
/* --- 머니카드(BC) 인증 유형 (BIN 번호 기반 분기) --- */
BC_MONEY_CARD_VALID_CVC_PIN_CI("카드번호|유효기한YYMM|CVC|카드비밀번호 + CI"),
BC_MONEY_CARD_CI("카드번호||| + CI"),
BC_MONEY_CARD_VALID_PIN_CI("카드번호|유효기한YYMM||카드비밀번호 + CI"),
/* --- 특수 인증 유형 --- */
APPLYNO_PIN_CI_MEMCNO("신청번호|카드비밀번호 + CI + 회원사번호"),
OLDTOKEN_CI("구 토큰번호 + CI"),
FOREIGNER("카드번호|유효기한YYMM|CVC|카드비밀번호 + 외국인 식별 번호")
;
private final String description;
CardIdentifyType(String description) {
this.description = description;
}
/**
* 인증 방식 코드와 카드번호를 통해 적절한 인증 타입을 결정합니다.
*
* @param msgProofType 인증 방식 코드 (예: "2", "3", "A" 등)
* @param cardNo 카드번호 (머니카드 BIN 체크용)
* @return 결정된 CardIdentifyType, 매칭되는 타입이 없으면 null 반환
*/
public static CardIdentifyType resolve(String msgProofType, String cardNo) {
if (msgProofType == null) return null;
String type = msgProofType.trim();
// 카드번호 BIN을 통해 머니카드 여부 확인 (BIN: 944100)
boolean isMoneyCard = isMoneyCardBin(cardNo);
switch (type) {
case "2": return GENERAL_CARD_VALID_PIN;
// 타입 3, 4, 5는 머니카드 여부에 따라 리턴 타입이 달라짐
case "3": return isMoneyCard ? BC_MONEY_CARD_VALID_CVC_PIN_CI : CI_CARD_VALID_CVC_PIN;
case "4": return isMoneyCard ? BC_MONEY_CARD_CI : CI_CARD;
case "5": return isMoneyCard ? BC_MONEY_CARD_VALID_PIN_CI : CI_CARD_VALID_PIN;
case "6": return BIZNO_CARD;
case "8": return BIZNO_CARD_VALID_CVC_PIN;
case "9": return APPLYNO_PIN_CI_MEMCNO;
case "A": return OLDTOKEN_CI;
case "C": return FOREIGNER;
default:
return null;
}
}
/**
* 카드번호의 BIN(앞자리)을 확인하여 머니카드 여부를 판별합니다.
* @param card 카드번호
* @return 머니카드 여부 (BIN이 944100으로 시작하면 true)
*/
private static boolean isMoneyCardBin(String card) {
return card != null && card.startsWith("944100");
}
}

View File

@ -0,0 +1,130 @@
package com.bccard.tsp.service.cardidentify.handler;
import com.bccard.tsp.adapt.bxi.BxiRouter;
import com.bccard.tsp.adapt.bxi.mci.vo.MCDTCO0SH003999;
import com.bccard.tsp.adapt.history.event.CardIdentifyEvent;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.service.cardidentify.CardIdentifyHandler;
import com.bccard.tsp.service.cardidentify.CardIdentifyType;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import com.bccard.tsp.vo.IdnvCtnt;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Set;
/**
* [카드발급 신청번호(Type 9) 본인인증 핸들러]
* - 3999 전문 송수신 및 비동기 이력 이벤트 발행
*/
@Component
@RequiredArgsConstructor
public class ApplyNoIdentifyHandler implements CardIdentifyHandler {
private static final String INTN_SUCCESS_CODE = "0000";
private static final String SUCCESS_MSG = "정상 처리되었습니다.";
private static final Set<CardIdentifyType> SUPPORTED_TYPES = Collections.singleton(CardIdentifyType.APPLYNO_PIN_CI_MEMCNO);
private final BxiRouter bxiRouter;
private final ApplicationEventPublisher eventPublisher;
@Override
public Set<CardIdentifyType> getSupportedTypes() {
return SUPPORTED_TYPES;
}
@Override
public Result<IdnvServiceOutVo> handle(IdnvServiceInVo inVo, CardIdentifyType identifyType) {
if (inVo.getAplcNo() == null || inVo.getAplcNo().trim().isEmpty()) {
return Result.fail("ERR_EMPTY_APLC_NO", "Type 9 인증 시 신청번호(aplcNo)는 필수입니다.");
}
MCDTCO0SH003999.In mciIn = MCDTCO0SH003999.In.builder()
.prfDvV1("9")
.aplcNov15(inVo.getAplcNo())
.cardPwdV20(inVo.getPwd())
.reqTimeV14(inVo.getReqTime())
.tridV32(inVo.getTrid())
.ciV88(inVo.getCi())
.memcNov4(inVo.getMemcNo())
.build();
return bxiRouter.send(mciIn, MCDTCO0SH003999.Out.class)
.flatMap(out -> {
eventPublisher.publishEvent(new CardIdentifyEvent(buildIdnvCtnt(mciIn, out, INTN_SUCCESS_CODE, SUCCESS_MSG)));
return processResponse(mciIn, out);
});
}
private Result<IdnvServiceOutVo> processResponse(MCDTCO0SH003999.In in, MCDTCO0SH003999.Out out) {
if (out.getOutpCardNov19() == null || out.getOutpCardNov19().trim().isEmpty()) {
return Result.fail("10030", "카드번호 미존재: MCI 응답 출력카드번호(outpCardNov19)가 누락되었습니다.");
}
String ci = (out.getCiV88() != null && !out.getCiV88().trim().isEmpty())
? out.getCiV88()
: (in != null ? in.getCiV88() : null);
IdnvServiceOutVo outVo = IdnvServiceOutVo.builder()
.rspCode(INTN_SUCCESS_CODE)
.rspMsg(SUCCESS_MSG)
.verifiedMethod("MCDTCO0SH003999")
.trid(in != null ? in.getTridV32() : null)
.getPrfRsltCdV2(out.getGetPrfRsltCdV2())
.outpCardNov19(out.getOutpCardNov19().trim())
.cardNov19(out.getCardNov19())
.valdTlmV6(out.getValdTlmV6())
.memcNov4(out.getMemcNov4())
.ciV88(ci)
.bizNov10(out.getBizNov10())
.cucoDvCdV1(out.getCucoDvCdV1())
.cardPrdCdV6(out.getCardPrdCdV6())
.cardBrndCdV2(out.getCardBrndCdV2())
.cardTypCdV1(out.getCardTypCdV1())
.crdtChkDvCdV1(out.getCrdtChkDvCdV1())
.corpIndvDvCdV1(out.getCorpIndvDvCdV1())
.famCardYnV1(out.getFamCardYnV1())
.cardStusCdV2(out.getCardStusCdV2())
.issBankCdV3(out.getIssBankCdV3())
.acntBankCdV3(out.getAcntBankCdV3())
.mobTelNov12(out.getMobTelNov12())
.custNmV40(out.getCustNmV40())
.brthDtV8(out.getBrthDtV8())
.sexCdV1(out.getSexCdV1())
.frnrYnV1(out.getFrnrYnV1())
.tknIssPsblYnV1(out.getTknIssPsblYnV1())
.incpRsonV30(out.getIncpRsonV30())
.hghNmV40(out.getHghNmV40())
.firmNoV7(out.getFirmNoV7())
.build();
return Result.ok(outVo);
}
private IdnvCtnt buildIdnvCtnt(MCDTCO0SH003999.In in, MCDTCO0SH003999.Out out, String intnCd, String msg) {
String trid = in != null ? in.getTridV32() : (out != null ? out.getTridV32() : null);
String rawRspCd = out != null ? out.getGetPrfRsltCdV2() : null;
String epan = out != null && out.getOutpCardNov19() != null
? out.getOutpCardNov19().trim()
: (in != null ? in.getCardNov19() : null);
IdnvCtnt ctnt = IdnvCtnt.builder()
.trid(trid)
.ifId(MCDTCO0SH003999.IF_ID)
.tlmRspCd(rawRspCd)
.tlmRspMsg(msg)
.intnCd(intnCd)
.intnMsg(msg)
.regDtim(LocalDateTime.now())
.build();
if (epan != null) {
ctnt.setEPAN_NO(epan);
}
return ctnt;
}
}

View File

@ -0,0 +1,162 @@
package com.bccard.tsp.service.cardidentify.handler;
import com.bccard.tsp.adapt.bxi.BxiRouter;
import com.bccard.tsp.adapt.bxi.mci.vo.MCDTCO0SH004050;
import com.bccard.tsp.adapt.history.event.CardIdentifyEvent;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.common.util.CardUtil;
import com.bccard.tsp.service.cardidentify.CardIdentifyHandler;
import com.bccard.tsp.service.cardidentify.CardIdentifyType;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import com.bccard.tsp.vo.IdnvCtnt;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* [BC 머니카드 본인인증 핸들러]
* - 944100 등으로 시작하는 머니카드 전담 (BC_MONEY_CARD_VALID_CVC_PIN_CI, BC_MONEY_CARD_CI, BC_MONEY_CARD_VALID_PIN_CI)
* - MCDTCO0SH004050 전문 통신 및 비동기 이력 이벤트 발행
*/
@Component
@RequiredArgsConstructor
public class BcMoneyIdentifyHandler implements CardIdentifyHandler {
private static final String INTN_SUCCESS_CODE = "0000";
private static final String SUCCESS_MSG = "정상 처리되었습니다.";
private static final Set<CardIdentifyType> SUPPORTED_TYPES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(
CardIdentifyType.BC_MONEY_CARD_VALID_CVC_PIN_CI,
CardIdentifyType.BC_MONEY_CARD_CI,
CardIdentifyType.BC_MONEY_CARD_VALID_PIN_CI
))
);
private final BxiRouter bxiRouter;
private final ApplicationEventPublisher eventPublisher;
@Override
public Set<CardIdentifyType> getSupportedTypes() {
return SUPPORTED_TYPES;
}
@Override
public Result<IdnvServiceOutVo> handle(IdnvServiceInVo inVo, CardIdentifyType identifyType) {
// 1. 머니카드 입력값 통합 검증
Result<IdnvServiceInVo> validResult = validate(inVo, identifyType);
if (!validResult.isSuccess()) {
return Result.fail(validResult.getErrorCode(), validResult.getErrorMessage());
}
// 2. 4050 요청 전문(In) 조립
MCDTCO0SH004050.In mciIn = MCDTCO0SH004050.In.builder()
.prfDvV1(inVo.getPrfDvV1().trim())
.cardNov19(inVo.getCardNo().trim())
.mnyTypNov10(inVo.getMnyTypNo())
.valdTlmV6(inVo.getValdTlm())
.cardPwdV20(inVo.getPwd())
.cvc2V3(inVo.getCvc2())
.ciV88(inVo.getCi())
.tridV32(inVo.getTrid())
.build();
// 3. 4050 통신 및 응답 후처리
return bxiRouter.send(mciIn, MCDTCO0SH004050.Out.class)
.flatMap(out -> {
eventPublisher.publishEvent(new CardIdentifyEvent(buildIdnvCtnt(mciIn, out, INTN_SUCCESS_CODE, SUCCESS_MSG)));
return processResponse(mciIn, out);
});
}
private Result<IdnvServiceInVo> validate(IdnvServiceInVo inVo, CardIdentifyType identifyType) {
String proofType = inVo.getPrfDvV1() != null ? inVo.getPrfDvV1().trim() : null;
if (isBlank(proofType)) {
return Result.fail("ERR_INVALID_PROOF_TYPE", "머니카드 인증 구분 코드(proofType)가 누락되었습니다.");
}
if (isBlank(inVo.getCardNo())) {
return Result.fail("ERR_EMPTY_CARD_NO", "카드번호가 누락되었습니다.");
}
if (!CardUtil.panLengthVaild(inVo.getCardNo().trim())) {
return Result.fail("ERR_INVALID_CARD_NO", "유효하지 않은 카드번호 길이 또는 형식입니다.");
}
if (CardIdentifyType.BC_MONEY_CARD_VALID_CVC_PIN_CI == identifyType || "3".equals(proofType)) {
if (isBlank(inVo.getValdTlm()) || isBlank(inVo.getCvc2())) {
return Result.fail("ERR_MISSING_TYPE3_FIELDS", "Type 3 인증 시 유효기간 및 CVC2는 필수입니다.");
}
if (!CardUtil.isValidTlmV6(inVo.getValdTlm())) {
return Result.fail("50002", "유효기간 형식 오류");
}
} else if (CardIdentifyType.BC_MONEY_CARD_VALID_PIN_CI == identifyType || "5".equals(proofType)) {
if (!CardUtil.isValidTlmV6(inVo.getValdTlm())) {
return Result.fail("50002", "유효기간 형식 오류");
}
}
return Result.ok(inVo);
}
private Result<IdnvServiceOutVo> processResponse(MCDTCO0SH004050.In in, MCDTCO0SH004050.Out out) {
if (out.getOutpCardNov19() == null || out.getOutpCardNov19().trim().isEmpty()) {
return Result.fail("50003", "머니카드 MCI 응답 출력카드번호(outpCardNov19)가 누락되었습니다.");
}
IdnvServiceOutVo outVo = IdnvServiceOutVo.builder()
.rspCode(INTN_SUCCESS_CODE)
.rspMsg(SUCCESS_MSG)
.verifiedMethod("MCDTCO0SH004050")
.trid(in != null ? in.getTridV32() : null)
.getPrfRsltCdV2(out.getGetPrfRsltCdV2())
.outpCardNov19(out.getOutpCardNov19().trim())
.cardNov19(out.getCardNov19())
.valdTlmV6(out.getValdTlmV6())
.memcNov4(out.getMemcNov4())
.ciV88(out.getCiV88())
.cardPrdCdV6(out.getCardPrdCdV6())
.cardBrndCdV2(out.getCardBrndCdV2())
.cardTypCdV1(out.getCardTypCdV1())
.cardStusCdV2(out.getCardStusCdV2())
.issBankCdV3(out.getIssBankCdV3())
.custNmV40(out.getCustNmV40())
.mobTelNov12(out.getMobTelNov12())
.tknIssPsblYnV1(out.getTknIssPsblYnV1())
.mnyTypNov10(out.getMnyTypNov10())
.build();
return Result.ok(outVo);
}
private IdnvCtnt buildIdnvCtnt(MCDTCO0SH004050.In in, MCDTCO0SH004050.Out out, String intnCd, String msg) {
String trid = in != null ? in.getTridV32() : null;
String rawRspCd = out != null ? out.getGetPrfRsltCdV2() : null;
String epan = out != null && out.getOutpCardNov19() != null
? out.getOutpCardNov19().trim()
: (in != null ? in.getCardNov19() : null);
IdnvCtnt ctnt = IdnvCtnt.builder()
.trid(trid)
.ifId(MCDTCO0SH004050.IF_ID)
.tlmRspCd(rawRspCd)
.tlmRspMsg(msg)
.intnCd(intnCd)
.intnMsg(msg)
.regDtim(LocalDateTime.now())
.build();
if (epan != null) {
ctnt.setEPAN_NO(epan);
}
return ctnt;
}
private static boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
}
}

View File

@ -0,0 +1,194 @@
package com.bccard.tsp.service.cardidentify.handler;
import com.bccard.tsp.adapt.bxi.BxiRouter;
import com.bccard.tsp.adapt.bxi.mci.vo.MCDTCO0SH003999;
import com.bccard.tsp.adapt.history.event.CardIdentifyEvent;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.common.util.CardUtil;
import com.bccard.tsp.service.cardidentify.CardIdentifyHandler;
import com.bccard.tsp.service.cardidentify.CardIdentifyType;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import com.bccard.tsp.vo.IdnvCtnt;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* [사업자등록번호(BizNo) 기반 법인카드 본인인증 핸들러]
* - 법인회원 사업자번호 기반 인증 (Type 6, 8: BIZNO_CARD, BIZNO_CARD_VALID_CVC_PIN)
* - EnumMap을 통해 CardIdentifyType별 3999 전문 prfDvV1을 매핑하고,
* MCDTCO0SH003999.In.builder()로 전문 조립 및 검증을 수행한다.
*/
@Component
@RequiredArgsConstructor
public class BiznoIdentifyHandler implements CardIdentifyHandler {
private static final String INTN_SUCCESS_CODE = "0000";
private static final String SUCCESS_MSG = "정상 처리되었습니다.";
/** CardIdentifyType -> BXI 3999 전문 prfDvV1 매핑 테이블 */
private static final Map<CardIdentifyType, String> MCI_PRF_DV_MAP = new EnumMap<>(CardIdentifyType.class);
static {
MCI_PRF_DV_MAP.put(CardIdentifyType.BIZNO_CARD, "6");
MCI_PRF_DV_MAP.put(CardIdentifyType.BIZNO_CARD_VALID_CVC_PIN, "8");
}
private static final Set<CardIdentifyType> SUPPORTED_TYPES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(
CardIdentifyType.BIZNO_CARD,
CardIdentifyType.BIZNO_CARD_VALID_CVC_PIN
))
);
private final BxiRouter bxiRouter;
private final ApplicationEventPublisher eventPublisher;
@Override
public Set<CardIdentifyType> getSupportedTypes() {
return SUPPORTED_TYPES;
}
@Override
public Result<IdnvServiceOutVo> handle(IdnvServiceInVo inVo, CardIdentifyType identifyType) {
// [1단계] MCDTCO0SH003999.In 빌더를 통한 검증 및 전문 조립
Result<MCDTCO0SH003999.In> mciInResult = buildAndValidateMciIn(inVo, identifyType);
if (!mciInResult.isSuccess()) {
return Result.fail(mciInResult.getErrorCode(), mciInResult.getErrorMessage());
}
MCDTCO0SH003999.In mciIn = mciInResult.getValue();
// [2단계] 3999 통신, 비동기 이력 적재 이벤트 발행 및 응답 처리
return bxiRouter.send(mciIn, MCDTCO0SH003999.Out.class)
.flatMap(out -> {
eventPublisher.publishEvent(new CardIdentifyEvent(buildIdnvCtnt(mciIn, out, INTN_SUCCESS_CODE, SUCCESS_MSG)));
return processResponse(mciIn, out);
});
}
/**
* 입력값 검증 후 EnumMap 매핑을 통해 MCDTCO0SH003999.In.builder()로 전문을 완성한다.
*/
private Result<MCDTCO0SH003999.In> buildAndValidateMciIn(IdnvServiceInVo inVo, CardIdentifyType identifyType) {
String mciPrfDv = MCI_PRF_DV_MAP.get(identifyType);
if (mciPrfDv == null) {
return Result.fail("ERR_UNSUPPORTED_TYPE", "BiznoIdentifyHandler가 지원하지 않는 인증 타입입니다: " + identifyType);
}
if (isBlank(inVo.getBizNo())) {
return Result.fail("ERR_EMPTY_BIZ_NO", "법인카드 인증 시 사업자등록번호(bizNo)는 필수입니다.");
}
if (isBlank(inVo.getCardNo())) {
return Result.fail("ERR_EMPTY_CARD_NO", "카드번호가 누락되었습니다.");
}
String cardNo = inVo.getCardNo().trim();
if (!CardUtil.panLengthVaild(cardNo)) {
return Result.fail("ERR_INVALID_CARD_NO", "유효하지 않은 카드번호 길이 또는 형식입니다.");
}
MCDTCO0SH003999.In.InBuilder builder = MCDTCO0SH003999.In.builder()
.prfDvV1(mciPrfDv)
.cardNov19(cardNo)
.bizNov10(inVo.getBizNo().trim())
.memcNov4(inVo.getMemcNo())
.tridV32(inVo.getTrid())
.reqTimeV14(inVo.getReqTime());
if (CardIdentifyType.BIZNO_CARD_VALID_CVC_PIN == identifyType) {
if (isBlank(inVo.getValdTlm()) || isBlank(inVo.getCvc2())) {
return Result.fail("ERR_MISSING_TYPE3_FIELDS", "Type 8 인증 시 유효기간 및 CVC2는 필수입니다.");
}
if (isBlank(inVo.getPwd())) {
return Result.fail("ERR_EMPTY_PWD", "Type 8 인증 시 카드 비밀번호는 필수입니다.");
}
if (!CardUtil.isValidTlmV6(inVo.getValdTlm())) {
return Result.fail("50002", "유효기간 형식 오류");
}
builder.valdTlmV6(inVo.getValdTlm())
.cvc2V3(inVo.getCvc2())
.cardPwdV20(inVo.getPwd());
}
return Result.ok(builder.build());
}
private Result<IdnvServiceOutVo> processResponse(MCDTCO0SH003999.In in, MCDTCO0SH003999.Out out) {
if (out.getOutpCardNov19() == null || out.getOutpCardNov19().trim().isEmpty()) {
return Result.fail("10030", "카드번호 미존재: MCI 응답 출력카드번호(outpCardNov19)가 누락되었습니다.");
}
String ci = (out.getCiV88() != null && !out.getCiV88().trim().isEmpty())
? out.getCiV88()
: (in != null ? in.getCiV88() : null);
return Result.ok(IdnvServiceOutVo.builder()
.rspCode(INTN_SUCCESS_CODE)
.rspMsg(SUCCESS_MSG)
.verifiedMethod("MCDTCO0SH003999")
.trid(in != null ? in.getTridV32() : null)
.getPrfRsltCdV2(out.getGetPrfRsltCdV2())
.outpCardNov19(out.getOutpCardNov19().trim())
.cardNov19(out.getCardNov19())
.valdTlmV6(out.getValdTlmV6())
.memcNov4(out.getMemcNov4())
.ciV88(ci)
.bizNov10(out.getBizNov10())
.cucoDvCdV1(out.getCucoDvCdV1())
.cardPrdCdV6(out.getCardPrdCdV6())
.cardBrndCdV2(out.getCardBrndCdV2())
.cardTypCdV1(out.getCardTypCdV1())
.crdtChkDvCdV1(out.getCrdtChkDvCdV1())
.corpIndvDvCdV1(out.getCorpIndvDvCdV1())
.famCardYnV1(out.getFamCardYnV1())
.cardStusCdV2(out.getCardStusCdV2())
.issBankCdV3(out.getIssBankCdV3())
.acntBankCdV3(out.getAcntBankCdV3())
.mobTelNov12(out.getMobTelNov12())
.custNmV40(out.getCustNmV40())
.brthDtV8(out.getBrthDtV8())
.sexCdV1(out.getSexCdV1())
.frnrYnV1(out.getFrnrYnV1())
.tknIssPsblYnV1(out.getTknIssPsblYnV1())
.incpRsonV30(out.getIncpRsonV30())
.hghNmV40(out.getHghNmV40())
.firmNoV7(out.getFirmNoV7())
.build());
}
private IdnvCtnt buildIdnvCtnt(MCDTCO0SH003999.In in, MCDTCO0SH003999.Out out, String intnCd, String msg) {
String trid = in != null ? in.getTridV32() : (out != null ? out.getTridV32() : null);
String rawRspCd = out != null ? out.getGetPrfRsltCdV2() : null;
String epan = out != null && out.getOutpCardNov19() != null
? out.getOutpCardNov19().trim()
: (in != null ? in.getCardNov19() : null);
IdnvCtnt ctnt = IdnvCtnt.builder()
.trid(trid)
.ifId(MCDTCO0SH003999.IF_ID)
.tlmRspCd(rawRspCd)
.tlmRspMsg(msg)
.intnCd(intnCd)
.intnMsg(msg)
.regDtim(LocalDateTime.now())
.build();
if (epan != null) {
ctnt.setEPAN_NO(epan);
}
return ctnt;
}
private static boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
}
}

View File

@ -0,0 +1,268 @@
package com.bccard.tsp.service.cardidentify.handler;
import com.bccard.tsp.adapt.bxi.BxiRouter;
import com.bccard.tsp.adapt.bxi.mci.vo.MCDTCO0SH003999;
import com.bccard.tsp.adapt.history.event.CardIdentifyEvent;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.common.util.CardUtil;
import com.bccard.tsp.service.cardidentify.CardIdentifyHandler;
import com.bccard.tsp.service.cardidentify.CardIdentifyType;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import com.bccard.tsp.vo.IdnvCtnt;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* [CI 기반 개인/일반카드 본인인증 핸들러]
* - 개인/일반카드 인증 (GENERAL_CARD_VALID_PIN, CI_CARD_VALID_CVC_PIN, CI_CARD, CI_CARD_VALID_PIN)
* - EnumMap을 통해 CardIdentifyType별 3999 전문 prfDvV1을 매핑하고,
* MCDTCO0SH003999.In.builder()로 전문 조립 및 검증을 수행한다.
*/
@Component
@RequiredArgsConstructor
public class CiIdentifyHandler implements CardIdentifyHandler {
private static final String INTN_SUCCESS_CODE = "0000";
private static final String SUCCESS_MSG = "정상 처리되었습니다.";
/** 카드 번호 없음 */
private static final String ERROR_50001 = "50001";
/** 유효기간 없음 */
private static final String ERROR_50002 = "50002";
/** 카드PWD 없음 */
private static final String ERROR_50003 = "50003";
/** CVV2 없음 */
private static final String ERROR_50004 = "50004";
/** CI 없음 */
private static final String ERROR_50005 = "50005";
private static final Map<CardIdentifyType, java.util.function.BiFunction<IdnvServiceInVo, MCDTCO0SH003999.In.InBuilder, Result<MCDTCO0SH003999.In>>> TYPE_FACTORIES = new EnumMap<>(CardIdentifyType.class);
static {
// 일반 카드 (Type 2)
TYPE_FACTORIES.put(CardIdentifyType.GENERAL_CARD_VALID_PIN, (in, builder) -> {
if (isBlank(in.getCardNo())) {
return Result.fail(ERROR_50001, "카드 번호 없음");
}
if (isBlank(in.getPwd())) {
return Result.fail(ERROR_50003, "카드PWD 없음");
}
return Result.ok(builder.prfDvV1("2")
.valdTlmV6(in.getValdTlm())
.cardPwdV20(in.getPwd())
.build());
});
// CI 카드 (Type 4)
TYPE_FACTORIES.put(CardIdentifyType.CI_CARD, (in, builder) -> {
if (isBlank(in.getCardNo())) {
return Result.fail(ERROR_50001, "카드 번호 없음");
}
if (isBlank(in.getCi())) {
return Result.fail(ERROR_50005, "CI 없음");
}
return Result.ok(builder.prfDvV1("7")
.encMthdDvV1("4")
.prfExcpDvV1("0")
.ciV88(in.getCi())
.build());
});
// CI + 유효기간 + 비밀번호 (Type 5)
TYPE_FACTORIES.put(CardIdentifyType.CI_CARD_VALID_PIN, (in, builder) -> {
if (isBlank(in.getCardNo())) {
return Result.fail(ERROR_50001, "카드 번호 없음");
}
if (isBlank(in.getValdTlm())) {
return Result.fail(ERROR_50002, "유효기간 없음");
}
if (isBlank(in.getPwd())) {
return Result.fail(ERROR_50003, "카드PWD 없음");
}
if (isBlank(in.getCi())) {
return Result.fail(ERROR_50005, "CI 없음");
}
if (!CardUtil.isValidTlmV6(in.getValdTlm())) {
return Result.fail(ERROR_50002, "유효기간 형식 오류");
}
return Result.ok(builder.prfDvV1("7")
.encMthdDvV1("4")
.prfExcpDvV1("0")
.valdTlmV6(in.getValdTlm())
.cardPwdV20(in.getPwd())
.ciV88(in.getCi())
.build());
});
// CI + 유효기간 + CVC + 비밀번호 (Type 3)
TYPE_FACTORIES.put(CardIdentifyType.CI_CARD_VALID_CVC_PIN, (in, builder) -> {
if (isBlank(in.getCardNo())) {
return Result.fail(ERROR_50001, "카드 번호 없음");
}
if (isBlank(in.getValdTlm())) {
return Result.fail(ERROR_50002, "유효기간 없음");
}
if (isBlank(in.getPwd())) {
return Result.fail(ERROR_50003, "카드PWD 없음");
}
if (isBlank(in.getCvc2())) {
return Result.fail(ERROR_50004, "CVV2 없음");
}
if (isBlank(in.getCi())) {
return Result.fail(ERROR_50005, "CI 없음");
}
if (!CardUtil.isValidTlmV6(in.getValdTlm())) {
return Result.fail(ERROR_50002, "유효기간 형식 오류");
}
return Result.ok(builder.prfDvV1("1")
.encMthdDvV1("4")
.prfExcpDvV1("0")
.valdTlmV6(in.getValdTlm())
.cvc2V3(in.getCvc2())
.cardPwdV20(in.getPwd())
.ciV88(in.getCi())
.build());
});
}
private static final Set<CardIdentifyType> SUPPORTED_TYPES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(
CardIdentifyType.GENERAL_CARD_VALID_PIN,
CardIdentifyType.CI_CARD_VALID_CVC_PIN,
CardIdentifyType.CI_CARD,
CardIdentifyType.CI_CARD_VALID_PIN
))
);
private final BxiRouter bxiRouter;
private final ApplicationEventPublisher eventPublisher;
@Override
public Set<CardIdentifyType> getSupportedTypes() {
return SUPPORTED_TYPES;
}
@Override
public Result<IdnvServiceOutVo> handle(IdnvServiceInVo inVo, CardIdentifyType identifyType) {
// [1단계] TYPE_FACTORIES를 통한 검증 및 MCDTCO0SH003999.In 조립
Result<MCDTCO0SH003999.In> mciInResult = buildAndValidateMciIn(inVo, identifyType);
if (!mciInResult.isSuccess()) {
return Result.fail(mciInResult.getErrorCode(), mciInResult.getErrorMessage());
}
MCDTCO0SH003999.In mciIn = mciInResult.getValue();
// [2단계] 3999 통신, 비동기 이력 적재 이벤트 발행 및 응답 처리
return bxiRouter.send(mciIn, MCDTCO0SH003999.Out.class)
.flatMap(out -> {
eventPublisher.publishEvent(new CardIdentifyEvent(buildIdnvCtnt(mciIn, out, INTN_SUCCESS_CODE, SUCCESS_MSG)));
return processResponse(mciIn, out);
});
}
/**
* TYPE_FACTORIES 매핑 함수를 통해 필수값 검증 및 MCDTCO0SH003999.In 전문을 생성한다.
*/
private Result<MCDTCO0SH003999.In> buildAndValidateMciIn(IdnvServiceInVo inVo, CardIdentifyType identifyType) {
java.util.function.BiFunction<IdnvServiceInVo, MCDTCO0SH003999.In.InBuilder, Result<MCDTCO0SH003999.In>> factory = TYPE_FACTORIES.get(identifyType);
if (factory == null) {
return Result.fail("ERR_UNSUPPORTED_TYPE", "CiIdentifyHandler가 지원하지 않는 인증 타입입니다: " + identifyType);
}
if (isBlank(inVo.getCardNo())) {
return Result.fail(ERROR_50001, "카드 번호 없음");
}
String cardNo = inVo.getCardNo().trim();
if (!CardUtil.panLengthVaild(cardNo)) {
return Result.fail("ERR_INVALID_CARD_NO", "유효하지 않은 카드번호 길이 또는 형식입니다.");
}
MCDTCO0SH003999.In.InBuilder builder = MCDTCO0SH003999.In.builder()
.cardNov19(cardNo)
.memcNov4(inVo.getMemcNo())
.tridV32(inVo.getTrid())
.reqTimeV14(inVo.getReqTime());
return factory.apply(inVo, builder);
}
private Result<IdnvServiceOutVo> processResponse(MCDTCO0SH003999.In in, MCDTCO0SH003999.Out out) {
if (out.getOutpCardNov19() == null || out.getOutpCardNov19().trim().isEmpty()) {
return Result.fail("10030", "카드번호 미존재: MCI 응답 출력카드번호(outpCardNov19)가 누락되었습니다.");
}
String ci = (out.getCiV88() != null && !out.getCiV88().trim().isEmpty())
? out.getCiV88()
: (in != null ? in.getCiV88() : null);
return Result.ok(IdnvServiceOutVo.builder()
.rspCode(INTN_SUCCESS_CODE)
.rspMsg(SUCCESS_MSG)
.verifiedMethod("MCDTCO0SH003999")
.trid(in != null ? in.getTridV32() : null)
.getPrfRsltCdV2(out.getGetPrfRsltCdV2())
.outpCardNov19(out.getOutpCardNov19().trim())
.cardNov19(out.getCardNov19())
.valdTlmV6(out.getValdTlmV6())
.memcNov4(out.getMemcNov4())
.ciV88(ci)
.bizNov10(out.getBizNov10())
.cucoDvCdV1(out.getCucoDvCdV1())
.cardPrdCdV6(out.getCardPrdCdV6())
.cardBrndCdV2(out.getCardBrndCdV2())
.cardTypCdV1(out.getCardTypCdV1())
.crdtChkDvCdV1(out.getCrdtChkDvCdV1())
.corpIndvDvCdV1(out.getCorpIndvDvCdV1())
.famCardYnV1(out.getFamCardYnV1())
.cardStusCdV2(out.getCardStusCdV2())
.issBankCdV3(out.getIssBankCdV3())
.acntBankCdV3(out.getAcntBankCdV3())
.mobTelNov12(out.getMobTelNov12())
.custNmV40(out.getCustNmV40())
.brthDtV8(out.getBrthDtV8())
.sexCdV1(out.getSexCdV1())
.frnrYnV1(out.getFrnrYnV1())
.tknIssPsblYnV1(out.getTknIssPsblYnV1())
.incpRsonV30(out.getIncpRsonV30())
.hghNmV40(out.getHghNmV40())
.firmNoV7(out.getFirmNoV7())
.build());
}
private IdnvCtnt buildIdnvCtnt(MCDTCO0SH003999.In in, MCDTCO0SH003999.Out out, String intnCd, String msg) {
String trid = in != null ? in.getTridV32() : (out != null ? out.getTridV32() : null);
String rawRspCd = out != null ? out.getGetPrfRsltCdV2() : null;
String epan = out != null && out.getOutpCardNov19() != null
? out.getOutpCardNov19().trim()
: (in != null ? in.getCardNov19() : null);
IdnvCtnt ctnt = IdnvCtnt.builder()
.trid(trid)
.ifId(MCDTCO0SH003999.IF_ID)
.tlmRspCd(rawRspCd)
.tlmRspMsg(msg)
.intnCd(intnCd)
.intnMsg(msg)
.regDtim(LocalDateTime.now())
.build();
if (epan != null) {
ctnt.setEPAN_NO(epan);
}
return ctnt;
}
private static boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
}
}

View File

@ -0,0 +1,130 @@
package com.bccard.tsp.service.cardidentify.handler;
import com.bccard.tsp.adapt.bxi.BxiRouter;
import com.bccard.tsp.adapt.bxi.mci.vo.MCDTCO0SH003999;
import com.bccard.tsp.adapt.history.event.CardIdentifyEvent;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.service.cardidentify.CardIdentifyHandler;
import com.bccard.tsp.service.cardidentify.CardIdentifyType;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import com.bccard.tsp.vo.IdnvCtnt;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Set;
/**
* [외국인 식별정보(Type C) 본인인증 핸들러]
* - 3999 전문 송수신 및 비동기 이력 이벤트 발행
*/
@Component
@RequiredArgsConstructor
public class ForeignerIdentifyHandler implements CardIdentifyHandler {
private static final String INTN_SUCCESS_CODE = "0000";
private static final String SUCCESS_MSG = "정상 처리되었습니다.";
private static final Set<CardIdentifyType> SUPPORTED_TYPES = Collections.singleton(CardIdentifyType.FOREIGNER);
private final BxiRouter bxiRouter;
private final ApplicationEventPublisher eventPublisher;
@Override
public Set<CardIdentifyType> getSupportedTypes() {
return SUPPORTED_TYPES;
}
@Override
public Result<IdnvServiceOutVo> handle(IdnvServiceInVo inVo, CardIdentifyType identifyType) {
if (inVo.getForeignerIdInfo() == null || inVo.getForeignerIdInfo().trim().isEmpty()) {
return Result.fail("ERR_EMPTY_FOREIGNER_ID", "Type C 인증 시 외국인식별정보(foreignerIdInfo)는 필수입니다.");
}
MCDTCO0SH003999.In mciIn = MCDTCO0SH003999.In.builder()
.prfDvV1("C")
.frnrIdInfoV13(inVo.getForeignerIdInfo())
.cardPwdV20(inVo.getPwd())
.reqTimeV14(inVo.getReqTime())
.tridV32(inVo.getTrid())
.ciV88(inVo.getCi())
.memcNov4(inVo.getMemcNo())
.build();
return bxiRouter.send(mciIn, MCDTCO0SH003999.Out.class)
.flatMap(out -> {
eventPublisher.publishEvent(new CardIdentifyEvent(buildIdnvCtnt(mciIn, out, INTN_SUCCESS_CODE, SUCCESS_MSG)));
return processResponse(mciIn, out);
});
}
private Result<IdnvServiceOutVo> processResponse(MCDTCO0SH003999.In in, MCDTCO0SH003999.Out out) {
if (out.getOutpCardNov19() == null || out.getOutpCardNov19().trim().isEmpty()) {
return Result.fail("10030", "카드번호 미존재: MCI 응답 출력카드번호(outpCardNov19)가 누락되었습니다.");
}
String ci = (out.getCiV88() != null && !out.getCiV88().trim().isEmpty())
? out.getCiV88()
: (in != null ? in.getCiV88() : null);
IdnvServiceOutVo outVo = IdnvServiceOutVo.builder()
.rspCode(INTN_SUCCESS_CODE)
.rspMsg(SUCCESS_MSG)
.verifiedMethod("MCDTCO0SH003999")
.trid(in != null ? in.getTridV32() : null)
.getPrfRsltCdV2(out.getGetPrfRsltCdV2())
.outpCardNov19(out.getOutpCardNov19().trim())
.cardNov19(out.getCardNov19())
.valdTlmV6(out.getValdTlmV6())
.memcNov4(out.getMemcNov4())
.ciV88(ci)
.bizNov10(out.getBizNov10())
.cucoDvCdV1(out.getCucoDvCdV1())
.cardPrdCdV6(out.getCardPrdCdV6())
.cardBrndCdV2(out.getCardBrndCdV2())
.cardTypCdV1(out.getCardTypCdV1())
.crdtChkDvCdV1(out.getCrdtChkDvCdV1())
.corpIndvDvCdV1(out.getCorpIndvDvCdV1())
.famCardYnV1(out.getFamCardYnV1())
.cardStusCdV2(out.getCardStusCdV2())
.issBankCdV3(out.getIssBankCdV3())
.acntBankCdV3(out.getAcntBankCdV3())
.mobTelNov12(out.getMobTelNov12())
.custNmV40(out.getCustNmV40())
.brthDtV8(out.getBrthDtV8())
.sexCdV1(out.getSexCdV1())
.frnrYnV1(out.getFrnrYnV1())
.tknIssPsblYnV1(out.getTknIssPsblYnV1())
.incpRsonV30(out.getIncpRsonV30())
.hghNmV40(out.getHghNmV40())
.firmNoV7(out.getFirmNoV7())
.build();
return Result.ok(outVo);
}
private IdnvCtnt buildIdnvCtnt(MCDTCO0SH003999.In in, MCDTCO0SH003999.Out out, String intnCd, String msg) {
String trid = in != null ? in.getTridV32() : (out != null ? out.getTridV32() : null);
String rawRspCd = out != null ? out.getGetPrfRsltCdV2() : null;
String epan = out != null && out.getOutpCardNov19() != null
? out.getOutpCardNov19().trim()
: (in != null ? in.getCardNov19() : null);
IdnvCtnt ctnt = IdnvCtnt.builder()
.trid(trid)
.ifId(MCDTCO0SH003999.IF_ID)
.tlmRspCd(rawRspCd)
.tlmRspMsg(msg)
.intnCd(intnCd)
.intnMsg(msg)
.regDtim(LocalDateTime.now())
.build();
if (epan != null) {
ctnt.setEPAN_NO(epan);
}
return ctnt;
}
}

View File

@ -0,0 +1,130 @@
package com.bccard.tsp.service.cardidentify.handler;
import com.bccard.tsp.adapt.bxi.BxiRouter;
import com.bccard.tsp.adapt.bxi.mci.vo.MCDTCO0SH003999;
import com.bccard.tsp.adapt.history.event.CardIdentifyEvent;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.service.cardidentify.CardIdentifyHandler;
import com.bccard.tsp.service.cardidentify.CardIdentifyType;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import com.bccard.tsp.vo.IdnvCtnt;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Set;
/**
* [구 토큰(Type A) 본인인증 핸들러]
* - 3999 전문 송수신 및 비동기 이력 이벤트 발행
*/
@Component
@RequiredArgsConstructor
public class OldTokenIdentifyHandler implements CardIdentifyHandler {
private static final String INTN_SUCCESS_CODE = "0000";
private static final String SUCCESS_MSG = "정상 처리되었습니다.";
private static final Set<CardIdentifyType> SUPPORTED_TYPES = Collections.singleton(CardIdentifyType.OLDTOKEN_CI);
private final BxiRouter bxiRouter;
private final ApplicationEventPublisher eventPublisher;
@Override
public Set<CardIdentifyType> getSupportedTypes() {
return SUPPORTED_TYPES;
}
@Override
public Result<IdnvServiceOutVo> handle(IdnvServiceInVo inVo, CardIdentifyType identifyType) {
if (inVo.getOldToken() == null || inVo.getOldToken().trim().isEmpty()) {
return Result.fail("ERR_EMPTY_OLD_TOKEN", "Type A 인증 시 구토큰(oldToken)은 필수입니다.");
}
MCDTCO0SH003999.In mciIn = MCDTCO0SH003999.In.builder()
.prfDvV1("A")
.oldTokenV19(inVo.getOldToken())
.cardPwdV20(inVo.getPwd())
.reqTimeV14(inVo.getReqTime())
.tridV32(inVo.getTrid())
.ciV88(inVo.getCi())
.memcNov4(inVo.getMemcNo())
.build();
return bxiRouter.send(mciIn, MCDTCO0SH003999.Out.class)
.flatMap(out -> {
eventPublisher.publishEvent(new CardIdentifyEvent(buildIdnvCtnt(mciIn, out, INTN_SUCCESS_CODE, SUCCESS_MSG)));
return processResponse(mciIn, out);
});
}
private Result<IdnvServiceOutVo> processResponse(MCDTCO0SH003999.In in, MCDTCO0SH003999.Out out) {
if (out.getOutpCardNov19() == null || out.getOutpCardNov19().trim().isEmpty()) {
return Result.fail("10030", "카드번호 미존재: MCI 응답 출력카드번호(outpCardNov19)가 누락되었습니다.");
}
String ci = (out.getCiV88() != null && !out.getCiV88().trim().isEmpty())
? out.getCiV88()
: (in != null ? in.getCiV88() : null);
IdnvServiceOutVo outVo = IdnvServiceOutVo.builder()
.rspCode(INTN_SUCCESS_CODE)
.rspMsg(SUCCESS_MSG)
.verifiedMethod("MCDTCO0SH003999")
.trid(in != null ? in.getTridV32() : null)
.getPrfRsltCdV2(out.getGetPrfRsltCdV2())
.outpCardNov19(out.getOutpCardNov19().trim())
.cardNov19(out.getCardNov19())
.valdTlmV6(out.getValdTlmV6())
.memcNov4(out.getMemcNov4())
.ciV88(ci)
.bizNov10(out.getBizNov10())
.cucoDvCdV1(out.getCucoDvCdV1())
.cardPrdCdV6(out.getCardPrdCdV6())
.cardBrndCdV2(out.getCardBrndCdV2())
.cardTypCdV1(out.getCardTypCdV1())
.crdtChkDvCdV1(out.getCrdtChkDvCdV1())
.corpIndvDvCdV1(out.getCorpIndvDvCdV1())
.famCardYnV1(out.getFamCardYnV1())
.cardStusCdV2(out.getCardStusCdV2())
.issBankCdV3(out.getIssBankCdV3())
.acntBankCdV3(out.getAcntBankCdV3())
.mobTelNov12(out.getMobTelNov12())
.custNmV40(out.getCustNmV40())
.brthDtV8(out.getBrthDtV8())
.sexCdV1(out.getSexCdV1())
.frnrYnV1(out.getFrnrYnV1())
.tknIssPsblYnV1(out.getTknIssPsblYnV1())
.incpRsonV30(out.getIncpRsonV30())
.hghNmV40(out.getHghNmV40())
.firmNoV7(out.getFirmNoV7())
.build();
return Result.ok(outVo);
}
private IdnvCtnt buildIdnvCtnt(MCDTCO0SH003999.In in, MCDTCO0SH003999.Out out, String intnCd, String msg) {
String trid = in != null ? in.getTridV32() : (out != null ? out.getTridV32() : null);
String rawRspCd = out != null ? out.getGetPrfRsltCdV2() : null;
String epan = out != null && out.getOutpCardNov19() != null
? out.getOutpCardNov19().trim()
: (in != null ? in.getCardNov19() : null);
IdnvCtnt ctnt = IdnvCtnt.builder()
.trid(trid)
.ifId(MCDTCO0SH003999.IF_ID)
.tlmRspCd(rawRspCd)
.tlmRspMsg(msg)
.intnCd(intnCd)
.intnMsg(msg)
.regDtim(LocalDateTime.now())
.build();
if (epan != null) {
ctnt.setEPAN_NO(epan);
}
return ctnt;
}
}

View File

@ -0,0 +1,47 @@
package com.bccard.tsp.service.cardidentify.impl;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 카드 본인인증 및 결제토큰 기등록 검증이 모두 통과한 후,
* 인증된 고객 정보(TB_CUST_INFO)와 카드 정보(TB_CARD_INFO)를 단일 트랜잭션으로 DB에 적재하는 서비스
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class CardCustomerPersistService {
private final CardCustomerRepository cardCustomerRepository;
/**
* 고객 원장 및 카드 원장 테이블에 인증 결과를 적재한다.
* 대외 MCI 네트워크 통신이 완전히 끝난 뒤 실행되므로 DB 커넥션 점유 시간을 최소화한다.
*
* @param outVo 본인인증 및 기등록 검증을 통과한 출력 VO
* @return 성공 시 Result.ok(outVo), DB 적재 오류 시 Result.fail("50005", ...)
*/
@Transactional
public Result<IdnvServiceOutVo> saveCardAndCustomerInfo(IdnvServiceOutVo outVo) {
if (outVo == null) {
return Result.fail("50004", "저장할 카드/고객 인증 결과 데이터가 존재하지 않습니다.");
}
try {
// 1. 고객 정보(TB_CUST_INFO) Upsert
cardCustomerRepository.upsertCustomerInfo(outVo);
// 2. 카드 정보(TB_CARD_INFO) Upsert
cardCustomerRepository.upsertCardInfo(outVo);
return Result.ok(outVo);
} catch (Exception e) {
log.error("[CardCustomerPersistService] 카드/고객 정보 DB 적재 중 오류 발생 - trid={}", outVo.getTrid(), e);
return Result.fail("50005", "카드 및 고객 정보 DB 저장 실패: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,34 @@
package com.bccard.tsp.service.cardidentify.impl;
import com.bccard.tsp.common.util.CardUtil;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
/**
* [고객/카드 원장 저장소/매퍼]
* TB_CUST_INFO, TB_CARD_INFO 원장 적재 전담 리포지토리
*/
@Slf4j
@Repository
public class CardCustomerRepository {
/**
* TB_CUST_INFO 테이블에 인증된 고객 정보를 적재(Upsert)한다.
*/
public int upsertCustomerInfo(IdnvServiceOutVo outVo) {
log.info("[CardCustomerRepository] upsertCustomerInfo 고객정보 DB 적재 완료 - trid={}, custNm={}, ci={}, bizNo={}",
outVo.getTrid(), outVo.getCustNmV40(), outVo.getCiV88(), outVo.getBizNov10());
return 1;
}
/**
* TB_CARD_INFO 테이블에 인증된 카드 정보를 적재(Insert/Upsert)한다.
*/
public int upsertCardInfo(IdnvServiceOutVo outVo) {
String rawCardNo = outVo.getOutpCardNov19() != null ? outVo.getOutpCardNov19() : outVo.getCardNov19();
log.info("[CardCustomerRepository] upsertCardInfo 카드정보 DB 적재 완료 - trid={}, cardNo={}, cardPrdCd={}, issBankCd={}",
outVo.getTrid(), CardUtil.maskCardNo(rawCardNo), outVo.getCardPrdCdV6(), outVo.getIssBankCdV3());
return 1;
}
}

View File

@ -0,0 +1,58 @@
package com.bccard.tsp.service.cardidentify.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 레거시 카드 본인인증 입력 VO
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class IdnvServiceInVo {
/** 인증구분코드 ("2", "3", "4", "5", "6", "8", "9", "A", "C") */
private String prfDvV1;
/** 카드번호 */
private String cardNo;
/** 유효기한 (YYMM) */
private String valdTlm;
/** 비밀번호 */
private String pwd;
/** CVC2 */
private String cvc2;
/** 요청일시 */
private String reqTime;
/** 트랜잭션 ID */
private String trid;
/** 연계정보 (CI) */
private String ci;
/** 사업자번호 */
private String bizNo;
/** 신청번호 (Type 9) */
private String aplcNo;
/** 회원사번호 (Type 9) */
private String memcNo;
/** 구 토큰 (Type A) */
private String oldToken;
/** 외국인 식별정보 (Type C) */
private String foreignerIdInfo;
/** 머니카드 권종번호 (BcMoney) */
private String mnyTypNo;
}

View File

@ -0,0 +1,131 @@
package com.bccard.tsp.service.cardidentify.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 카드 본인인증 표준 출력 VO
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class IdnvServiceOutVo {
/** 내부 응답 코드 (예: "0000" 성공) */
private String rspCode;
/** 응답 메시지 */
private String rspMsg;
/** 인증된 방법 식별자 (예: "identifyCard", "identifyBcMoney1", "MCDTCO0SH003999" 등) */
private String verifiedMethod;
/** 트랜잭션 ID */
private String trid;
// --- MCI 본인인증 응답 매핑 필드 (20여 개) ---
/** 인증결과코드 (2자리) */
private String getPrfRsltCdV2;
/** 출력카드번호 (19자리) */
private String outpCardNov19;
/** 카드번호 (19자리) */
private String cardNov19;
/** 유효기한 (6자리) */
private String valdTlmV6;
/** 회원사번호 (4자리) */
private String memcNov4;
/** 연계정보 CI (88자리) */
private String ciV88;
/** 사업자등록번호 (10자리) */
private String bizNov10;
/** 고객구분코드 (1자리) */
private String cucoDvCdV1;
/** 카드상품코드 (6자리) */
private String cardPrdCdV6;
/** 카드브랜드코드 (2자리) */
private String cardBrndCdV2;
/** 카드유형코드 (1자리) */
private String cardTypCdV1;
/** 신용체크구분코드 (1자리) */
private String crdtChkDvCdV1;
/** 법인개인구분코드 (1자리) */
private String corpIndvDvCdV1;
/** 가족카드여부 (1자리) */
private String famCardYnV1;
/** 카드상태코드 (2자리) */
private String cardStusCdV2;
/** 발급은행코드 (3자리) */
private String issBankCdV3;
/** 결제계좌은행코드 (3자리) */
private String acntBankCdV3;
/** 휴대폰번호 (12자리) */
private String mobTelNov12;
/** 고객명 (40자리) */
private String custNmV40;
/** 생년월일 (8자리) */
private String brthDtV8;
/** 성별코드 (1자리) */
private String sexCdV1;
/** 외국인여부 (1자리) */
private String frnrYnV1;
/** 토큰발급가능여부 (1자리) */
private String tknIssPsblYnV1;
// --- DB 결제토큰 기등록 조회 결과 필드 ---
/** 기등록 결제토큰 번호 */
private String payTokenNo;
/** 기등록 결제토큰 상태코드 (예: "00" 정상) */
private String payTokenStatCd;
/** 기등록 결제토큰 등록일시 */
private String payTokenRegDtm;
/** 불능사유 (30자리) */
private String incpRsonV30;
/** 한글성명 (40자리) */
private String hghNmV40;
/** 업체번호 (7자리) */
private String firmNoV7;
/** 카드 클래스/구분코드 (코나 선불="3" 등) */
private String cardClss;
/** 암호화된 카드번호 */
private String epanno;
/** 마스킹된 카드번호 */
private String mpanno;
/** 가상카드번호 (VCN) */
private String vcnNo;
}

View File

@ -0,0 +1,41 @@
package com.bccard.tsp.service.token;
import org.springframework.stereotype.Repository;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* [결제토큰 저장소/매퍼]
* DB 결제토큰 원장 조회 전담 리포지토리
*/
@Repository
public class PaymentTokenRepository {
private static final Map<String, Map<String, String>> REGISTERED_PAYMENT_TOKENS;
static {
Map<String, Map<String, String>> tokenDb = new HashMap<String, Map<String, String>>();
Map<String, String> sampleToken = new HashMap<String, String>();
sampleToken.put("payTokenNo", "TKN_9999888877776666");
sampleToken.put("payTokenStatCd", "00");
sampleToken.put("payTokenRegDtm", "20261105120000");
// 기등록 테스트용 카드번호 등록
tokenDb.put("9999888877776666", Collections.unmodifiableMap(sampleToken));
REGISTERED_PAYMENT_TOKENS = Collections.unmodifiableMap(tokenDb);
}
/**
* 카드번호로 DB에 이미 발급되어 있는 결제토큰 정보를 조회한다.
*
* @param cardNo 조회할 카드번호
* @return 기등록 결제토큰 정보 Map (없으면 null)
*/
public Map<String, String> selectPaymentTokenByCardNo(String cardNo) {
if (cardNo == null || cardNo.trim().isEmpty()) {
return null;
}
return REGISTERED_PAYMENT_TOKENS.get(cardNo.trim());
}
}

View File

@ -0,0 +1,69 @@
package com.bccard.tsp.service.token;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* 결제토큰 검증 및 발급/관리 서비스
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class TokenService {
public static final String ERR_ALREADY_REGISTERED_CODE = "50099";
public static final String ERR_ALREADY_REGISTERED_MSG = "이미 등록된 결제토큰이 존재합니다.";
private final PaymentTokenRepository paymentTokenRepository;
/**
* 카드 본인인증 결과 VO의 카드번호로 DB 기등록 결제토큰 여부를 조회/검증한다.
* 기등록 토큰이 존재할 경우 기등록 오류(Result.fail)를 발생시키되, 조회된 결과(IdnvServiceOutVo)를 함께 담아 반환한다.
*
* @param outVo 카드 본인인증 완료 출력 VO
* @return 미등록 시 Result.ok(outVo), 기등록 시 Result.fail("50099", 메시지, 조회결과가 세팅된 outVo)
*/
public Result<IdnvServiceOutVo> verifyNotAlreadyRegistered(IdnvServiceOutVo outVo) {
if (outVo == null) {
return Result.fail("50004", "본인인증 결과 데이터가 존재하지 않습니다.");
}
String cardNo = resolveCardNo(outVo);
if (cardNo == null || cardNo.isEmpty()) {
return Result.ok(outVo);
}
Map<String, String> existingToken = paymentTokenRepository.selectPaymentTokenByCardNo(cardNo);
if (existingToken != null && !existingToken.isEmpty()) {
// 조회된 결제토큰 정보를 출력 VO에 세팅하고 응답코드를 기등록 오류 코드로 갱신
outVo.setRspCode(ERR_ALREADY_REGISTERED_CODE);
outVo.setRspMsg(ERR_ALREADY_REGISTERED_MSG);
outVo.setPayTokenNo(existingToken.get("payTokenNo"));
outVo.setPayTokenStatCd(existingToken.get("payTokenStatCd"));
outVo.setPayTokenRegDtm(existingToken.get("payTokenRegDtm"));
log.warn("[TokenService] 기등록 결제토큰 감지 - trid={}, payTokenNo={}",
outVo.getTrid(), outVo.getPayTokenNo());
// 기등록 오류를 발생시키면서 조회된 결과(outVo)를 함께 리턴!
return Result.fail(ERR_ALREADY_REGISTERED_CODE, ERR_ALREADY_REGISTERED_MSG, outVo);
}
return Result.ok(outVo);
}
private String resolveCardNo(IdnvServiceOutVo outVo) {
if (outVo.getOutpCardNov19() != null && !outVo.getOutpCardNov19().trim().isEmpty()) {
return outVo.getOutpCardNov19().trim();
}
if (outVo.getCardNov19() != null && !outVo.getCardNov19().trim().isEmpty()) {
return outVo.getCardNov19().trim();
}
return null;
}
}

View File

@ -0,0 +1,51 @@
package com.bccard.tsp.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
* [카드 본인인증 연계내역 이력 VO]
* - DB 이력 테이블(TB_IDNV_LKG_CTNTN) 매핑 VO
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class IdnvCtnt {
/** 거래번호 (32자리) */
private String trid;
/** 전문명 / 인터페이스 ID (예: MCDTCO0SH003999, MCDTCO0SH004050) */
private String ifId;
/** 전문 원본 응답값 (결과코드: 00, 01, 02 등) */
private String tlmRspCd;
/** 전문 원본 응답 메시지 */
private String tlmRspMsg;
/** 내부 코드로 변환된 메시지 */
private String intnMsg;
/** 내부 오류/결과 코드 */
private String intnCd;
/** 등록일시 */
private LocalDateTime regDtim;
/** 카드번호 (EPAN_NO) */
private String epanNo;
public void setEPAN_NO(String epan) {
this.epanNo = epan;
}
public String getEPAN_NO() {
return this.epanNo;
}
}

View File

@ -0,0 +1,49 @@
package com.bccard.tsp.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* W010 컨트롤러 토큰 등록 요청 입력 VO (W010In)
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class W010In {
/** 인증구분코드 ("2", "3", "4", "5", "6", "8", "9", "A", "C") */
private String prfDvV1;
/** 암호화된 카드 정보 문자열 (복호화 시 [0]=cardNo, [1]=yymm, [2]=cvc2, [3]=pwd) */
private String encData;
/** 요청일시 */
private String reqTime;
/** 트랜잭션 ID */
private String trid;
/** 연계정보 (CI) */
private String ci;
/** 사업자번호 */
private String bizNo;
/** 신청번호 (Type 9) */
private String aplcNo;
/** 회원사번호 (Type 9) */
private String memcNo;
/** 구 토큰 (Type A) */
private String oldToken;
/** 외국인 식별정보 (Type C) */
private String foreignerIdInfo;
/** 머니카드 권종번호 (BcMoney) */
private String mnyTypNo;
}

View File

@ -0,0 +1,2 @@
server.port=8080
spring.application.name=tsp-core

View File

@ -0,0 +1,251 @@
package com.bccard.tsp.controller;
import com.bccard.tsp.common.Result;
import com.bccard.tsp.service.cardidentify.CardIdentifyDispatcher;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceInVo;
import com.bccard.tsp.service.cardidentify.vo.IdnvServiceOutVo;
import com.bccard.tsp.vo.W010In;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
class W010ControllerVisitorTest {
@Autowired
private CardIdentifyDispatcher cardIdentifyDispatcher;
@Autowired
private W010Controller w010Controller;
@Test
@DisplayName("CI 개인카드 Type 3 요청 시 CiIdentifyHandler(MCDTCO0SH003999)가 실행된다")
void testCiCardType3() {
IdnvServiceInVo inVo = IdnvServiceInVo.builder()
.prfDvV1("3")
.cardNo("1234567812345678")
.valdTlm("2812")
.cvc2("123")
.pwd("12")
.ci("CI-SAMPLE-001")
.trid("TR-CI-003")
.build();
Result<IdnvServiceOutVo> result = cardIdentifyDispatcher.dispatch(inVo);
assertThat(result.isSuccess()).isTrue();
assertThat(result.getValue().getVerifiedMethod()).isEqualTo("MCDTCO0SH003999");
assertThat(result.getValue().getOutpCardNov19()).isEqualTo("1234567812345678");
}
@Test
@DisplayName("법인카드 Type 8 요청 시 BiznoIdentifyHandler(MCDTCO0SH003999)로 매핑되어 실행된다")
void testBiznoCardType8() {
IdnvServiceInVo inVo = IdnvServiceInVo.builder()
.prfDvV1("8")
.cardNo("1234567812345678")
.valdTlm("2812")
.cvc2("123")
.pwd("12")
.bizNo("1234567890")
.trid("TR-BIZ-008")
.build();
Result<IdnvServiceOutVo> result = cardIdentifyDispatcher.dispatch(inVo);
assertThat(result.isSuccess()).isTrue();
assertThat(result.getValue().getVerifiedMethod()).isEqualTo("MCDTCO0SH003999");
}
@Test
@DisplayName("법인카드 Type 6 요청 시 BiznoIdentifyHandler(MCDTCO0SH003999)로 매핑되어 실행된다")
void testBiznoCardType6() {
IdnvServiceInVo inVo = IdnvServiceInVo.builder()
.prfDvV1("6")
.cardNo("1234567812345678")
.bizNo("1234567890")
.trid("TR-BIZ-006")
.build();
Result<IdnvServiceOutVo> result = cardIdentifyDispatcher.dispatch(inVo);
assertThat(result.isSuccess()).isTrue();
assertThat(result.getValue().getVerifiedMethod()).isEqualTo("MCDTCO0SH003999");
}
@Test
@DisplayName("일반 카드 유효기한 형식 오류 시 예외를 던지지 않고 Result.fail(50002)을 반환한다")
void testInvalidValdTlmReturnsFailResult() {
IdnvServiceInVo inVo = IdnvServiceInVo.builder()
.prfDvV1("3")
.cardNo("1234567812345678")
.valdTlm("2819") // 19월 -> 잘못된 유효기한
.trid("TR-ERR-50002")
.build();
Result<IdnvServiceOutVo> result = cardIdentifyDispatcher.dispatch(inVo);
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorCode()).isEqualTo("50002");
assertThat(result.getErrorMessage()).isEqualTo("유효기간 형식 오류");
}
@Test
@DisplayName("머니카드 BIN(944100) + Type 3 요청 시 BcMoneyIdentifyHandler(MCDTCO0SH004050)가 실행된다")
void testMoneyCardType3() {
IdnvServiceInVo inVo = IdnvServiceInVo.builder()
.prfDvV1("3")
.cardNo("9441001234567812")
.valdTlm("2812")
.cvc2("999")
.pwd("34")
.trid("TR-MNY-003")
.build();
Result<IdnvServiceOutVo> result = cardIdentifyDispatcher.dispatch(inVo);
assertThat(result.isSuccess()).isTrue();
assertThat(result.getValue().getVerifiedMethod()).isEqualTo("MCDTCO0SH004050");
}
@Test
@DisplayName("머니카드 BIN(944100) + Type 4 요청 시 MCDTCO0SH004050으로 실행된다")
void testMoneyCardType4() {
IdnvServiceInVo inVo = IdnvServiceInVo.builder()
.prfDvV1("4")
.cardNo("9441001234567812")
.ci("CI-VALUE-123")
.trid("TR-MNY-004")
.build();
Result<IdnvServiceOutVo> result = cardIdentifyDispatcher.dispatch(inVo);
assertThat(result.isSuccess()).isTrue();
assertThat(result.getValue().getVerifiedMethod()).isEqualTo("MCDTCO0SH004050");
}
@Test
@DisplayName("머니카드 BIN(944100) + Type 5 요청 시 MCDTCO0SH004050으로 실행된다")
void testMoneyCardType5() {
IdnvServiceInVo inVo = IdnvServiceInVo.builder()
.prfDvV1("5")
.cardNo("9441009988887777")
.valdTlm("2812")
.pwd("56")
.trid("TR-MNY-005")
.build();
Result<IdnvServiceOutVo> result = cardIdentifyDispatcher.dispatch(inVo);
assertThat(result.isSuccess()).isTrue();
assertThat(result.getValue().getVerifiedMethod()).isEqualTo("MCDTCO0SH004050");
}
@Test
@DisplayName("신청번호(Type 9), 구토큰(Type A), 외국인(Type C) 각각의 전담 핸들러와 3999 전문으로 디스패치된다")
void testSpecialTypes9AC() {
// Type 9
IdnvServiceInVo type9Vo = IdnvServiceInVo.builder().prfDvV1("9").aplcNo("APLC-001").trid("TR-9").build();
assertThat(cardIdentifyDispatcher.dispatch(type9Vo).getValue().getVerifiedMethod()).isEqualTo("MCDTCO0SH003999");
// Type A
IdnvServiceInVo typeAVo = IdnvServiceInVo.builder().prfDvV1("A").oldToken("TOK-OLD-01").trid("TR-A").build();
assertThat(cardIdentifyDispatcher.dispatch(typeAVo).getValue().getVerifiedMethod()).isEqualTo("MCDTCO0SH003999");
// Type C
IdnvServiceInVo typeCVo = IdnvServiceInVo.builder().prfDvV1("C").cardNo("5555444433332222").foreignerIdInfo("F-123").trid("TR-C").build();
assertThat(cardIdentifyDispatcher.dispatch(typeCVo).getValue().getVerifiedMethod()).isEqualTo("MCDTCO0SH003999");
}
@Test
@DisplayName("W010Controller 기존 identify 엔드포인트는 호출 차단(403 FORBIDDEN)된다")
void testLegacyIdentifyBlocked() {
IdnvServiceInVo validVo = IdnvServiceInVo.builder()
.prfDvV1("2")
.cardNo("1111222233334444")
.trid("TR-CTRL-001")
.build();
ResponseEntity<Map<String, Object>> response = w010Controller.identifyCard(validVo);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(response.getBody()).containsEntry("success", Boolean.FALSE);
assertThat(response.getBody()).containsEntry("errorCode", "ERR_DEPRECATED_ENDPOINT");
}
@Test
@DisplayName("카드 본인인증 성공 후 DB에 기등록된 결제토큰이 존재하면 기등록 오류(50099)를 발생시키고 조회된 결과(data)를 함께 리턴한다")
void testAlreadyRegisteredPaymentTokenReturnsFailWithQueriedData() {
W010In alreadyRegisteredReq = W010In.builder()
.prfDvV1("2")
.encData("9999888877776666|2812||") // DB에 기등록 결제토큰이 존재하는 카드번호
.trid("TR-DUP-TOKEN-001")
.build();
ResponseEntity<Map<String, Object>> response = w010Controller.tokenReg(alreadyRegisteredReq);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
Map<String, Object> body = response.getBody();
assertThat(body).isNotNull();
assertThat(body).containsEntry("status", "FAIL");
assertThat(body).containsEntry("code", "50099");
assertThat(body).containsEntry("message", "이미 등록된 결제토큰이 존재합니다.");
// 실패 응답이지만 조회된 카드본인인증 + 기등록 결제토큰 결과(IdnvServiceOutVo)가 data에 함께 포함되어 리턴됨
assertThat(body).containsKey("data");
IdnvServiceOutVo data = (IdnvServiceOutVo) body.get("data");
assertThat(data.getRspCode()).isEqualTo("50099");
assertThat(data.getOutpCardNov19()).isEqualTo("9999888877776666");
assertThat(data.getPayTokenNo()).isEqualTo("TKN_9999888877776666");
assertThat(data.getPayTokenStatCd()).isEqualTo("00");
}
@Test
@DisplayName("tokenReg 엔드포인트에서 CryptoDataParser 및 createFromRaw 파이프라인이 정상 동작한다")
void testTokenRegWithCryptoDataParser() {
// 정상 케이스: [0]=cardNo, [1]=yymm(2812 -> 202812), [2]=cvc2, [3]=pwd
W010In validReq = W010In.builder()
.prfDvV1("3")
.encData("1234567812345678|2812|123|12")
.trid("TR-TOKEN-REG-01")
.build();
ResponseEntity<Map<String, Object>> okRes = w010Controller.tokenReg(validReq);
assertThat(okRes.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(okRes.getBody()).containsEntry("status", "SUCCESS");
// Type 3 필수값(CVC2) 누락 케이스
W010In missingCvcReq = W010In.builder()
.prfDvV1("3")
.encData("1234567812345678|2812||12")
.trid("TR-TOKEN-REG-ERR")
.build();
ResponseEntity<Map<String, Object>> failRes = w010Controller.tokenReg(missingCvcReq);
assertThat(failRes.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(failRes.getBody()).containsEntry("status", "FAIL");
assertThat(failRes.getBody()).containsEntry("code", "50004");
}
@Test
@DisplayName("디스패치 후처리: 코나 선불 BIN(946044) 카드 요청 시 cardClss가 3으로 자동 세팅되고 mpanno 마스킹이 적용된다")
void testKonaBinPostProcessing() {
IdnvServiceInVo inVo = IdnvServiceInVo.builder()
.prfDvV1("3")
.cardNo("9460441234567890")
.valdTlm("2812")
.cvc2("123")
.pwd("12")
.ci("CI-KONA-01")
.trid("TR-KONA-001")
.build();
Result<IdnvServiceOutVo> result = cardIdentifyDispatcher.dispatch(inVo);
assertThat(result.isSuccess()).isTrue();
IdnvServiceOutVo outVo = result.getValue();
assertThat(outVo.getCardClss()).isEqualTo("3");
assertThat(outVo.getMpanno()).isEqualTo("946044******7890");
}
}