아임포트 api 를 이용해서 kakaopay 결제 연동 테스트 (React)
1. 아임포트 회원가입 후 가맹점 식별코드 + kakaopay 테스트 결제 모드로 설정
2. 아임포트 api import - 프로젝트의 index.html 에 모듈 import
// MYAPP/public/index.html
<!-- jQuery -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js" ></script>
<!-- iamport.payment.js -->
<script type="text/javascript" src="https://cdn.iamport.kr/js/iamport.payment-1.1.8.js"></script>
3. 결제 버튼 컴포넌트
import React from 'react';
const Payment = () => {
function onClickPayment() {
/* 1. 가맹점 식별하기 */
const { IMP } = window;
IMP.init('imp00000000'); // 가맹점 식별번호
/* 2. 결제 데이터 정의하기 */
const data = {
pg: 'kakaopay', // PG사
pay_method: 'kakaopay', // 결제수단
merchant_uid: `mid_${new Date().getTime()}`, // 주문번호
amount: 1000, // 결제금액
name: '아임포트 결제 데이터 분석', // 주문명
buyer_name: '홍길동', // 구매자 이름
buyer_tel: '01012341234', // 구매자 전화번호
buyer_email: 'example@example', // 구매자 이메일
buyer_addr: '신사동 661-16', // 구매자 주소
buyer_postcode: '06018', // 구매자 우편번호
};
/* 4. 결제 창 호출하기 */
IMP.request_pay(data, callback);
}
/* 3. 콜백 함수 정의하기 */
function callback(response) {
const { // success와 error_msg 필수 나머지는 필요한 것 추가
success,
error_msg,
buyer_name,
merchant_uid,
name,
paid_amount,
pay_method,
} = response;
if (success) {
alert('결제 성공');
console.log(success)
console.log(buyer_name)
console.log(merchant_uid)
console.log(name)
console.log(paid_amount)
console.log(pay_method)
} else {
alert(`결제 실패: ${error_msg}`);
// 백엔드 API 호출 테스트
fetch('http://localhost:8080/payment', {
method: 'GET',
headers: {"Content-Type":"application/json"},
}).then((response) => console.log(response.json()))
}
}
return (
<button onClick={onClickPayment}>결제하기</button>
);
}
export default Payment
4. 결제 성공 시 백엔드 API 호출하여 원하는 형태로 데이터 저장 하면 끝
** 실 거래의 경우 서버는 클라이언트로 부터 결제 정보를 수신한 후에 해당 거래의결제금액의 위변조 여부를 검증하고 결제 정보를데이터베이스에 저장해야하나 우선 테스트 겸 이후 추가 공부 예정
Spring - CORS 해결을 위한 WebConfig
React와 Spring이 서로 분리 되어있기에 fetch api로 호출 시 CORS 오류가 발생하는데 이를 해결하기 위한 코드
package org.payment.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods(HttpMethod.GET.name());
}
}
'회고록(TIL&WIL)' 카테고리의 다른 글
TIL 2022.11.21 Spring webflux(webclinet), spring cron 간단 예제 (0) | 2022.11.22 |
---|---|
TIL 2022.11.14 Spring boot (gradle) dot.env dockerfile-docker-compose (0) | 2022.11.15 |
TIL 2022.10.28 Typescirpt 기본 3 (0) | 2022.10.28 |
TIL 2022.10.26 Typescript 기본2 (0) | 2022.10.26 |
TIL 2022.10.25 Typescript 기본 (1) | 2022.10.25 |