결제 요청, 인증, 승인… 이게 다 뭔가요?

Untitled

1. 결제 요청

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);
    }
  };

프론트단에서의 결제 요청 코드

2. 결제 승인

  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);
      }
    })();