hyeonga_code

reProject_46_결제하기(아임포트 결제 검증 적용) 본문

Project_WEATHERWEAR

reProject_46_결제하기(아임포트 결제 검증 적용)

hyeonga 2024. 2. 16. 05:59
반응형

 

2024.02.15

-- 기존에 작업한 방식은 결제 검증을 하지 않았으나, 포트원 API를 보던 중 사전 검증, 사후 검증에 관련된 내용이 있어 적용시키려고 몇일동안 결제만 잡고 있었다...

-- api에서는 axios를 사용했는데, script에서 따로 설치하거나 참조하면 사용할 수 있으나, require()는 사용할 수 없었고, 이는 Node.js에서 사용하는 문법이라고 한다. (Node.js 를 배웠어야 했나..) 대부분 스프링 부트나 리엑트, Vue를 사용한 프로젝트 블로그가 많아 어려웠다. 추후 더 알아갈 예정이다.

-- 사전 검증은 적용하지 못했고, payment/prepare 를 적용하는 방법을 알고싶어졌다.

-- 결국 결제 후 검증을 하는 방법을 선택(검증은 IamportClient<Payment>를 공부하며 알아본 내용을 토대로 작성)

-- 구글링을 하다 보니, 결제해야하는 금액을 DB에 넣어두고 결제한 금액과 비교하여 결제 완료를 설정해야 한다고 했기에 결제창을 띄우기 전에 DB에 먼저 데이터를 넣도록 작업했다. 스크립트를 변경해서 결제 금액을 변경하는 해킹을 방지하기 위함이라고 했는데, 이런 위험이 방지되었는지는 잘 모르겠다.

---- 완벽하게 방지하기 위해서는 주문창을 띄우기 전에 데이터를 먼저 삽입해야 하나 싶은데, 그러면 포인트, 쿠폰 적용 값은 포함되지 않은 값으로 지정되어 결국 스크립트를 해킹해서 작업을 하려고 마음먹는다면 DB에 저장한 값은 나두고 포인트와 쿠폰 적용값을 변경해서 결제에 영향을 줄 수도 있지 않을까 라는 의문이 생겼다.

 

-- 기존에 작업했던 orderResiter.js가 너무 지저분해서 orderReady.js와 분리하여 작업

 

orderReady.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/**
 * - 화면초기화
 * - 주문상품 가격
 * - 쿠폰리스트 
 * - 배송비 적용
 * - 포인트 적용(전체/부분) 
 * - 기본배송지
 * - 신규배송지
 * - 배송지 설정
 * - 배송지 삭제
 * - 배송지 목록 불러오기
 */
