PaymentService 개발
2024. 7. 1. 15:28ㆍ토비의 스프링 6
요구사항
- 해외직구를 위한 원화 결제 준비 기능 개발
- 주문번호, 외국 통화 종류, 외국 통화 기준 결제 금액을 전달 받아서 다음의 정보를 더해 Payment를 생성한다.
- 적용 환율
- 원화 환산 금액
- 원화 환산 금액 유효시간
- PaymentService.prepare() 메소드로 개발
- Payment 오브젝트 리턴
개발방법
- 빠르게 완성해서 가장 간단한 방법을 찾는다.
- 작성한 코드가 동작하는지 확인하는 방법을 찾는다.
- 조금씩 기능을 추가하고 다시 검증한다.
- 코드를 한눈에 이해하기 힘들다면 코멘트로 설명을 달아준다.
환율 가져오기
- https://open.er-api.com/v6/latest/{기준통화} 이용
- 이 서비스가 더이상 유효되지 않는 경우 사용할 다른 서비스 URL을 강의자료에서 확인
- JSON 포맷으로 리턴되는 값을 분석해서 원화(KRW) 환율 값을 가져온다
- JSON을 자바 오브젝트로 변환
- Jackson 프로젝트의 ObjectMapper 사용
Payment
package tobyspring.hellospring;
import java.math.BigDecimal;
import java.time.LocalDateTime;
public class Payment {
private Long orderId;
private String currency;
private BigDecimal foreignCurrenyAmount; //돈과같은 정확한 소수점 계산을 위한 자료형
private BigDecimal exRate;
private BigDecimal convertedAmount;
private LocalDateTime validUntil;
public Payment(Long orderId, String currency, BigDecimal foreignCurrenyAmount, BigDecimal exRate, BigDecimal convertedAmount, LocalDateTime validUntil) {
this.orderId = orderId;
this.currency = currency;
this.foreignCurrenyAmount = foreignCurrenyAmount;
this.exRate = exRate;
this.convertedAmount = convertedAmount;
this.validUntil = validUntil;
}
public Long getOrderId() {
return orderId;
}
public String getCurrency() {
return currency;
}
public BigDecimal getForeignCurrenyAmount() {
return foreignCurrenyAmount;
}
public BigDecimal getExRate() {
return exRate;
}
public BigDecimal getConvertedAmount() {
return convertedAmount;
}
public LocalDateTime getValidUntil() {
return validUntil;
}
@Override
public String toString() {
return "Payment{" +
"orderId=" + orderId +
", currency='" + currency + '\'' +
", foreignCurrenyAmount=" + foreignCurrenyAmount +
", exRate=" + exRate +
", convertedAmount=" + convertedAmount +
", validUntil=" + validUntil +
'}';
}
}
PaymentService
package tobyspring.hellospring;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;
import java.util.stream.Collectors;
public class PaymentService {
public Payment prepare(Long orderId, String currency, BigDecimal foreignCurrencyAmount) throws IOException {
//환율 가져오기
URL url = new URL("https://open.er-api.com/v6/latest/"+currency);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = br.lines().collect(Collectors.joining());
br.close();
ObjectMapper mapper = new ObjectMapper();
ExRateData data = mapper.readValue(response, ExRateData.class);
BigDecimal exRate = data.rates().get("KRW");
System.out.println(exRate);
//금액 계산
BigDecimal convertedAmount = foreignCurrencyAmount.multiply(exRate); //* 사용안하고 multiply사용
//유효 시간 계산
LocalDateTime validUntil = LocalDateTime.now().plusMinutes(30);
return new Payment(orderId,currency,foreignCurrencyAmount,exRate,convertedAmount,validUntil);
}
public static void main(String[] args) throws IOException {
PaymentService paymentService = new PaymentService();
Payment payment = paymentService.prepare(100L,"USD",BigDecimal.valueOf(50.7));
System.out.println(payment);
}
}
ExRateData
package tobyspring.hellospring;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.math.BigDecimal;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public record ExRateData(String result, Map<String, BigDecimal> rates) {
}'토비의 스프링 6' 카테고리의 다른 글
| 오브젝트 팩토리 (0) | 2024.07.03 |
|---|---|
| 관계설정 책임의 분리 (0) | 2024.07.03 |
| 인터페이스 도입 (0) | 2024.07.03 |
| 클래스의 분리 (0) | 2024.07.03 |
| 오브젝트와 의존관계 (0) | 2024.07.02 |