Tech/Spring | Spring Boot
[SpringBootJPA] 카카오페이 결제API (결제취소)
싱브이
2024. 8. 1. 21:41
728x90
반응형
이전 글에서 카카오페이 결제 API (단건결제)를 구현해보았다.
결제를 취소하는 api도 구현해보려고 한다.
결제 취소
결제 취소는 결제 고유번호 (tid)에 해당하는 결제 건에 대해서 취소를 요청하는 것이다.
그래서 나는 아직 tid를 저장하는 로직으로 구성하지 않았기 때문에 tid를 따로 넣어서 취소 요청하는 것으로 구현을 해볼 것이다.
[KakaoCancelResponse]
@Getter
@Setter
@ToString
public class KakaoCancelResponse {
private String aid; // 요청 고유 번호
private String tid; // 결제 고유 번호
private String cid; // 가맹점 코드
private String status; // 결제 상태
private String partner_order_id; // 가맹점 주문 번호
private String partner_user_id; // 가맹점 회원 ID
private String payment_method_type; // 결제 수단
private Amount amount; // 결제 금액 정보, 결제 요청 구현할때 이미 구현해놓음
private ApprovedCancelAmount approved_cancel_amount; // 이번 요청으로 취소된 금액
private CanceledAmount canceled_amount; // 누계 취소 금액
private CancelAvailableAmount cancel_available_amount; // 남은 취소 금액
private String item_name; // 상품 이름
private String item_code; // 상품 코드
private int quantity; // 상품 수량
private String created_at; // 결제 준비 요청 시각
private String approved_at; // 결제 승인 시각
private String canceled_at; // 결제 취소 시각
private String payload; // 취소 요청 시 전달한 값
/**
* 이번 요청으로 취소된 금액
*/
@Getter
@Setter
@ToString
public static class ApprovedCancelAmount {
private int total; // 이번 요청으로 취소된 전체 금액
private int tax_free; // 이번 요청으로 취소된 비과세 금액
private int vat; // 이번 요청으로 취소된 부가세 금액
private int point; // 이번 요청으로 취소된 포인트 금액
private int discount; // 이번 요청으로 취소된 할인 금액
private int green_deposit; // 컵 보증금
}
/**
* 누계 취소 금액
*/
@Getter
@Setter
@ToString
public static class CanceledAmount {
private int total; // 취소된 전체 누적 금액
private int tax_free; // 취소된 비과세 누적 금액
private int vat; // 취소된 부가세 누적 금액
private int point; // 취소된 포인트 누적 금액
private int discount; // 취소된 할인 누적 금액
private int green_deposit; // 컵 보증금
}
/**
* 취소 요청 시 전달한 값
*/
@Getter
@Setter
@ToString
public static class CancelAvailableAmount {
private int total; // 전체 취소 가능 금액
private int tax_free; // 취소 가능 비과세 금액
private int vat; // 취소 가능 부가세 금액
private int point; // 취소 가능 포인트 금액
private int discount; // 취소 가능 할인 금액
private int green_deposit; // 컵 보증금
}
}
Request
[service]
@Service
@RequiredArgsConstructor
@Transactional
@Slf4j
public class KakaoPayService {
private final KakaoPayProperties payProperties;
private RestTemplate restTemplate = new RestTemplate();
private KakaoReadyResponse kakaoReady;
private HttpHeaders getHeaders() {
. . .
}
/**
* 결제 완료 승인
*/
public KakaoReadyResponse kakaoPayReady() {
. . .
}
/**
* 결제 완료 승인
*/
public KakaoApproveResponse approveResponse (String pgToken){
. . .
}
/**
* 결제 환불
*/
public KakaoCancelResponse kakaoCancel(String tid) {
// 카카오페이 요청
Map<String, String> parameters = new HashMap<>();
parameters.put("cid", payProperties.getCid());
parameters.put("tid", tid);
parameters.put("cancel_amount", "2200");
parameters.put("cancel_tax_free_amount", "0");
parameters.put("cancel_vat_amount", "0");
// 파라미터, 헤더
HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(parameters, this.getHeaders());
// 외부에 보낼 url
RestTemplate restTemplate = new RestTemplate();
KakaoCancelResponse cancelResponse = restTemplate.postForObject(
"https://open-api.kakaopay.com/online/v1/payment/cancel",
requestEntity,
KakaoCancelResponse.class);
System.out.println();
System.out.println();
System.out.println(cancelResponse);
System.out.println();
System.out.println();
return cancelResponse;
}
}
[controller]
@RestController
@RequestMapping("/payment")
@RequiredArgsConstructor
public class KakaoPayController {
private final KakaoPayService kakaoPayService;
/**
* 결제요청
*/
@PostMapping("/ready")
public KakaoReadyResponse readyToKakaoPay() {
. . .
}
/**
* 결제성공
*/
@PostMapping ("/success")
public ResponseEntity<KakaoApproveResponse> afterPayRequest(@RequestParam("pg_token") String pgToken) {
. . .
}
/**
* 결제 진행 중 취소
*/
@GetMapping("/cancel")
public void cancel() {
. . .
}
/**
* 결제실패
*/
@GetMapping("/fail")
public void fail() {
. . .
}
/**
* 환불
*/
@PostMapping("/refund")
public ResponseEntity<KakaoCancelResponse> refund(@RequestParam("tid") String tid) {
KakaoCancelResponse kakaoCancelResponse = kakaoPayService.kakaoCancel(tid);
return new ResponseEntity<>(kakaoCancelResponse, HttpStatus.OK);
}
}
결제 ready, approve 과정을 거쳐 성공을 하게 되면 tid가 나오게 되는데 tid를 잘 저장해두었다가 전달해준다.
Response
그러면 예시와 같은 결과가 나오는 것을 확인할 수 있다.
그러면 예시와 같은 결과가 나오는 것을 확인할 수 있다.
그리고 진짜로 취소가 되었다는 카톡 또한 온다 !
취소도 구현 완료!
728x90
반응형