⛳️ 이 가이드를 읽고 나면 토스페이먼츠 결제위젯 SDK로 주문서 페이지에 결제를 연동할 수 있어요.
토스페이먼츠와 계약하기 전이라면, 문서 테스트 키로 결제위젯을 연동하세요. 토스페이먼츠와 계약을 완료했다면, 나만의 테스트 키로 결제위젯을 연동하고 상점관리자에서 커스터마이징을 해보세요.
// 문서 테스트 키
// 토스페이먼츠와 계약하지 않았다면 아래 키로 결제위젯을 연동하세요.
const clientKey = 'test_ck_D5GePWvyJnrK0W0k6q8gLzN97Eoq'
const secretKey = 'test_sk_zXLkKEypNArWmo50nX3lmeaxYG5R'
// 나만의 테스트 키
// 토스페이먼츠와 계약했다면 아래 키로 결제위젯을 연동하세요.
// 로그인하면 나만의 키로 변경됩니다.
const clientKey = 'test_ck_D5GePWvyJnrK0W0k6q8gLzN97Eoq'
const secretKey = 'test_sk_zXLkKEypNArWmo50nX3lmeaxYG5R'
clientKey : test_ck_D5GePWvyJnrK0W0k6q8gLzN97Eoq | secretKey : test_sk_zXLkKEypNArWmo50nX3lmeaxYG5R
아래 예제 코드는 HTML 페이지에 결제위젯, 이용약관 UI를 연동합니다. 결제하기 버튼을 눌러서 결제창을 띄워보세요. 실제로 결제되지 않으니 안심하세요.
<head>
<meta charset="utf-8" />
<!-- 결제위젯 SDK 추가 -->
<script src="https://js.tosspayments.com/v1/payment-widget"></script>
</head>
<body>
<!-- 결제위젯, 이용약관 영역 -->
<div id="payment-method"></div>
<div id="agreement"></div>
<!-- 결제하기 버튼 -->
<button id="payment-button">결제하기</button>
<script>
const clientKey = "test_ck_D5GePWvyJnrK0W0k6q8gLzN97Eoq"
const customerKey = "" // 내 상점의 고객을 식별하는 고유한 키
const button = document.getElementById("payment-button")
// ------ 결제위젯 초기화 ------
// 비회원 결제에는 customerKey 대신 ANONYMOUS를 사용하세요.
const paymentWidget = PaymentWidget(clientKey, customerKey) // 회원 결제
// const paymentWidget = PaymentWidget(clientKey, PaymentWidget.ANONYMOUS) // 비회원 결제
// ------ 결제위젯 렌더링 ------
// 결제위젯이 렌더링될 DOM 요소를 지정하는 CSS 선택자 및 결제 금액을 넣어주세요.
// https://docs.tosspayments.com/reference/widget-sdk#renderpaymentmethods선택자-결제-금액-옵션
paymentWidget.renderPaymentMethods("#payment-method", 15000)
// ------ 이용약관 렌더링 ------
// 이용약관이 렌더링될 DOM 요소를 지정하는 CSS 선택자를 넣어주세요.
// https://docs.tosspayments.com/reference/widget-sdk#renderagreement선택자
paymentWidget.renderAgreement('#agreement')
// ------ '결제하기' 버튼 누르면 결제창 띄우기 ------
// 더 많은 결제 정보 파라미터는 결제위젯 SDK에서 확인하세요.
// https://docs.tosspayments.com/reference/widget-sdk#requestpayment결제-정보
button.addEventListener("click", function () {
paymentWidget.requestPayment({
orderId: "", // 주문 ID(직접 만들어주세요)
orderName: "토스 티셔츠 외 2건", // 주문명
successUrl: "https://my-store.com/success", // 결제에 성공하면 이동하는 페이지(직접 만들어주세요)
failUrl: "https://my-store.com/fail", // 결제에 실패하면 이동하는 페이지(직접 만들어주세요)
customerEmail: "customer123@gmail.com",
customerName: "김토스"
})
})
</script>
</body>
결제 금액이 바뀐다면 updateAmount()
를 사용해서 결제위젯을 업데이트하세요.
// 새로운 결제 금액을 넣어주세요
paymentMethods.updateAmount(50000);
결제 요청이 성공하면 설정했던 결제 성공 페이지(successUrl
)로 이동합니다. 결제 성공 페이지의 URL에는 아래 네 가지 쿼리 파라미터가 들어있습니다.
https://my-store.com/success?paymentKey={PAYMENT_KEY}&orderId={ORDER_ID}&amount={AMOUNT}&paymentType={PAYMENT_TYPE}
paymentKey
: 결제의 키값입니다.orderId
: 상점에서 발급한 주문 건 ID입니다.requestPayment()
에 담아 보낸 값입니다.amount
: 실제로 결제된 금액입니다.paymentType
: 결제 유형입니다.NORMAL
,BRANDPAY
중 하나입니다.
* 결제 요청이 실패하면 설정했던 결제 실패 페이지(failUrl
)로 이동합니다. 결제 실패 URL을 살펴보세요.
renderPaymentMethods()
메서드에 담아 보낸 결제 금액과 successUrl
로 돌아온 amount
값이 같은지 반드시 확인해보세요. 클라이언트에서 결제 금액을 조작해 승인하는 행위를 방지할 수 있습니다.
만약 값이 다르다면 결제를 취소하고 구매자에게 알려주세요. 적립금이나 쿠폰이 적용된 금액이 맞는지도 확인해보세요.
결제 승인 API를 호출해서 마지막 단계를 완료합니다.
먼저 API 인증을 위해 아래와 같이 인증 헤더 값을 만듭니다.
시크릿 키 뒤에 :
을 추가하고 base64로 인코딩합니다. 콜론을 빠트리지 않도록 주의하세요.
echo -n 'test_sk_zXLkKEypNArWmo50nX3lmeaxYG5R' + ':' | base64
인코딩된 값을 Basic 인증 헤더에 넣고 요청 본문도 추가하세요. 앞 단계에서 리다이렉트 URL로 받은 paymentKey
, orderId
, amount
를 넣어주세요.
아래 예제 코드에는 내 테스트 결제의 paymentKey
값을 넣어 실행해주세요.
curl --request POST \
--url https://api.tosspayments.com/v1/payments/confirm \
--header 'Authorization: Basic dGVzdF9za196WExrS0V5cE5BcldtbzUwblgzbG1lYXhZRzVSOg==' \
--header 'Content-Type: application/json' \
--data '{"paymentKey":"{PAYMENT_KEY}","amount":15000,"orderId":"_-khCq72AxwpmqWjA8kfC"}'
성공 페이지로 리다이렉트 된 후 10분 이내에 결제 승인 API를 호출해야 합니다. 10분이 지나면 결제가 만료되어 결제 승인을 할 수 없습니다.
결제 승인에 성공하면 HTTP 200 OK
와 Payment 객체를 받습니다.
{
"mId": "tosspayments",
"version": "2022-11-16",
"paymentKey": "",
"status": "DONE",
"lastTransactionKey": "",
"orderId": "",
"orderName": "토스 티셔츠 외 2건",
"requestedAt": "2022-06-08T15:40:09+09:00",
"approvedAt": "2022-06-08T15:40:49+09:00",
"useEscrow": false,
"cultureExpense": false,
"card": {
"issuerCode": "61",
"acquirerCode": "31",
"number": "12345678****789*",
"installmentPlanMonths": 0,
"isInterestFree": false,
"interestPayer": null,
"approveNo": "00000000",
"useCardPoint": false,
"cardType": "신용",
"ownerType": "개인",
"acquireStatus": "READY",
"amount": 15000
},
"virtualAccount": null,
"transfer": null,
"mobilePhone": null,
"giftCertificate": null,
"cashReceipt": null,
"cashReceipts": null,
"discount": null,
"cancels": null,
"secret": null,
"type": "NORMAL",
"easyPay": null,
"country": "KR",
"failure": null,
"isPartialCancelable": true,
"receipt": {
"url": "https://dashboard.tosspayments.com/sales-slip?transactionId=KAgfjGxIqVVXDxOiSW1wUnRWBS1dszn3DKcuhpm7mQlKP0iOdgPCKmwEdYglIHX&ref=PX"
},
"checkout": {
"url": "https://api.tosspayments.com/v1/payments//checkout"
},
"currency": "KRW",
"totalAmount": 15000,
"balanceAmount": 15000,
"suppliedAmount": 13636,
"vat": 1364,
"taxFreeAmount": 0,
"method": "카드"
}
✅ 응답 객체에 선택한 결제수단 필드가 있는지 확인하세요.
✅ 응답 객체의 method
가 선택한 결제수단인지 확인하세요.
✅ 간편결제를 테스트했다면 선택한 결제수단에 따라 돌아오는 응답 객체가 달라집니다. 간편결제 응답 처리를 참고하세요.
✅ 가상계좌를 테스트했다면 입금하고 결제를 완료하세요. 환불 계좌를 입력받았다면 환불 계좌 정보도 확인하세요.