$(document).ready(function(){
/** 화면 초기화 */
    $("#totalDiscountPrice").html(0);
    $("#discountPrice").html(0);
    
    // 보유 포인트
    let havingPoint = parseInt($("#clientPoint").val());
    
    let usedPoint = 0;            //사용포인트
    let couponPrice = 0;        //쿠폰적용값
    let oriPrice = 0;            //기존금액
    let deliveryPrice = 3000;    //배송비
    let discountPrice = 0;        //할인가격(포인트+쿠폰값)
    let orderPrice = 0;            //주문금액(결제금액)
    
/** 주문상품 가격 */
    let orderProductPriceList = document.querySelectorAll(".productPriceInput");
    orderProductPriceList.forEach(price => {
        oriPrice += parseInt(price.value);
    });
    $("#totalOrderPrice").html(oriPrice);
 
/** 쿠폰리스트 */
    let couponList = document.querySelectorAll(".couponOption");
    let couponOption = document.getElementById("couponId");
    couponList.forEach(coupon => {
        if(coupon.value.split("_")[1> oriPrice){    //최소금액이 결제금액보다 큰 경우
            coupon.disabled = true;
            couponOption.appendChild(coupon);    //아래로 정렬
        }
    });
 
/** 배송비 적용 */
    if(oriPrice > 50000){    // 50000원 이상인 경우
        deliveryPrice = 0;
        $("#deliveryPriceDiv").html("0 (무료)");
    } else {
        $("#deliveryPriceDiv").html(deliveryPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
    }
    $("#totalDeliveryPrice").html(deliveryPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
    $("input[name='deliveryPrice']").val(deliveryPrice);
 
/** 포인트 적용 */
    // 전체적용(회원 주문인 경우)
    const applyAllPointBtn = document.querySelector("#applyAllPoint");
    if(applyAllPointBtn){
        applyAllPointBtn.addEventListener("click"function(){
            $("input[name='usedPoint']").val(havingPoint);
            discountPrice = havingPoint + couponPrice;    //할인금액
            setDiscount();
        })
    
        //부분 할인 적용
        $("#usedPoint, #couponId").change(function(){
            usedPoint = parseInt($("input[name='usedPoint']").val());
            couponPrice = parseInt($("#couponId").val());
    
            if(havingPoint < usedPoint){    // 포인트 적용
                playToast("보유한 포인트를 초과할 수 없습니다.""warning");
                $("input[name='usedPoint']").val("");
                $("input[name='usedPoint']").focus();
                usedPoint = 0;
            }
            
            if(usedPoint == null || usedPoint == ''){    //포인트 초기화
                usedPoint = 0;
            }
            if(couponPrice == null || couponPrice == ''){    //쿠폰 초기화
                couponPrice = 0;
            }
            discountPrice = usedPoint + couponPrice;
            setDiscount();
        });
        
        //할인금액 화면 출력
        function setDiscount(){
            if(discountPrice > oriPrice){    // 할인금액이 결제 금액보다 큰 경우
                discountPrice = oriPrice;    // 최소 결제 금액
            }
            $("#discountPrice").html(discountPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
            $("#totalDiscountPrice").html(discountPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
            orderPrice = oriPrice + deliveryPrice - discountPrice;
            if(orderPrice < 0) {// 주문 금액이 0원 이하인 경우
             orderPrice = 0;
            }
            $("#totalPayPrice").html(orderPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
            $("#orderPrice").val(orderPrice);
        }
    
/** 기본 배송지 등록 */
        document.getElementById("baseAddress").addEventListener("change"function() {
            if (this.checked) {    // 체크박스가 체크된 경우 "Y" 반환 (기본배송지)
                $("#baseAddress").val("Y");
            } else {
                $("#baseAddress").val("N");
            }
        });
    }
 
/** 최종 결제 금액 */
    orderPrice = oriPrice + deliveryPrice - discountPrice;
    $("#totalPayPrice").html(orderPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
    $("#orderPrice").val(orderPrice);
 
    $("#sameInfo").click(function(){
        $("#addressName").val($("#clientName").val());
        $("#addressNum").val($("#clientNum").val());
    });
 
/** 새로운 배송지 초기화 */
    $("#newInfo").click(function(){
        $("#addressTitle").val("");
        $("#addressName").val("");
        $("#addressPostNum").val("");
        $("#address1").val("");
        $("#address2").val("");
        $("#addressNum").val("");
        $("#deliveryMessage").val("");
        $("#addressId").val("");
    });
});
 
/** 배송지 설정 */
function selectAddress(button){
    let addressId = button.id;
    
    $.ajax({
        url: "getAddressInfo.do",
        type: "POST",
        async: true,
        dataType: "json",
        data: {
            addressId: addressId,
        },
        success: function(res){
            if(res.code == 1){
                $("#addressTitle").val(res.data.addressTitle);
                $("#addressName").val(res.data.addressName);
                $("#addPostNum").val(res.data.addressPostNum);
                $("#address1").val(res.data.address1);
                $("#address2").val(res.data.address2);
                $("#addressNum").val(res.data.addressNum);
                $("#addressId").val(res.data.addressId);
                
                if(res.data.addressMemo){
                    $("#deliveryMessage").val("inputmessage");
                    $("div#deliDiv").html("<input type='text' class='form-control' name='deliMsg' id='deliMsg' required value='" + res.data.addressMemo + "'>");
                } else {
                    $("#deliveryMessage").val("");
                    $("div#deliDiv").html("");
                }
                playToast("적용되었습니다.""success");
            } else {
                playToast("오류가 발생했습니다. 다시 시도해주세요.""error");
            }
        },
        error : function(error){
            playToast("오류가 발생했습니다."'error');
        }
    });
}
 
/** 배송지 삭제 */
function deleteAddress(button){
    let addressId = button.id;
    
    Swal.fire({
        title: "배송지를 삭제하시겠습니까?",
        icon: "question",
          showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: "삭제하기",
          cancelButtonText: "취소하기",
        reverseButtons: true// 버튼 순서 거꾸로
    }).then((result) => {
        if(result.isConfirmed){    // 매개변수 list 안됨
            $.ajax({
                url: "deleteAddress.do",
                type: "POST",
                async: true,
                dataType: "json",
                data: {
                    addressId: addressId,
                },
                success: function(res){
                    if(res.code == 1){
                        playToast(res.message, "success");
                        getAddressList();
                    } else {
                        playToast("오류가 발생했습니다. 다시 시도해주세요.""error");
                        getAddressList();
                    }
                },
                error : function(error){
                    playToast("오류가 발생했습니다."'error');
                }
            });
        }
        getAddressList();
    });
}
 
/** 배송지 목록 불러오기 */
function getAddressList(){
    let addressListContent = "<div class='row' style='border-bottom:1px solid silver; margin-bottom:10px;'></div>";
    let clientId = $("#clientId").val();
    
    $.ajax({
        url: "getAddressList.do",
        type: "POST",
        async: true,
        dataType: "json",
        data: {
            clientId: clientId,
        },
        success: function(res){
            if(res.code == 1){
                for(let i=0; i<res.data.length; i++){
                    addressListContent += "<div class='confirmDiv'><div class='deliDiv' id='" + res.data[i].addressId;
                    addressListContent += "'><div class='deliDiv_sub'><b>";
                    addressListContent += res.data[i].addressTitle;
                    if(res.data[i].addressBase == 'Y' || res.data[i].addressBase == 'y'){
                        addressListContent += "&nbsp;<code>[ 기본 배송지 ]</code>";
                    }
                    addressListContent += "</b></div><div class='deliDiv'><input type='button' class='form-control applyAddrBtn' value='선택' onclick='selectAddress(this)' id='" + res.data[i].addressId + "'>&nbsp;";
                    addressListContent += "<input type='button' class='form-control deleteAddrBtn' value='삭제' onclick='deleteAddress(this)' id='" + res.data[i].addressId + "'></div></div><div class='deliDiv'><div class='deliDiv_sub'>";
                    addressListContent += res.data[i].addressName;
                    addressListContent += "</div><div class='deliDiv_sub'>";
                    addressListContent += res.data[i].addressNum.slice(0,3+ "-" + res.data[i].addressNum.slice(3,7+ "-" + res.data[i].addressNum.slice(7);
                    addressListContent += "</div></div><div class='deliDiv'>";
                    addressListContent += res.data[i].addressPostNum;
                    addressListContent += "</div><div class='deliDiv'>";
                    addressListContent += res.data[i].address1;
                    addressListContent += "</div><div class='deliDiv'>";
                    addressListContent += res.data[i].address2 ;
                    addressListContent += "</div></div>";
                }
                addressListContent += "</div>";
            }
            
            Swal.fire({
                title: "\n배송지 목록",
                html: addressListContent,
                icon: null,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: "취소",
                reverseButtons: true// 버튼 순서 거꾸로
            }).then((result) => {
                if(result.isConfirmed){    // 매개변수 list 안됨
                    return;
                }
            });
        },
        error : function(error){
            playToast("오류가 발생했습니다."'error');
        }
    });
}
    
// 배송메세지 직접 입력란 생성
function setMessage(){
    if(document.querySelector("#deliveryMessage").value == "inputmessage"){
        $("div#deliDiv").html("<input type='text' class='form-control' name='deliMsg' id='deliMsg' required placeholder='배송 메세지 직접 입력'>");
        $("#deliMsg").focus();
    } else {
        $("div#deliDiv").html("");
    }
}

 

 

orderResister.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/**
 * - 결제방식 선택
 * - (비회원)비밀번호 확인
 * - 데이터 체크
 * - 결제 (payment_info 추후 삽입)
 */
 
 /** 데이터 체크 */
 function checkCondition(inputId, message){
     let input = document.getElementById(inputId);
     let value = input.value;
     
     if(value == null || value == ""){
         playToast(message, "warning");
         input.focus();
         $("#" + inputId).css("border-color""red");
         return null;
     } else {
         input.blur();
         $("#" + inputId).css("border""var(--bs-border-width) solid var(--bs-border-color)");
     }
     return value;
 }
 
/** 비밀번호 확인 */
function checkPwd(data){
    // this로 받아오는 경우 값을 가져오지 않음
    
    const cookiePwd = document.getElementById("cookiePwd");
    
    if(data.value != cookiePwd.value){
        playToast("비밀번호가 일치하지 않습니다""error");
        $("#cookiePwdCheck").val("");
        $("#cookiePwdCheck").focus();
    }
}
 
// 결제 정보 (일반결제/ 카카오페이/ 토스페이/ 가상결제)
let pg = "";            // PG사
let payMethod = "";        // 결제방법
let sqlPayMethod = "";
 
/** 결제 방식 선택 */
$(() => {
    $("#html5_inicis").on("click", ()=>{
        pg = "html5_inicis";
        payMethod = "card";
        sqlPayMethod = "카드";
        console.log("일반결제 : " + pg + " / " + payMethod);
    });
 
    $("#kakaopay").on("click", ()=>{
        pg = "kakaopay";
        payMethod = "card";
        sqlPayMethod = "카카오페이";
        console.log("카카오페이 : " + pg + " / " + payMethod);
    });
    
    $("#tosspay").on("click", ()=>{
        pg = "tosspay";
        payMethod = "card";
        sqlPayMethod = "토스페이";
        console.log("토스페이 : " + pg + " / " + payMethod);
    });
    
    $("#vbank").on("click", ()=>{
        pg = "vbank";
        payMethod = "vbank";
        sqlPayMethod = "가상결제";
        console.log("가상결제 : " + pg + " / " + payMethod);
    });
});
 
/** 결제하기 버튼(정보 확인) */
function checkSubmit(){    
    if(pg == "" || payMethod == ""){
        playToast("결제 방식을 선택해주세요""warning");
        return;
    }
    console.log("1. checkSubmit() 시작");
    let clientemail = checkCondition("clientEmail""이메일은 필수 입력값입니다");
    let clientName = checkCondition("addressName""받는 사람을 입력해주세요");
    let clientNumber = checkCondition("addressNum""연락처를 입력해주세요");
    let postNum = checkCondition("addressPostNum""우편번호를 입력해주세요");
    let address1 = checkCondition("address1""기본 주소는 필수 입력값입니다.");
    let address2 = checkCondition("address2""상세 주소를 입력해주세요");
    
    let addressMemo = $("#deliveryMessage").val();
    if(addressMemo == "inputMessage"){
        addressMemo = $("#deliMsg").val();
    }
    
    //회원
    let addressTitle = $("#addressTitle").val();
    let addressId = $("#addressId").val();
    let addressBase = $("#baseAddress").val();
    let clientId = $("#clientId").val();
    let couponId = $("#couponId").val().split("_")[2];
    let usedPoint = parseInt($("#usedPoint").val());
    
    //비회원
    let cookiePwd = $("#cookiePwd").val();
    
    let orderPrice = parseInt($("#orderPrice").val());                    //주문금액
    let priceList = document.querySelectorAll(".productPriceInput");    //상품별 금액 
    let cntList = document.querySelectorAll(".cartCnt");                //상품별 수량
    let cartId = document.querySelectorAll(".cartId");                    //장바구니 번호
    let optionList = document.querySelectorAll(".optionId");            //상품별 옵션
    let optionIdList = '';
    let cartIdList = [];
    let orderInfoList = [];
    
    //orders_info
    for(let i=0; i<priceList.length; i++){
        let order = {
            "optionId": optionList[i].value,
            "orderProCnt"parseInt(cntList[i].value),
            "orderTotal"parseInt(priceList[i].value)
        };
        orderInfoList.push(order);
        cartIdList.push(parseInt(cartId[i].value));
        optionIdList += optionList[i].value;
        if(i<priceList.length-1 ) {
            optionIdList += ",";
        }
    }
    
    let data = {};
    data["cartIdList"= cartIdList;
    data["orderInfoList"= orderInfoList;
    
    //배송지
    let addressInfo = {
        "addressId": addressId,
        "clientId": clientId,
        "addressTitle": addressTitle,
        "addressName": clientName,
        "addressNum": clientNumber,
        "addressPostNum": postNum,
        "address1": address1,
        "address2": address2,
        "addressMemo": addressMemo,
        "addressBase": addressBase
    };
    data["addressInfo"= addressInfo;
    data["addressBase"= addressBase;
 
    //주문정보
    let orderInfo = {
        "clientId": clientId,
        "optionIdList": optionIdList,
        "addressId": addressId,
        "orderEmail": clientemail,
        "orderPrice": orderPrice,
        "usedPoint": usedPoint,
        "couponId": couponId,
        "cookiePwd": cookiePwd,
    };
    data["orderInfo"= orderInfo;
    data["orderPrice"= orderPrice;
    
    // 회원    
    if(couponId != null){
        let usedCouponInfo = {
            "couponId": couponId.split("_")[2],
            "clientId": clientId
        };
        data["usedCouponInfo"= usedCouponInfo;
    }
    
    $.ajax({
        url: "orderRegisterProc.do",
        type: "POST",
        async: true,
        dataType: "json",
        data: JSON.stringify(data),
        contentType: "application/json",
        success: function(res){
            if(res.code == 1){
                let orderId = res.data;
                let IMP = window.IMP;
                IMP.init('imp21162314');
                
                IMP.request_pay({
                    pg: pg,                        // pg사 코드
                    pay_method: payMethod,        // 결제 수단
                    merchant_uid: 'merchant_'+new Date().getTime(),   // 주문번호(고유)
                    name: optionIdList,            // 주문명
                    amount: orderPrice,                // 결제 금액(숫자)
                    buyer_email: clientemail,        // 이메일
                    buyer_name: clientName,            // 구매자 이름
                    buyer_tel: clientNumber,        // 구매자 연락처
                    buyer_addr: address1 + address2,// 구매자 주소
                    buyer_postcode: postNum,            // 구매자 우편번호
                    card: {
                        detail: [
                            {card_cod: "*", enabled:true}
                        ]
                    },
                    display: {
                      card_quota: [1,2,3,4,6],      // 할부개월 6개월만 활성화
                      only_installment: true          // 일시불 항목은 제외
                    }
                }, function (rsp) { // callback
                    if(rsp.success){
                        let paymentStatus;
                        //결제검증
                        $.ajax({
                            type: "POST",
                            url: "verifyIamport.do?imp_uid=" + rsp.imp_uid
                        }).done(function(data){
                            let result = $(data).find("amount").text();
                            
                            if(rsp.paid_amount == result){
                                if(rsp.status == "ready"){
                                    paymentStatus = "결제대기";
                                } else if (rsp.status == "paid"){
                                    paymentStatus = "결제완료";
                                } else if (rsp.status == "fail"){
                                    paymentStatus = "결제실패";
                                }
 
                                let paymentInfo = {
                                    "orderId": orderId,
                                    "paymentId": rsp.merchant_uid,
                                    "paymentMethod": sqlPayMethod,
                                    "paymentDate": rsp.paid_at,
                                    "paymentStatus": paymentStatus
                                }
                                
                                $.ajax({
                                    url: "paymentInsert.do",
                                    type: "POST",
                                    async: true,
                                    dataType: "json",
                                    data: JSON.stringify(paymentInfo),
                                    contentType: "application/json",
                                    success: function(res){
                                        if(res.code == 1){
                                            let successAction = "location.href='orderInfo.do?orderId=" + res.data + "'";
                                            playConfirm(res.message, "주문 상세페이지로 이동하시겠습니까?""success""이동하기""메인페이지로", successAction, "location.href='main.do'");
                                        }
                                        
                                        if(res.code == -1){
                                            playToast(res.message, "error");
                                        }
                                    },
                                    error : function(error){
                                        playToast("오류가 발생했습니다."'error');
                                    }
                                });
                            }
                        });
                    }
                    if(res.code == -1){
                        playToast(res.message, "error");
                    }
                });
            }
        },
        error : function(error){
            playToast("오류가 발생했습니다."'error');
        }
    });
}
 
 

 

 

PaymentController.java 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.w2.client.controller;
 
import java.io.IOException;
 
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
import com.siot.IamportRestClient.IamportClient;
import com.siot.IamportRestClient.exception.IamportResponseException;
import com.siot.IamportRestClient.response.IamportResponse;
import com.siot.IamportRestClient.response.Payment;
 
import lombok.RequiredArgsConstructor;
 
@RestController
@RequiredArgsConstructor
@PropertySource("classpath:config/webserverdb.properties")
public class PaymentController {
 
    @Value("${imp.api.key}")
    private String apiKey;
    
    @Value("${imp.api.secretKey}")
    private String secretKey;
    
    private IamportClient iamportClient;
    
    @RequestMapping("sample.do")
    public String samplePayment() {
        return "test";
    }
    
    @ResponseBody
    @RequestMapping("verifyIamport.do")
    public IamportResponse<Payment> paymentByImpUid(@Param("imp_uid"String imp_uid) throws IamportResponseException, IOException {
        iamportClient = new IamportClient(apiKey, secretKey);
        IamportResponse<Payment> result = iamportClient.paymentByImpUid(imp_uid);
 
        return result;
    }
}
 

 

 

ClientOrderController.java 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package com.w2.client.controller;
 
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;
 
import com.w2.cart.CartVO;
import com.w2.cart.service.CartService;
import com.w2.client.ClientVO;
import com.w2.client.service.ClientService;
import com.w2.clientAddress.service.ClientAddressService;
import com.w2.coupon.service.CouponService;
import com.w2.order.OrderInfoVO;
import com.w2.order.service.OrderService;
import com.w2.payment.PaymentVO;
import com.w2.util.ClientCookie;
import com.w2.util.RandomString;
import com.w2.util.ResponseDTO;
 
@Controller
public class ClientOrderController {    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    
    @Autowired
    private ClientService clientService;
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private ClientAddressService addressService;
    
    @Autowired
    private CouponService couponService;
 
    @RequestMapping("noClientOrder.do")
    public String noClientOrderView() {
        return "order/noClientOrder";
    }
 
    @RequestMapping("ttt.do")
    public String ttt(@Param("ID")String id) {
        System.err.println(">>> id : " + id);
        return "test";
    }
    
    /**
     * 주문 화면 호출
     * @return
     */
    @RequestMapping("orderRegister.do")
    public String orderRegister(@Param("caIdList"String cartList, @Param("cartOk"String cartOk,HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model, CartVO cartvo) {
        String userId = "";
        String[] list = cartList.split(",");
        List<String> cartIdList = Arrays.asList(list);
        
        Map<String, Object> orderMap = new HashMap<String, Object>();
        orderMap.put("cartIdList", cartIdList);
        
        if(session.getAttribute("userInfo"== null) {
            if(cartOk != null && cartOk.equals("Y")) {
                String cookieId = ClientCookie.setCookie(request, response);
                orderMap.put("cookieId", cookieId);
                session.setAttribute("cookieId", cookieId);
            }
            if(session.getAttribute("cookieId"== null) {
                return "order/orderLogin";
            }
        } else {
            ClientVO user= (ClientVO)session.getAttribute("userInfo");
            userId = user.getClientId();
            orderMap.put("clientId", user.getClientId());
            model.addAttribute("baseAddress", addressService.getBaseAddress(user.getClientId()));
            model.addAttribute("couponList", couponService.getCouponList(user.getClientId()));
        }
        
        List<CartVO> orderList = orderService.getOrderProductList(orderMap);
        if(orderList.size() <= 0) {
            return "redirect:login.do";
        }else {
            model.addAttribute("orderList", orderList);
        }
        
        return "order/orderRegister";
    }
    
    /**
     * 주문 상세 페이지 호출
     * @return
     */
    @RequestMapping("orderInfo.do")
    public String orderInfo(@Param("orderId"String orderId, HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model, CartVO cartvo) {
        model.addAttribute("orderInfo", orderService.getOrderInfo(orderId));
        model.addAttribute("orderProductList", orderService.getOrderInfoList(orderId));
        return "order/orderInfo";
    }
    
    /** 주문 추가 */
    @ResponseBody
    @PostMapping("orderRegisterProc.do")
    public ResponseDTO<String> orderRegisterProc(@RequestBody Map<String, Object> data, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Integer statusCode = HttpStatus.OK.value();
        int code = 0;
        String resultCode;
        String msg;
        String orderId = "OD" + RandomString.createFileName() + RandomString.setRandomString(8"number");
        
        Map<String, Object> addressInfo = (Map<String, Object>) data.get("addressInfo");
        
        // 배송지Id 설정
        if(addressInfo.get("addressId"== null || addressInfo.get("addressId"== "") {
            addressInfo.put("addressId""AD" + RandomString.createFileName() + RandomString.setRandomString(5"number"));
            data.put("addressInfo", addressInfo);
        }
        
        // 주문번호 설정
        data.put("orderId", orderId);
 
        if(session.getAttribute("userInfo"== null) {
            data.put("cookieId", (String)session.getAttribute("cookieId"));
        } 
        
        try {
            System.err.println("6. try 시작");
            int result = orderService.insertImsiOrder(data);
            
            System.err.println("14. insertImsiOrder : " + result);
            orderId = (String)data.get("orderId");
            if(result > 0) {
                code = 1;
                resultCode = "success";
                msg = "주문이 완료되었습니다.";
            } else {
                code = -1;
                resultCode = "fail";
                msg = "주문중 오류가 발생했습니다.";
            }
        } catch (Exception e) {
            code = -1;
            resultCode = "fail";
            msg = "오류가 발생했습니다.";
            orderId = null;
        }
        return new ResponseDTO<String>(statusCode, code, resultCode, msg, orderId);
    }
    
    /** 결제 정보 등록 */
    @ResponseBody
    @PostMapping("paymentInsert.do")
    public ResponseDTO<String> paymentInsert(@RequestBody Map<String, Object> data) throws IOException {
        Integer statusCode = HttpStatus.OK.value();
        int code = 0;
        String resultCode;
        String msg;
        String orderId = (String)data.get("orderId");
 
        try {
            System.err.println("31. try 시작");
            int result = orderService.insertPayment(data);
            System.err.println("32. insertPayment :  " + result);
            if(result > 0) {
                code = 1;
                resultCode = "success";
                msg = "주문이 완료되었습니다.";
            } else {
                code = -1;
                resultCode = "fail";
                msg = "주문중 오류가 발생했습니다.";
            }
        } catch (Exception e) {
            code = -1;
            resultCode = "fail";
            msg = "오류가 발생했습니다.";
        }
        return new ResponseDTO<String>(statusCode, code, resultCode, msg, orderId);
    }
    
    /**
     * 비회원 로그인 프로세스
     * @param vo: 사용자 정보
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("loginOrder.do")
    public String loginOrder(ClientVO vo, HttpServletRequest request, HttpServletResponse response, Model model, @Param("cartList"String cartList) {
        HttpSession session = request.getSession();
        ClientVO client = clientService.getClient(vo);
        
        if(client != null) {
            // 아이디 존재
            if(!passwordEncoder.matches(vo.getClientPwd(), client.getClientPwd())) {
                // 비밀번호 불일치
                model.addAttribute("msg""비밀번호가 일치하지 않습니다.");
                return "order/orderLogin";
            } else {
                // 로그인 성공
                session.setAttribute("userInfo", client);
                session.setMaxInactiveInterval(10*60);
                
                // 쿠키 존재하는 경우 쿠키 삭제
                if(ClientCookie.checkCookie(request, response) == 1) {
                    clientService.changeCookieSetId(WebUtils.getCookie(request, "clientCookie").getValue(), vo.getClientId());
                    ClientCookie.removeCookie(request, response);
                }
                return "redirect:orderRegister.do?cartList="+cartList;
            }
        } else {
            // 아이디 불일치
            model.addAttribute("msg""아이디가 존재하지 않습니다.");
            return "order/orderLogin";
        }
    }
 
    /** 주문 수정 */
    @ResponseBody
    @PostMapping("updateOrder.do")
    public ResponseDTO<OrderInfoVO> updateOrder(OrderInfoVO order, String orderStatus, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Integer statusCode = HttpStatus.OK.value();
        int code = 0;
        String resultCode;
        String msg;
        
        Map<String, Object> orderData = new HashMap<String, Object>();
        orderData.put("order", order);
        orderData.put("orderStatus", orderStatus);
        
        if(session.getAttribute("userInfo"== null) {
            orderData.put("cookieId", (String)session.getAttribute("cookieId"));
        } else {
            ClientVO client = (ClientVO) session.getAttribute("userInfo");
            orderData.put("clientId", client.getClientId());
        }
        
        System.err.println("orderData : " + orderData);
        
        try {
            int result = orderService.updateOrder(orderData);
            if(result > 0) {
                code = 1;
                resultCode = "success";
                msg = "주문 상태가 변경되었습니다.";
            } else {
                code = -1;
                resultCode = "fail";
                msg = "오류가 발생했습니다.";
            }
        } catch (Exception e) {
            code = -1;
            resultCode = "fail";
            msg = "오류가 발생했습니다.";
        }
        
        return new ResponseDTO<OrderInfoVO>(statusCode, code, resultCode, msg, order);
    }
 
    /** 교환, 환불 요청 */
    @ResponseBody
    @PostMapping("insertSwapRefund.do")
    public ResponseDTO<String> insertSwapRefund(String requestWhat, String orderId, String optionId, String reason, String email, 
                                                String deliverWay, int cost, String costMtd, String status, String bankId, String refundBankNum, 
                                                HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Integer statusCode = HttpStatus.OK.value();
        int code = 0;
        String resultCode;
        String msg;
        String id = "";
        
        Map<String, Object> requestInfo = new HashMap<String, Object>();
        requestInfo.put("requestWhat", requestWhat);
        requestInfo.put("orderId", orderId);
        requestInfo.put("reason", reason);
        requestInfo.put("email", email);
        requestInfo.put("deliverWay", deliverWay);
        requestInfo.put("cost", cost);
        requestInfo.put("costMtd", costMtd);
        requestInfo.put("status", status);
 
        if(requestWhat.equals("swap")) {
            id += "SW";
        } else if(requestWhat.equals("refund")) {
            id += "RF";
            requestInfo.put("bankId", bankId);
            requestInfo.put("refundBankNum", refundBankNum);
        }
        id += RandomString.createFileName() + RandomString.setRandomString(5"number");
        requestInfo.put("id", id);
        
        if(session.getAttribute("userInfo"!= null) {
            ClientVO client = (ClientVO) session.getAttribute("userInfo");
            requestInfo.put("clientId", client.getClientId());
        }
        
        System.err.println("requestInfo : " + requestInfo);
        
        try {
            int result = orderService.insertSwapRefund(requestInfo);
            if(result > 0) {
                code = 1;
                resultCode = "success";
                msg = "주문 상태가 변경되었습니다.";
            } else {
                code = -1;
                resultCode = "fail";
                msg = "오류가 발생했습니다.";
            }
        } catch (Exception e) {
            code = -1;
            resultCode = "fail";
            msg = "오류가 발생했습니다.";
        }
        
        return new ResponseDTO<String>(statusCode, code, resultCode, msg, id);
    }
}
 

 

 

orderRegister.jsp 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
<%@ 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="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WeatherWear 사용자</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400;500&amp;family=Inter:wght@400;500&amp;family=Playfair+Display:ital,wght@0,400;0,700;1,400;1,700&amp;display=swap" rel="stylesheet">
 
<!-- Vendor CSS Files -->
<link href="resources/client/ZenBlog/assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="resources/client/ZenBlog/assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
 
<!-- Swiper -->
<link href="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.css" rel="stylesheet"/>
 
<!-- Template Main CSS Files -->
<link href="resources/client/ZenBlog/assets/css/main.css" rel="stylesheet">
<link href="resources/client/ZenBlog/assets/css/variables.css" rel="stylesheet">
 
<!-- 주소 검색 -->
<script src="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<style>
    .resultDiv{ height: 55px; font-size: larger !important; display: flex; align-items: center;}
    .inputLabel{ font-size: larger !important; display: flex; align-items: center; justify-content: center;}
    .resultInput{ font-size: larger !important; display: flex; align-items: center; justify-content: flex-end;}
    .selectOption{ border-radius:0; text-align: center; font-size: large;}
    .check {width:15px; height:15px;}
    .rowDivForm {height: 700px;}
    .payBtn { width:100%; height:70px; font-size: x-large; background-color: black; color: white; border-radius: 0;}
    .deliDiv { display: flex; justify-content: space-between;}
    .confirmDiv {border-bottom:1px solid silver; margin-bottom:10px;}
</style>
</head>
<body class="hold-transition sidebar-collapse layout-top-nav">
    <div class="wrapper">
        <%@ include file="../header.jsp" %>
 
        <main id="main">
            <section id="contact" class="contact mb-5">
                <div class="container aos-init aos-animate" data-aos="fade-up">
                    <div class="row">
                        <div class="col-lg-12 text-center mb-5">
                            <h1 class="page-title">ORDER</h1>
                        </div>
                    </div>
                    <div class="row gy-4">
                        <div class="col-md-6">
                            <div class="form mt-5">
                                <div class="php-email-form rowDivForm">
                                    <div class="form-group">
                                        <h3>주문자</h3>
                                    </div>
                                    <div class="form-group">
                                        <input type="text" name="clientName" class="form-control" id="clientName" placeholder="이름" required <c:if test="${ userInfo != null }">value="${ userInfo.clientName }"</c:if>>
                                        <input type="hidden" id="clientId" <c:if test="${ userInfo != null }">value="${ userInfo.clientId }"</c:if>>
                                    </div>
                                    <div class="form-group">
                                        <input type="email" class="form-control" name="clientEmail" id="clientEmail" placeholder="이메일" required <c:if test="${ userInfo != null }">value="${ userInfo.clientEmail }"</c:if>>
                                    </div>
                                    <div class="form-group">
                                        <input type="text" class="form-control" name="clientNum" id="clientNum" required placeholder="연락처" maxlength="13" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(^02.{0}|^01.{1}|[0-9]{3,4})([0-9]{3,4})([0-9]{4})/g, '$1-$2-$3')" <c:if test="${ userInfo != null }">value="${fn:substring(userInfo.clientNum,0,3)}-${fn:substring(userInfo.clientNum,3,7)}-${fn:substring(userInfo.clientNum,7,12)}"</c:if>>
                                    </div>
                                    <c:if test="${ userInfo == null }">
                                        <div class="form-group"><br>
                                            <hr>
                                            <h3>비회원 주문조회 비밀번호</h3><br>
                                        </div>
                                        <div class="form-group">
                                            <input type="password" class="form-control" name="cookiePwd" id="cookiePwd" placeholder="비회원 비밀번호" >
                                        </div>
                                        <div class="form-group" id="checkPwd">
                                            <input type="password" class="form-control" name="cookiePwdCheck" id="cookiePwdCheck" placeholder="비회원 비밀번호 확인" onchange="checkPwd(this)">
                                        </div>
                                    </c:if>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form mt-5">
                                <div class="php-email-form rowDivForm">
                                    <div class="form-group">
                                        <h3>배송지</h3>
                                    </div>
                                    <div class="form-group">
                                        <div class="row">
                                            <div class="form-group col-md-8">
                                                <div class="custom-control custom-radio">
                                                    <input class="custom-control-input custom-control-input-danger" type="radio" id="sameInfo" name="addressInfo">
                                                    <label for="sameInfo" class="custom-control-label">주문자 정보와 동일</label>&nbsp;&nbsp;&nbsp;
                                            <c:if test="${ userInfo != null }">
                                                    <input class="custom-control-input custom-control-input-danger" type="radio" id="newInfo" name="addressInfo">
                                                    <label for="newInfo" class="custom-control-label">새로운 배송지</label>
                                            </c:if>
                                                </div>
                                            </div>
                                            <c:if test="${ userInfo != null }">
                                            <div class="form-group col-md-4">
                                                <input type="button" class="form-control" value="배송지목록" id="addressListBtn" onclick="getAddressList()">
                                            </div>
                                            </c:if>
                                        </div>
                                    </div>
                            <c:if test="${ userInfo != null }">
                                    <div class="form-group">
                                        <input type="text" name="addressTitle" class="form-control" id="addressTitle" placeholder="배송지 이름" required <c:if test="${ userInfo != null }">value="${ baseAddress.addressTitle }"</c:if>>
                                    </div>
                            </c:if>    
                                    <div class="form-group">
                                        <input type="text" name="addressName" class="form-control" id="addressName" placeholder="받는 사람" required <c:if test="${ userInfo != null }">value="${ baseAddress.addressName }"</c:if>>
                                        <input type="hidden" name="addressId" class="form-control" id="addressId" <c:if test="${ userInfo != null }">value="${ baseAddress.addressId }"</c:if>>
                                    </div>
                                    <div class="row">
                                        <div class="form-group col-md-6">
                                            <input type="text" name="addressPostNum" class="form-control" id="addressPostNum" placeholder="우편번호" required disabled <c:if test="${ userInfo != null }">value="${ baseAddress.addressPostNum }"</c:if>>
                                        </div>
                                        <div class="form-group col-md-6">
                                            <input type="button" class="form-control" value="주소검색" id="findAddressBtn" onclick="daumPost()">
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <input type="text" class="form-control" name="address1" id="address1" placeholder="기본주소" required disabled <c:if test="${ userInfo != null }">value="${ baseAddress.address1 }"</c:if>>
                                    </div>
                                    <div class="form-group">
                                        <input type="text" class="form-control" name="address2" id="address2" required placeholder="상세주소" <c:if test="${ userInfo != null }">value="${ baseAddress.address2 }"</c:if>>
                                    </div>
                                    <div class="form-group">
                                        <input type="text" class="form-control" name="addressNum" id="addressNum" required placeholder="연락처" maxlength="13" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(^02.{0}|^01.{1}|[0-9]{3,4})([0-9]{3,4})([0-9]{4})/g, '$1-$2-$3')" <c:if test="${ userInfo != null }">value="${fn:substring(userInfo.clientNum,0,3)}-${fn:substring(userInfo.clientNum,3,7)}-${fn:substring(userInfo.clientNum,7,12)}"</c:if>>
                                    </div>
                                    <div class="form-group" id="deliMsgDiv">
                                        <select class="form-control selectOption" id="deliveryMessage" name="deliveryMessage" onchange="setMessage()">
                                            <option value=""  <c:if test="${ userInfo == null }">selected="selected"</c:if>>---------- 배송메시지 선택 (선택사항) ----------</option>
                                            <option value="배송 전에 미리 연락바랍니다." <c:if test="${ userInfo != null && baseAddress.addressMemo eq '배송 전에 미리 연락바랍니다.'}">selected="selected"</c:if>>배송 전에 미리 연락바랍니다.</option>
                                            <option value="부재 시 경비실에 맡겨주세요." <c:if test="${ userInfo != null && baseAddress.addressMemo eq '부재 시 경비실에 맡겨주세요.'}">selected="selected"</c:if>>부재 시 경비실에 맡겨주세요.</option>
                                            <option value="부재 시 문 앞에 놓아주세요." <c:if test="${ userInfo != null && baseAddress.addressMemo eq '부재 시 문 앞에 놓아주세요.'}">selected="selected"</c:if>>부재 시 문 앞에 놓아주세요.</option>
                                            <option value="빠른 배송 부탁드립니다." <c:if test="${ userInfo != null && baseAddress.addressMemo eq '빠른 배송 부탁드립니다.'}">selected="selected"</c:if>>빠른 배송 부탁드립니다.</option>
                                            <option value="택배함에 보관해 주세요." <c:if test="${ userInfo != null && baseAddress.addressMemo eq '택배함에 보관해 주세요.'}">selected="selected"</c:if>>택배함에 보관해 주세요.</option>
                                            <option value="inputmessage" <c:if test="${ userInfo!=null&&baseAddress.addressMemo!=null&&baseAddress.addressMemo!='배송 전에 미리 연락바랍니다.'&&baseAddress.addressMemo!='부재 시 경비실에 맡겨주세요.'&& baseAddress.addressMemo!='부재 시 문 앞에 놓아주세요.'&&baseAddress.addressMemo!='빠른 배송 부탁드립니다.'&&baseAddress.addressMemo!='택배함에 보관해 주세요.'}">selected="selected"</c:if>>직접 입력</option>
                                        </select>
                                        <div class="form-group" id="deliDiv">
                                            <c:if test="${ userInfo!=null&&baseAddress.addressMemo!=null&&baseAddress.addressMemo!='배송 전에 미리 연락바랍니다.'&&baseAddress.addressMemo!='부재 시 경비실에 맡겨주세요.'&& baseAddress.addressMemo!='부재 시 문 앞에 놓아주세요.'&&baseAddress.addressMemo!='빠른 배송 부탁드립니다.'&&baseAddress.addressMemo!='택배함에 보관해 주세요.'}">
                                                <input type='text' class='form-control' name='deliMsg' id='deliMsg' required value="${ baseAddress.addressMemo }">
                                            </c:if>
                                        </div>
                                    </div>
                            <c:if test="${ userInfo != null }">
                                    <div class="form-group">
                                        <input type="checkbox" <c:if test="${ userInfo != null }">value="Y"</c:if><c:if test="${ userInfo == null }">value="N"</c:if> class="check" name="baseAddress" id="baseAddress">
                                        <label for="baseAddress" class="custom-control-label">기본 배송지로 등록</label>
                                    </div>
                            </c:if>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="form mt-5">
                            <div class="php-email-form">
                                <div class="form-group">
                                    <h3>주문 상품</h3>
                                </div>
                                <c:forEach items="${ orderList }" var="pro">
            <!-- 상품마다 반복 시작 -->
                                <div class="form-group" class="productDiv">
                                    <div class="row gy-4">
                                        <div class="col-md-2">
                                            <img class="product_image" src="${ pro.product.mainImage }" style="height:150px; width:150px;">
                                        </div>
                                        <div class="col-md-9">
                                            <h4>${ pro.product.productName }</h4>
                                            <h5>${ pro.option.optionColor } / ${ pro.option.optionSize }</h5>
                                            <h5>수량 : ${ pro.cartCnt }</h5><br>
                                            <h4 class="productPrice"><fmt:formatNumber pattern="#,###,###" value="${ pro.product.productPrice * pro.cartCnt }" /></h4>
                                            <input type="hidden" name="productPrice" class="productPriceInput" value="${ pro.product.productPrice * pro.cartCnt }">
                                            <input type="hidden" name="cartCnt" class="cartCnt" value="${ pro.cartCnt }">
                                            <input type="hidden" name="cartId" class="cartId" value="${ pro.cartId }">
                                            <input type="hidden" name="optionId" class="optionId" value="${ pro.optionId }">
                                        </div>
                                    </div>
                                </div>
            <!-- 상품마다 반복 끝 -->
                                </c:forEach>
                                <div class="row resultDiv" style="background-color:#F6F6F6;">
                                    <div class="form-group col-md-1 resultDiv"></div>
                                    <div class="form-group col-md-2 resultDiv">
                                        배송비<input type="hidden" name="deliveryPrice" id="deliveryPrice">    
                                    </div>
                                    <div class="form-group col-md-7 resultDiv"></div>
                                    <div class="form-group col-md-2 resultDiv" id="deliveryPriceDiv"></div>
                                </div><!-- End DeliveryPrice -->
                            </div>
                        </div>
                    </div>
            <c:if test="${ userInfo != null }">
                <!-- 할인(회원) -->
                    <div class="row">
                        <div class="form mt-5">
                            <div class="php-email-form">
                                <div class="form-group">
                                    <h3>할인</h3>
                                </div>
                                <div class="row">
                                    <div class="form-group col-md-2 inputLabel">
                                        포인트 [ <fmt:formatNumber pattern="#,###,###" value="${ userInfo.clientPoint }"/> ]
                                    </div>
                                    <div class="form-group col-md-8">
                                        <input type="number" class="form-control" name="usedPoint" id="usedPoint" value="0">
                                        <input type="hidden" class="form-control" name="clientPoint" id="clientPoint" value=${ userInfo.clientPoint }>
                                    </div>
                                    <div class="form-group col-md-2">
                                        <input type="button" class="form-control" value="전체사용" id="applyAllPoint">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="form-group col-md-2 inputLabel">
                                        쿠폰
                                    </div>
                                    <div class="form-group col-md-10">
                                        <select class="form-control selectOption" id="couponId" name="couponId">
                                            <option value="0" selected="selected">------------ 쿠폰 선택 ------------</option>
                                            <c:forEach items="${ couponList }" var="coupon">
                                                <option value="${ coupon.couponPrice }_${ coupon.minPrice }_${ coupon.couponId }" class="couponOption">
                                                    ${ coupon.couponName }&nbsp;&nbsp;&nbsp;
                                                    [ 적용금액: <fmt:formatNumber pattern="#,###,###" value="${ coupon.couponPrice }"/> | 
                                                    최소금액: <fmt:formatNumber pattern="#,###,###" value="${ coupon.minPrice }"/> ]
                                                </option>
                                            </c:forEach>
                                        </select>
                                    </div>
                                </div>
                                <div class="row resultDiv" style="background-color:#F6F6F6;">
                                    <div class="form-group col-md-1 resultDiv"></div>
                                    <div class="form-group col-md-2 resultDiv">
                                        적용금액
                                    </div>
                                    <div class="form-group col-md-7 resultDiv"></div>
                                    <div class="form-group col-md-2 resultDiv" id="discountPrice"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </c:if>
                    <div class="row">
                        <div class="form mt-5">
                            <div class="php-email-form">
                                <div class="form-group">
                                    <h3>결제 정보</h3>
                                </div>
                                <div class="row">
                                    <div class="form-group col-md-1"></div>
                                    <div class="form-group col-md-2 inputLabel">
                                        주문상품
                                    </div>
                                    <div class="form-group col-md-7"></div>
                                    <div class="form-group col-md-1 resultInput" id="totalOrderPrice"></div>
                                    <div class="form-group col-md-1"></div>
                                </div>
                                <div class="row">
                                    <div class="form-group col-md-1"></div>
                                    <div class="form-group col-md-2 inputLabel">
                                        배송비
                                    </div>
                                    <div class="form-group col-md-7"></div>
                                    <div class="form-group col-md-1 resultInput" id="totalDeliveryPrice"></div>
                                    <div class="form-group col-md-1"></div>
                                </div>
                                <div class="row">
                                    <div class="form-group col-md-1"></div>
                                    <div class="form-group col-md-2 inputLabel">
                                        할인
                                    </div>
                                    <div class="form-group col-md-7"></div>
                                    <div class="form-group col-md-1 resultInput" id="totalDiscountPrice"></div>
                                    <div class="form-group col-md-1"></div>
                                </div>
                                <div class="row resultDiv" style="background-color:#F4F7FF;">
                                    <div class="form-group col-md-1 resultDiv"></div>
                                    <div class="form-group col-md-2 resultDiv">
                                        최종 결제 금액<input type="hidden" name="orderPrice" id="orderPrice">
                                    </div>
                                    <div class="form-group col-md-7 resultDiv"></div>
                                    <div class="form-group col-md-2 resultDiv" id="totalPayPrice"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="form mt-5">
                            <div class="php-email-form">
                                <div class="form-group">
                                    <h3>결제 방식</h3>
                                </div>
                                <div class="row">
                                    <div class="form-group col-md-3">
                                        <input type="button" class="form-control" value="일반결제" id="html5_inicis">
                                    </div>
                                    <div class="form-group col-md-3">
                                        <input type="button" class="form-control" value="카카오페이" id="kakaopay">
                                    </div>
                                    <div class="form-group col-md-3">
                                        <input type="button" class="form-control" value="토스페이" id="tosspay">
                                    </div>
                                    <div class="form-group col-md-3">
                                        <input type="button" class="form-control" value="가상결제" id="vbank">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="form mt-5">
                            <input type="button" class="payBtn" value="결제하기" onclick="checkSubmit()">
                        </div>
                    </div>
                </div>
            </section>
        </main>
        
        <%@ include file="../footer.jsp" %>
    </div>
 
<script src="resources/client/ZenBlog/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script  src="resources/util/plugins/sweetalert/jquery-lates.min.js"></script>
<script src="resources/util/plugins/sweetalert/sweetalert2.js"></script>
 
<!-- Template Main JS File -->
<script src="resources/client/ZenBlog/assets/js/main.js"></script>
<!-- sweetAlert (alert/confirm/toast) -->
<script src="resources/util/js/sweetalert.js"></script>
<!-- PortOne SDK -->
<script src="https://cdn.iamport.kr/v1/iamport.js"></script>
<!-- iamport.payment.js -->
<script type="text/javascript" src="https://cdn.iamport.kr/js/iamport.payment-1.1.5.js"></script>
 
<script src="resources/client/js/post.js"></script>
<script src="resources/client/js/orderRegister.js"></script>
<script src="resources/client/js/orderReady.js"></script>
</body>
</html>

 

 

 

반응형