새소식

인기 검색어

풀스택개발자_대학교 정규과정/프로젝트_throwsgg

쇼핑몰 결제 및 취소 기능

  • -

시현 자료 : https://youtu.be/jRb8Iw4CGZ8

 

실제 결제가 완료된것을 확인 할 수 있다

paymenySerivce.java

package dao;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class paymentService {
	public String getToken() throws IOException {

		HttpsURLConnection conn = null;

		URL url = new URL("https://api.iamport.kr/users/getToken");

		// URL 연결 (웹페이지 URL 연결.)
		conn = (HttpsURLConnection) url.openConnection();

		// 요청 방식 선택 (GET, POST)
		conn.setRequestMethod("POST");
		// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 application/xml로 서버에 전달.)
		conn.setRequestProperty("Content-type", "application/json");
		// 서버 Response Data를 json 형식의 타입으로 요청.
		conn.setRequestProperty("Accept", "application/json");
		// OutputStream으로 POST 데이터를 넘겨주겠다는 옵션.
		conn.setDoOutput(true);

		JsonObject json = new JsonObject();

		json.addProperty("imp_key", "2526475461703220");
		json.addProperty("imp_secret",
				"2hpv1CyJoSrcsj1ZQWqz4Nsr2F0D5lXO5CmUg19N9KEk747KzQ3gcionK4o9bOU3Luj6fHhcRS9qjtN8");

		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));

		// 출력
		bw.write(json.toString());
		// 버퍼 비움
		bw.flush();
		bw.close();

		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

		Gson gson = new Gson();
		// Json 문자열 -> Map 객체로 변환 후 response 키 값의 value값을 추출
		String response = gson.fromJson(br.readLine(), Map.class).get("response").toString();

		System.out.println(response);
		// Json 문자열 -> Map 객체로 변환 후 access_token 키 값의 value값을 추출
		String token = gson.fromJson(response, Map.class).get("access_token").toString();

		br.close();
		conn.disconnect();

		return token;
	}

	public void paymentInfo(String access_token,String imp_uid) throws IOException {

		HttpsURLConnection conn = null;

		URL url = new URL("https://api.iamport.kr/payments/" + imp_uid);

		conn = (HttpsURLConnection) url.openConnection();

		conn.setRequestMethod("GET");
		conn.setRequestProperty("Authorization", access_token);
		conn.setDoOutput(true);

		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

		Gson gson = new Gson();

		Map<String, Object> response123 = gson.fromJson(br.readLine(), Map.class);

		br.close();
		conn.disconnect();
        // 방법3
        for( String key : response123.keySet() ){
            System.out.println( String.format("키 : %s, 값 : %s", key, response123.get(key)) );
        }

	}

	public void payMentCancle(String access_token, String imp_uid, int amount, String reason) throws IOException {//결제취소 요청 메서드
		System.out.println("결제 취소");

		System.out.println(access_token);

		System.out.println(imp_uid);

		HttpsURLConnection conn = null;
		URL url = new URL("https://api.iamport.kr/payments/cancel");

		conn = (HttpsURLConnection) url.openConnection();

		conn.setRequestMethod("POST");

		conn.setRequestProperty("Content-type", "application/json");
		conn.setRequestProperty("Accept", "application/json");
		conn.setRequestProperty("Authorization", access_token);

		conn.setDoOutput(true);

		JsonObject json = new JsonObject();

		json.addProperty("reason", reason);
		json.addProperty("imp_uid", imp_uid);
		json.addProperty("amount", amount);
		json.addProperty("checksum", amount);

		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));

		bw.write(json.toString());
		bw.flush();
		bw.close();

		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

		br.close();
		conn.disconnect();

	}
}

getToken메서드는 토큰을 생성하는 부분입니다 url 요청시 아래 사진과 같이 json형태의 데이터로 응답을 받는데 Gson을 사용하여 JSON문자열을 Map객체로 변환 후 추출하는 식으로 구현하였습니다.

 

