const handleOnPayment = async () => {
try {
const tosspayments = await loadTossPayments(
process.env.REACT_APP_TOSS_CLIENT_KEY
);
tossPaymentsRef.current = tosspayments;
// #1 요청을 보내기 전 결제정보를 DB에 저장하는 과정이 필요함
await tosspayments.requestPayment("카드", {
amount: sunsuMembershipPrice,
orderId: nanoid(),
orderName: "순수 멤버십",
successUrl: `${window.location.origin}/payments`,
failUrl: `${window.location.origin}/payments/fail`,
customerName: userInfo.name,
customerEmail: userInfo.email,
});
} catch (error) {
console.error("비동기 작업 중 오류 발생:", error);
}
};
프론트단에서의 결제 요청 코드
#1 요청을 보내기 전 결제 정보를 DB에 저장
→ 이 때 사용할 수 있는 정보: amount, orderId, orderName, customerName, customerEmail
→ /payments/save 사용
const secretKey = process.env.REACT_APP_TOSS_SECRET_KEY;
const url = "<https://api.tosspayments.com/v1/payments/confirm>";
const basicToken = btoa(`${secretKey}:`); // base64 인코딩
useEffect(() => {
// 실무에서는 Toss에서 전달받은 결제정보와 DB에 저장된 결제정보를 비교하는 과정이 필요함
// ->
// #2 인증까지 마친 결제의 정보를 다시 보내줌
// #3 백엔드에서 이전의 저장한 결제 정보와 인증까지 마친 결제 정보가 일치하다면 response로
// success를 보내줌 / 만약 일치하지 않는다면 fail
// #4 프론트에서 response를 받아서 일치한다면 승인 요청을 보냄/일치하면 않는다면 failUrl 이동
// #5 승인 요청을 보낸 후 /user/upgrade 요청을 백엔드로 보냄
(async () => {
try {
const requestData = {
amount: searchParams.get("amount"),
orderId: searchParams.get("orderId"),
paymentKey: searchParams.get("paymentKey"),
};
const response = await fetch(url, {
method: "post",
headers: {
Authorization: `Basic ${basicToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(requestData),
});
const res = await response.json();
if (!response.ok) {
console.log("실패", res);
navigate(`/payments/fail?message=${res.message}`);
} else {
navigate(`/payments/complete?orderId=${res.orderId}`);
}
} catch (error) {
// 네트워크 오류 또는 파싱 오류 등을 처리
console.error("비동기 작업 중 오류 발생:", error);
}
})();
현재 승인 요청을 하기전 successUrl로 이동한 상태
URL의 쿼리 파라미터로 받기 때문에 클라이언트에서 실행한 결제의 무결성 보증
→ 진행된 결제 정보가 이전에 저장한 결제 정보와의 일치 여부 확인
→ #2 프론트단에서 다시 한 번 진행된 결제의 정보를 백엔드에 보내줌
→ #3 백엔드에서 저장된 결제 정보와 인증을 마친 결제 정보가 일치한다면 승인 요청을 하라는 response 보내줌
→ #4 프론트에서는 success이면 결제 승인 요청을 보내고 fail이면 승인 요청을 안보냄으로써 결제 만료를 시킴
→ #5 결제 승인을 진행한 뒤 /user/upgrade 를 진행함