react 카카오 결제 api 연동하고 db에 저장까지 완료하였다.
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>
이 코드를 추가하고 난 후
아래처럼 하면 되는데 payment가 저장되고 그 값이 useState에 저장되고 저장된 값(payment 테이블의 id)을 바로
usageState에 저장되야 하는데 useState값이 당연히 바로 적용안되니 useEffect사용했는데 카카오 결제 api안에서 useEffect 사용이 안되서 useRef이용해서 바로 적용되게 설정했다.(useState값을 useRef에 넣어서
useEffect(() => {
latestPayments.current = payments;
}, [payments]); 이런 식으로 저장)
declare const window: typeof globalThis & {
IMP: any;
};
const PassComponent = () => {
const [subscriptions, setSubscriptions]:any = useState([]);
const [payments,setPayments]:any = useState([]);
const latestPayments:any = useRef([]);
useEffect(() => {
latestPayments.current = payments;
}, [payments]);
//구독 상품 종류 조회해서 가져오기
useEffect(() => {
axios.get('/subscription')
.then(response => {
setSubscriptions(response.data);
})
.catch(error => {
console.log(error);
});
}, []);
const onPayButtonClick = (index:number) => {
const IMP = window.IMP;
IMP.init(가맹점 식별코드); // 가맹점 식별코드 입력
IMP.request_pay(
{
amount: subscriptions[index].price, // 결제 금액
pg: 'kakao', // 결제 수단 - 카카오페이
pay_method: 'kakaopay', // 결제 수단 - 카드
merchant_uid: `mid_${new Date().getTime()}`, // 가맹점에서 관리하는 거래번호
name: subscriptions[index].name, // 상품명
// buyer_email: '구매자 이메일', // 구매자 이메일
// buyer_name: '구매자 이름', // 구매자 이름
// buyer_tel: '구매자 전화번호', // 구매자 전화번호
m_redirect_url: '결제 완료 후 이동할 페이지 URL', // 결제 완료 후 이동할 페이지 URL
},
(rsp: any) => {
if (rsp.success) {
doPayment(index)
setTimeout(()=>{
doUsage(index)
},5000)
} else {
alert('결제가 완료되지 않았습니다. 다시 시도해주세요.')
//notPayment(index)
}
}
);
};
const doPayment = (index:number) => {
axios.post('/payment/pay', {
subscription_id: subscriptions[index].id,
payment_amount: subscriptions[index].price,
pay_check:true
}).then(response => {
setPayments(response.data)
latestPayments.current = response.data;
console.log(response.data);
}).catch(error => {
console.error(error.response.data);
});
}
const doUsage = (index:number) => {
axios.post('/usageState/usage', {
subscription_id: subscriptions[index].id,
payment_id: latestPayments.current?.id,
subscription_check:true
}).then(response => {
console.log(response.data);
}).catch(error => {
console.error(error.response.data);
});
}
return (
<div className="pass_component">
{subscriptions?.map((item:any,index:number) => (
<div className={'pass_type'} key={"subscriptions-list"+index}>
<p>{item.name}</p>
<button onClick={()=>onPayButtonClick(index)}><span>월간 이용권</span>{item.price}원</button>
</div>
))}
</div >
);
}
export default PassComponent;