Access Token 받기

이 토큰을 가지고 결제정보를 가져올수 있는데
paymentInfo메서드 부분입니다 토큰으로 결제정보를 요청할 경우
{"code":0,"message":null,"response":{"amount":6000, .... } 형태의
중첩 JSON문을 받아오는데 여기서 amount(금액)부분만 가져오면 됩니다

payMentCancle 메서드는 주문취소 로직을 가지는데 반드시 토큰정보와
imp_uid , 금액등이 필요합니다 

 

결제 관련 view.jsp

	function payment() {
        var IMP = window.IMP; // 생략가능
        IMP.init('가맹점 식별코드'); // 'iamport' 대신 부여받은 "가맹점 식별코드"를 사용
        var msg;
        
        var oderName = '${carVoList.get(0).getPname() } 외 ${carVoList.size() - 1}개';
		var name = $( 'input#name' ).val();
		var recipient = $( 'input#recipient' ).val();
		var phone = $( 'input#phone' ).val();
		var email =  $( 'input#email' ).val();
		var totalAmount = document.getElementById("FtotalPrice").innerText;
		var sample4_roadAddress = $( 'input#sample4_roadAddress' ).val();
		var sample4_detailAddress = $( 'input#sample4_detailAddress' ).val();
		if (name != ''&& phone != '' && email != '' && sample4_roadAddress != '' && sample4_detailAddress != '') {
	        IMP.request_pay({
	            pg : 'html5_inicis',
	            pay_method : 'card',
	            merchant_uid : 'merchant_' + new Date().getTime(),
	            name : oderName,
	            amount : totalAmount,
	            buyer_email : email,
	            buyer_name : name,
	            buyer_tel : phone,
	            buyer_addr : sample4_roadAddress+' '+sample4_detailAddress,
				buyer_postcode : '123-456',
				}, function(rsp) { // callback
					if (rsp.success) {
						// 결제 성공 시 로직,
						msg = '결제가 완료되었습니다.';
						msg += '\n은행 : ' + rsp.card_name;
						msg += '\n카드번호 : ' + rsp.card_number;
						msg += '\n주문번호 : ' + rsp.imp_uid;
						msg += '\nName : ' + oderName;
						msg += '\namount : ' + totalAmount;
						msg += '\nbuyer_email : ' + email;
						msg += '\nbuyer_name : ' + name;
						msg += '\nbuyer_tel : ' + phone;
						msg += '\nbuyer_addr : ' + sample4_roadAddress+' '+sample4_detailAddress;
						alert(msg);
						InsertSaleOrder(rsp.imp_uid, rsp.buyer_addr, rsp.buyer_tel, rsp.card_name, rsp.card_number, totalAmount, rsp.receipt_url,recipient);
					} else {
						// 결제 실패 시 로직,
						msg = '결제에 실패하였습니다.';
						msg += '에러내용 : ' + rsp.error_msg;
						alert(msg);
					}
				});
		} else{
			alert('양식이 유효하지 않습니다');
		}

	}
	function InsertSaleOrder(saleID,addr,tel,cardName,cardNo,total,detailLink,recipient) { // 제출 버튼 이벤트 지정
	    console.log('InsertSaleOrderAjax'); 
	    $.ajax({
	        type: "POST", // HTTP Method
	        url: "InsertSaleOrder.str", // 목적지
	        data: {
	            userid: '${sessionScope.id}', // 전송 데이터
	            saleID : saleID,
	            addr: addr,
	            tel: tel,
	            cardName: cardName,
	    		cardno: cardNo,
	    		total: total,
	    		detailLink: detailLink,
	    		recipient: recipient,
	    		prodcount: '${carVoList.size()}'
	    	}
	    }).done(function(data) {
	    	location.replace('userinfo.jsp');
	    }).fail(function(Response) {
	        console.log('에러')
	    });
	}

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.