결제 위젯 연동 시 결제 위젯을 띄우는 컴포넌트와 결제하기 버튼 로직 컴포넌트가 분리되어 있을 경우

.
. 이 paymentWidget .
const [paymentWidget, setPaymentWidget] = useState<PaymentWidgetInstance | null>(null);

. ...
...?


는 PaymentWidget 는 PaymentInfo .

는 PaymentWidget .
import { useEffect } from "react"; import { loadPaymentWidget, PaymentWidgetInstance } from "@tosspayments/payment-widget-sdk"; import styled from "styled-components"; interface PaymentWidgetProps { setPaymentWidget: (widget: PaymentWidgetInstance | null) => void; } export default function PaymentWidget({ setPaymentWidget }: PaymentWidgetProps) { const clientKey = ${import.meta.env.VITE_SINGLE_CLIENTKEY}; const price = 500; const customerKey = "customer-unique-key"; useEffect(() => { (async () => { const paymentWidget = await loadPaymentWidget(clientKey, customerKey); paymentWidget.renderPaymentMethods("#payment-widget", price); setPaymentWidget(paymentWidget); })(); }, [setPaymentWidget]); return ( <PaymentWidgetContainer> <PaymentWidgetBox id="payment-widget" /> </PaymentWidgetContainer> ); } const PaymentWidgetContainer = styled.div
width: 100%;
; const PaymentWidgetBox = styled.div
width: 100%;
;
고 PaymentInfo.
<PaymentButton $isAgree={isAgree} disabled={!isAgree} type="button" onClick={() => handlePayment(id)}>결제하기</PaymentButton>

async function handlePayment(id: number) { if (id === 4) { // 단건 결제 요청 (paymentWidget 사용) if (!paymentWidget) return; try { await paymentWidget.requestPayment({ orderId: "FWZbnh9VMiNXnK9zBqn4f", orderName: "토스 티셔츠 외 2건", customerName: "김토스", customerEmail: "customer123@gmail.com", customerMobilePhone: "01012341234", successUrl: ${window.location.origin}/success, failUrl: ${window.location.origin}/fail, }); } catch (error) { console.error("Error requesting payment:", error); } } else { // 다른 결제 방식 처리 (단건 결제 외 로직) postMembership( { productId: selectedPlan, couponMemberId: activeCouponId, }, { onSuccess: () => { if (activeCouponId) { sessionStorage.removeItem("couponTxt"); sessionStorage.removeItem("dcInfo"); } }, }, ); } }
2025-02-25_8.49.02.png
2025-02-25_8.51.26.png
Was this page helpful?