Toss Payment API 결제 구현

  1. 사용자클라이언트 : 결제창 호출

  2. 클라이언트PG사 : 결제 요청

  3. PG사클라이언트: 결제키 발급

  4. 클라이언트PG사 : 결제 승인 API 요청

  5. PG사클라이언트: 승인 결과 응답

  6. 클라이언트사용자 : 결제 결과 응답

Pre-Requirement.

Installment.

npm install @tosspayments/payment-sdk

결제요청

const clientKey = process.env.NEXT_PUBLIC_TOSS_CLIENT_KEY;
const tosspayments = await loadTossPayments(
  clientKey
);

try {
  const data = await tosspayments.requestPayment('카드', {
    amount: 5000,
    orderId: Math.random().toString(36).slice(2),
    orderName: '노트북',
  });

  console.log(data);
	/*
		amount,
		orderId,
		paymentKey
	*/
} catch (err: any) {
  if (err.code === 'USER_CANCEL') {
    // 사용자가 창을 닫아 취소한 경우에 대한 처리
  }
}

결제성공

const { amount, orderId, paymentKey } = req.query;
const secretKey = process.env.NEXT_PUBLIC_TOSS_SECRET_KEY;

const url = "<https://api.tosspayments.com/v1/payments/confirm>";
const basicToken = Buffer.from(`${secretKey}:`, 'utf-8').toString('base64');

await fetch(url, {
  method: 'post',
  body: JSON.stringify({
    amount, orderId, paymentKey
  }),
  headers: {
    Authorization: `Basic ${basicToken}`,
    'Content-Type': 'application/json',
  }
});

res.redirect(`/payments/complete?orderId=${orderId}`);

References

Last updated