Files
sake/src/main/webapp/WEB-INF/views/sopmal/ordr/PayTossPayC.jsp
2025-10-29 17:08:05 +09:00

178 lines
8.8 KiB
Plaintext

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="ui" uri="http://www.winbit.kr/ctl/ui"%>
<%@ taglib prefix="f" uri="/WEB-INF/tlds/f.tld"%>
<%--
Class Name : PayTossPayC.jsp
Description : 토스결제 모든 결제수단 All(사용안함)
Modification Information
수정일 수정자 수정내용
------- -------- ---------------------------
2024-04-11 김혜인 최초 생성
--%>
<!-- 토스페이먼츠 JSP 결제 샘플 소스코드 -->
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<link rel="icon" href="https://static.toss.im/icons/png/4x/icon-toss-logo.png" />
<link rel="stylesheet" href="<c:url value='/css/style2.css'/>">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>토스페이먼츠 샘플 프로젝트</title>
<!-- 결제창 SDK 추가 -->
<script src="https://js.tosspayments.com/v1/payment"></script>
</head>
<body>
<div class="box_section" style="width: 600px">
<h2 style="margin-top: -10px">토스페이먼츠 샘플 프로젝트</h2>
<p class="typography--p" style="margin-bottom: 30px">연동 진행하며 궁금한 점은 공식 <a href="https://discord.com/invite/A4fRFXQhRu">Discord 채널</a>로 문의주세요.</p>
<h4 class="text--left">결제수단</h4>
<!-- 라디오 영역 -->
<div class="checkable typography--p">
<label for="card" class="checkable__label typography--regular">
<input type="radio" value="card" id="card" name="method" class="checkable__input" checked />
<span class="checkable__label-text" style="padding-right: 25px">카드</span>
</label>
<label for="easypay" class="checkable__label typography--regular">
<input type="radio" value="easypay" id="easypay" name="method" class="checkable__input" />
<span class="checkable__label-text" style="padding-right: 25px">간편결제</span>
<label for="tossPayments" class="checkable__label typography--regular">
<input type="radio" value="tossPayments" id="tossPayments" name="method" class="checkable__input" />
<span class="checkable__label-text" style="padding-right: 25px">기타 결제수단</span>
</label>
</label>
</div>
<!-- 드롭다운 영역 -->
<div class="input radius--m p-select input--medium p-select--medium" style="margin-top: 20px">
<span class="input__field p-select__field"> <span class="p-select__field-title" id="selectText"></span></span>
<select class="p-select__native" aria-invalid="false" aria-label="결제수단 선택" id="paymentType" name="paymentType">
<option disabled="" selected>결제수단 선택</option>
</select>
</div>
<!-- 구매자 정보 영역 -->
<h4 class="text--left">구매자 정보</h4>
<div class="input radius--m input--medium input--default dashboard-emotion-cache-15lad2a">
<input class="input__field" placeholder="이름(선택)" aria-invalid="false" aria-label="이름 입력" id="customerName" value="" />
</div>
<div class="input radius--m input--medium input--default dashboard-emotion-cache-15lad2a" style="margin-top: 10px">
<input class="input__field" placeholder="이메일 입력(선택)" aria-invalid="false" aria-label="이메일 입력" id="customerEmail" value="" />
</div>
<!-- 결제내역 영역 -->
<h4 style="text-align: left; margin-top: 40px">결제내역</h4>
<div class="p-grid typography--p">
<div class="p-grid-col text--left">결제금액</div>
<div class="p-grid-col text--right">15,000원</div>
</div>
<div class="p-grid typography--p" style="margin-top: 10px">
<div class="p-grid-col text--left">주문상품 정보</div>
<div class="p-grid-col text--right">토스 티셔츠 외 2건</div>
</div>
<!-- 결제하기 버튼 -->
<button class="button" id="payment-button" style="width: 300px">결제하기</button>
</div>
<script>
/* ================== 결제 수단 섹션 ================== */
document.addEventListener("DOMContentLoaded", function () {
function setOptions(event) {
const options = {
tossPayments: ["계좌이체", "가상계좌", "휴대폰", "문화상품권", "도서문화상품권", "게임문화상품권"],
card: [
"신한",
"현대",
"삼성",
"롯데",
"토스뱅크",
"하나",
"국민",
"비씨",
"농협",
"우리",
"카카오뱅크",
"케이뱅크",
"기업",
"씨티",
"새마을",
"우체국",
"수협",
"신협",
"광주은행",
"전북",
"산업",
"제주",
"저축",
],
easypay: ["토스페이", "네이버페이", "삼성페이", "엘페이", "카카오페이", "핀페이", "페이코", "SSG페이"],
};
paymentType.innerHTML = "<option disabled='' selected>결제수단 선택</option>";
selectText.innerHTML = document.querySelector("select[name=paymentType] option:checked").text;
options[event.target.id].forEach((e) => (paymentType.innerHTML += `<option value=${e}">${e}</option>`));
}
// 라디오 선택에 따라 드롭다운 수정
setOptions({ target: { id: document.querySelector("input[name='method']").value } });
document.querySelectorAll("input[name='method']").forEach((input) => input.addEventListener("change", setOptions));
// 드롭다운 선택에 따라 보여주는 텍스트 수정
document.querySelector("select[name=paymentType]").addEventListener("change", function () {
selectText.innerHTML = document.querySelector("select[name=paymentType] option:checked").text;
});
});
/* ================== SDK 초기화 ================== */
const clientKey = "test_ck_D5GePWvyJnrK0W0k6q8gLzN97Eoq";
const tossPayments = TossPayments(clientKey);
/* ================== '결제' Btn Event ================== */
const button = document.getElementById("payment-button");
document.getElementById("payment-button").addEventListener("click", function () {
// 선택에 따라 파라미터 수정하기
const selectedMethod = document.querySelector("input[name='method']:checked").value;
const selectedOption = document.querySelector("select[name=paymentType] option:checked").text;
const paymentData = initPaymentData(selectedMethod, selectedOption);
const paymentMethod = selectedMethod === "tossPayments" ? selectedOption : "카드";
// 결제 요청하기
tossPayments.requestPayment(paymentMethod, paymentData).catch(function (error) {
if (error.code === "USER_CANCEL") {
// 결제 고객이 결제창을 닫았을 때 에러 처리
} else if (error.code === "INVALID_CARD_COMPANY") {
// 유효하지 않은 카드 코드에 대한 에러 처리
}
});
});
/* ============= [결제 데이터 생성] ================= */
function initPaymentData(selectedMethod, selectedOption) {
const generateRandomString = () => window.btoa(Math.random()).slice(0, 20);
const paymentData = {
amount: 15000,
orderId: generateRandomString(),
orderName: "토스 티셔츠 외 2건",
customerName: "박토스",
successUrl: window.location.origin + "/jsp/success.jsp",
failUrl: window.location.origin + "/jsp/fail.jsp",
flowMode: selectedMethod === "tossPayments" ? "DEFAULT" : "DIRECT", // 카드사・간편결제사 결제창은 'DIRECT'로 설정
cardCompany: selectedMethod === "card" ? selectedOption : null, // 열고 싶은 카드사 결제창
easyPay: selectedMethod === "easypay" ? selectedOption : null, // 열고 싶은 간편결제사 결제창
customerName: document.getElementById("customerName").value === "" ? null : document.getElementById("customerName").value,
customerEmail: document.getElementById("customerEmail").value === "" ? null : document.getElementById("customerEmail").value,
};
return paymentData;
}
</script>
</body>
</html>