프로젝트

[ Spring Boot 프로젝트 ] 결제하기 / 결제완료 문자발송

sian han 2022. 7. 14. 11:09

선택한 결제 API : 아임포트 IMPORT

 

 

아임포트 라이브러리

<script type="text/javascript" src="https://cdn.iamport.kr/js/iamport.payment-1.1.8.js">

 

 

 

 

▷ orderPayment.jsp 

  - 결제요청 view

<div class="orderPaymentWrapper">
    <input type="hidden" id="payPrice" class="div" value="${payPrice }" name="payPrice"> 
    <label for = "orderNo"></label>
    <input type="hidden" id="orderNo" class="div" value="${orderNO }" name="orderNo">
    <input type="hidden" id="email" class="div" value="${email }" name="email">
    <input type="hidden" id="name" class="div" value="${name }" name="name">
    <input type="hidden" id="userPoint" class="div" value="${userPoint}" name="userPoint">
    <input type="hidden" id="savePoint" class="div" value="${savePoint }" name="savePoint"> 
    </div>
</div>

△ controller 에서 내려보낸 결제 관련 데이터들을 set

 

 

 

▽ 데이터들을 변수에 담아서 결제정보를 import 로 전송 ! 

$(function(){
	var paymentResult = true;
	$(document).ready(function () {
				var email = $('#email').val();
				var name = $('#name').val();
				var orderNo = $('#orderNo').val();
				var payPrice = $('#payPrice').val();
				var userPoint = $('#userPoint').val();
				var savePoint =$('#savePoint').val();
				
				console.log(savePoint);
				
				if(userPoint<0 || userPoint==null){
					userPoint = 0;
				}
				
				//전액 포인트로 결제할 경우
				if(payPrice ==0){
					$.ajax({
	                	type:'get',
	            		url:"/launer/laundryService/payment/requestPayment",
	            		data:{
	            			"orderNo" : orderNo,
	            			"payPrice" :payPrice,
	            			"userPoint" : userPoint,
	            			"savePoint" : savePoint,
	            		},
	            	});
					
					alert("결제가 완료되었습니다");
					document.location.href="/launer/mypage/paymentdetails";
					event.preventDefault();
	                return false;
				}

		        // getter
		        var IMP = window.IMP;
				IMP.init("imp--------");
		        
		        var amount = $('#payPrice').val();
		        console.log(amount);		        

		        IMP.request_pay({
	            	 pg: 'html5_inicis',
	                 paymentCode: 'p' + new Date().getTime(),
	                 pay_method:"card",
	                 merchant_uid: orderNo,
	                 amount: amount,
	                 name: '빨래',
	                 buyer_email: email,
	                 buyer_name: name,
	                // buyer_tel: '010-1111-1111', 
	            
		        }, function (rsp) {
		            console.log(rsp);
		            if (rsp.success) {
		            	
		            	
		                var msg = '결제가 완료되었습니다.';
		               // msg += '고유ID : ' + rsp.imp_uid;
		                msg += '카드 승인번호 : ' + rsp.apply_num;
		           
		                $.ajax({
		                	type:'get',
		            		url:"/launer/laundryService/payment/requestPayment",
		            		data:{
		            			"orderNo" : orderNo,
		            			"payPrice" :payPrice,
		            			"userPoint" : userPoint,
		            			"savePoint" : savePoint,
		            		},
		            	});
		            } else {
		            	var msg = '결제에 실패하였습니다. 메인화면으로 이동합니다';
		            	paymentResult = false;
		            }
		            alert(msg);
		            //alert창 확인 후 이동할 url 설정
		            if(paymentResult){
		           	  document.location.href="/launer/mypage/paymentdetails"; //결제 성공 시 이동할 url
		            }else {
		            	$.ajax({
		                	type:'get',
		            		url:"/launer/laundryService/payment/paymentFailed",
		            		data:{
		            			"orderNo" : orderNo,
		            			"payPrice" :payPrice,
		            			"userPoint" : userPoint,
		            			"savePoint" : savePoint,
		            		},
		            	});
		            	document.location.href="/launer"; //결제 성공 시 이동할 url
		            }          
			});
	});
});

 

 

 

 

▷ PaymentController

결제 성공 시

결제 완료 문자를 발송하고 결제테이블에 데이터 입력

//결제요청
	@GetMapping("/requestPayment")
	public String requestPayment_post(Model model, int orderNo,int payPrice, int savePoint,int userPoint, RedirectAttributes reAttr,
			HttpSession session) {
		int no = (int) session.getAttribute("no");
		
		System.out.println("fk주문번호="+orderNo);
		System.out.println("결제금액="+payPrice);
		System.out.println("userPoint="+userPoint);
		
		PaymentVO paymentVo = new PaymentVO();
		paymentVo.setOrderNo(orderNo);
		paymentVo.setPayPrice(payPrice);
		
		int result = paymentService.insertPaymentDetail(paymentVo);
		logger.info("결제성공여부 result={}",result);
		
		int rs = 0;
		if(result>0) {
			
			try {
				UserVO userVo = userService.selectById(no);
				String hp = userVo.getHp();
				String name = userVo.getName();
				smsApi.sendSms(hp,orderNo,name,payPrice,savePoint);
				logger.info("sms 전송완료");
			} catch (CoolsmsException e) {
				e.printStackTrace();
			}
			
			//orders 테이블 paymentDate null => sysdate
			rs = orderService.updatePaymentDate(orderNo);
			System.out.println("결제일(date)update="+rs);
		}

		reAttr.addAttribute("paymentCode", paymentVo.getPaymentCode());
		reAttr.addAttribute("paymentStatus", rs);

		return "/launer/laundryService/payment/orderPayment";
	}

 

 

문자발송 API 는 .. 사용하는데 어려움이 없었기 때문에 따로 기재하지 않겠음

사용된 API : coolSMS

 

 

주문하기 => 컨트롤러 주문정보 입력 => 결제요청 view => 결제요청 컨트롤러

   => 결제요청 view 로 돌아와서 결제 성공 view 로 redirect

 

 - 결제 api 적용할때 흐름이 좀 헷갈렸어서 적어놓음

 

 

 

++ 바보같은 실수를 했기에 .. . ..  문자발송 api 도 첨부함 ^^

  - 수신인 <-> 발송인 바꿔서 매개변수 넣어놨더라 ~~ 정신차리자 ~~~

@Service
public class SmsAPI {

	 public void sendSms(String hp,int orderNo,String name,int totalPrice, int point) throws CoolsmsException {

	        String api_key = "--"; // coolSms api_key
	        String api_secret = "--"; // coolSms api_secret
	        Message coolsms = new Message(api_key, api_secret);
	        HashMap<String, String> params = new HashMap<String, String>();

	        params.put("to", hp);
	        params.put("from", "coolsms 에서 등록한 전화번호);
	        params.put("type", "SMS");
	        params.put("text", "[러너] "+" 주문번호: "+orderNo+", "+name+"님, "+totalPrice+"원 결제완료되었습니다."+" 적립포인트: "+point+" p");
	        params.put("app_version", "test app 1.2");

	        try {
	            JSONObject obj = (JSONObject) coolsms.send(params);
	            System.out.println(obj.toString());
	        } catch (CoolsmsException e) {
	            System.out.println(e.getMessage());
	            System.out.println(e.getCode());
	        }
	    }
	
	
}