diff --git a/.github/workflows/ci-cd-payment-service.yml b/.github/workflows/ci-cd-payment-service.yml index 7363627..b26511c 100644 --- a/.github/workflows/ci-cd-payment-service.yml +++ b/.github/workflows/ci-cd-payment-service.yml @@ -10,12 +10,12 @@ env: SERVICE_NAME: payment-service # 예: order-service DOCKER_IMAGE: ${{ secrets.DOCKERHUB_USERNAME }}/${{ vars.DOCKER_IMAGE_NAME }}:latest EC2_HOST: ${{ secrets.EC2_HOST }} - EC2_SSH_USER: ec2-user + EC2_SSH_USER: ${{secrets.EC2_SSH_USER}} PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }} TIMEZONE: Asia/Seoul DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} DOCKER_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} - PROJECT_PATH: /home/ec2-user/delivery-system/payment-service # 예: /home/ec2-user/delivery-system/order-service + PROJECT_PATH: /home/kmj02dev/delivery-system/payment-service # 예: /home/ec2-user/delivery-system/order-service APPLICATION: ${{ secrets.APPLICATION }} jobs: diff --git a/payment-service/.gitattributes b/payment-service/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/payment-service/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/payment-service/.gitignore b/payment-service/.gitignore new file mode 100644 index 0000000..3b33c53 --- /dev/null +++ b/payment-service/.gitignore @@ -0,0 +1,38 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ +*.yml + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/payment-service/README.md b/payment-service/README.md index 6f7d059..af7dc69 100644 --- a/payment-service/README.md +++ b/payment-service/README.md @@ -1,2 +1,3 @@ # Server + 가천대학교 2025-1 고급 웹프로그래밍 <TEAM 1 - (server)> diff --git a/payment-service/build.gradle b/payment-service/build.gradle new file mode 100644 index 0000000..4fdf47f --- /dev/null +++ b/payment-service/build.gradle @@ -0,0 +1,65 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.5' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'gcu.web' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +ext { + set('springCloudVersion', "2023.0.1") +} + + +dependencies { + + /// 기본 의존성 + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + + /// Lombok + annotationProcessor 'org.projectlombok:lombok' + compileOnly 'org.projectlombok:lombok' + + /// FeignClient + implementation 'org.springframework.cloud:spring-cloud-starter-openfeign' + + /// JPA + runtimeOnly 'com.mysql:mysql-connector-j' + + /// SWAGGER + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0' + + + /// Test + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testImplementation 'com.h2database:h2' +} + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" + } +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/payment-service/gradle/wrapper/gradle-wrapper.jar b/payment-service/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9bbc975 Binary files /dev/null and b/payment-service/gradle/wrapper/gradle-wrapper.jar differ diff --git a/payment-service/gradle/wrapper/gradle-wrapper.properties b/payment-service/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..37f853b --- /dev/null +++ b/payment-service/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/payment-service/gradlew b/payment-service/gradlew new file mode 100755 index 0000000..faf9300 --- /dev/null +++ b/payment-service/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/payment-service/gradlew.bat b/payment-service/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/payment-service/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/payment-service/settings.gradle b/payment-service/settings.gradle new file mode 100644 index 0000000..d90e184 --- /dev/null +++ b/payment-service/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'payment-service' diff --git a/payment-service/src/main/java/gcu/web/paymentservice/PaymentServiceApplication.java b/payment-service/src/main/java/gcu/web/paymentservice/PaymentServiceApplication.java new file mode 100644 index 0000000..56212f9 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/PaymentServiceApplication.java @@ -0,0 +1,14 @@ +package gcu.web.paymentservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; + +@EnableFeignClients +@SpringBootApplication +public class PaymentServiceApplication { + public static void main(String[] args) { + SpringApplication.run(PaymentServiceApplication.class, args); + } +} + diff --git a/payment-service/src/main/java/gcu/web/paymentservice/common/config/SwaggerConfig.java b/payment-service/src/main/java/gcu/web/paymentservice/common/config/SwaggerConfig.java new file mode 100644 index 0000000..85c1a68 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/common/config/SwaggerConfig.java @@ -0,0 +1,25 @@ +package gcu.web.paymentservice.common.config; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SwaggerConfig { + + @Bean + public OpenAPI openAPI() { + return new OpenAPI() + .components(new Components()) + .info(apiInfo()); + } + + private Info apiInfo() { + return new Info() + .version("1.0") + .title("고급 웹프로그래밍 API") + .description("고급 웹프로그래밍 결제 서버의 API 입니다"); + } +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/common/config/WebMvcConfig.java b/payment-service/src/main/java/gcu/web/paymentservice/common/config/WebMvcConfig.java new file mode 100644 index 0000000..c592bc3 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/common/config/WebMvcConfig.java @@ -0,0 +1,24 @@ +package gcu.web.paymentservice.common.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins("http://localhost:3000", "http://localhost:5173", "http://54.66.149.225", "http://34.127.7.212") + .allowedMethods("GET", "POST", "PUT", "DELETE") + .allowedHeaders("*") // 모든 헤더 허용 + .allowCredentials(true); // 쿠키 포함 허용; + + // addMapping : CORS를 적용할 url의 패턴을 정의 ("/**"로 모든 패턴 가능) + // allowedOrigins : 허용할 origin ("*"로 모든 origin 허용 가능, 여러 개도 지정 가능) + // allowedMethods : 허용할 HTTP Method ("*"로 모든 Method 허용 가능) + // maxAge : 요청을 캐싱할 시간 + } +} + diff --git a/payment-service/src/main/java/gcu/web/paymentservice/common/response/ApiResponse.java b/payment-service/src/main/java/gcu/web/paymentservice/common/response/ApiResponse.java new file mode 100644 index 0000000..0740b89 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/common/response/ApiResponse.java @@ -0,0 +1,31 @@ +package gcu.web.paymentservice.common.response; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.micrometer.common.lang.Nullable; +import org.springframework.http.HttpStatus; + +public record ApiResponse( + @JsonIgnore + HttpStatus httpStatus, + boolean isSuccess, + @Nullable int code, + @Nullable String message, + @Nullable T data + +) { + + public static ApiResponse ok(@Nullable final T data, @Nullable final String message) { + return new ApiResponse<>(HttpStatus.OK, true, 1000, message, data); + } + + public static ApiResponse created(@Nullable final T data, @Nullable final String message) { + return new ApiResponse<>(HttpStatus.CREATED, true, 1001, message, data); + } + + public static ApiResponse fail(final CustomException e) { + ExceptionDto dto = ExceptionDto.of(e.getErrorCode()); + return new ApiResponse<>(e.getErrorCode().getHttpStatus(), false, dto.getCode(), dto.getMessage(), null); + } + + +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/common/response/CustomException.java b/payment-service/src/main/java/gcu/web/paymentservice/common/response/CustomException.java new file mode 100644 index 0000000..ceef65d --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/common/response/CustomException.java @@ -0,0 +1,14 @@ +package gcu.web.paymentservice.common.response; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class CustomException extends RuntimeException{ + private final ErrorCode errorCode; + + public String getMessage() { + return errorCode.getMessage(); + } +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/common/response/ErrorCode.java b/payment-service/src/main/java/gcu/web/paymentservice/common/response/ErrorCode.java new file mode 100644 index 0000000..3625ddd --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/common/response/ErrorCode.java @@ -0,0 +1,28 @@ +package gcu.web.paymentservice.common.response; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum ErrorCode { + + // Test Error + TEST_ERROR(100, HttpStatus.BAD_REQUEST, "테스트 에러입니다."), + // 400 Bad Request + BAD_REQUEST(400, HttpStatus.BAD_REQUEST, "잘못된 요청입니다."), + // 403 Bad Reques + Forbidden(403, HttpStatus.FORBIDDEN, "접속 권한이 없습니다."), + // 404 Not Found + NOT_FOUND_END_POINT(404, HttpStatus.NOT_FOUND, "요청한 대상이 존재하지 않습니다."), + // 500 Internal Server Error + INTERNAL_SERVER_ERROR(500, HttpStatus.INTERNAL_SERVER_ERROR, "서버 내부 오류입니다."), + + /// 결제 + NOT_FOUND_EXIST_PAYMENT(5000, HttpStatus.NOT_FOUND, "결제 내역이 존재하지 않습니다."),; + + private final Integer code; + private final HttpStatus httpStatus; + private final String message; +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/common/response/ExceptionDto.java b/payment-service/src/main/java/gcu/web/paymentservice/common/response/ExceptionDto.java new file mode 100644 index 0000000..a50e5de --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/common/response/ExceptionDto.java @@ -0,0 +1,23 @@ +package gcu.web.paymentservice.common.response; + +import lombok.Getter; +import org.antlr.v4.runtime.misc.NotNull; + +@Getter +public class ExceptionDto { + + @NotNull + private final Integer code; + + @NotNull + private final String message; + + public ExceptionDto(ErrorCode errorCode) { + this.code = errorCode.getCode(); + this.message = errorCode.getMessage(); + } + + public static ExceptionDto of(ErrorCode errorCode) { + return new ExceptionDto(errorCode); + } +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/common/response/pageable/PageRequest.java b/payment-service/src/main/java/gcu/web/paymentservice/common/response/pageable/PageRequest.java new file mode 100644 index 0000000..29d5836 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/common/response/pageable/PageRequest.java @@ -0,0 +1,21 @@ +package gcu.web.paymentservice.common.response.pageable; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.SuperBuilder; +import lombok.extern.slf4j.Slf4j; + +@Data +@SuperBuilder +@AllArgsConstructor +@NoArgsConstructor +@Slf4j +public class PageRequest { + @Builder.Default + private int page = 1; + + @Builder.Default + private int size = 10; +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/common/response/pageable/PageResponse.java b/payment-service/src/main/java/gcu/web/paymentservice/common/response/pageable/PageResponse.java new file mode 100644 index 0000000..c5c20de --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/common/response/pageable/PageResponse.java @@ -0,0 +1,58 @@ +package gcu.web.paymentservice.common.response.pageable; + +import lombok.Builder; +import lombok.Data; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + + +@Data +public class PageResponse { + + private List dtoList; + + private List pageNumList; + + private PageRequest pageRequest; + + private boolean prev, next; + + private int totalCount, prevPage, nextPage, totalPage, current; + + @Builder(builderMethodName = "withAll") + public PageResponse(List dtoList, PageRequest pageRequest, long total) { + + this.dtoList = dtoList; + this.pageRequest = pageRequest; + this.totalCount = (int)total; + + int end = (int)(Math.ceil( pageRequest.getPage() / 10.0 )) * 10; + + int start = end - 9; + + int last = (int)(Math.ceil((totalCount/(double) pageRequest.getSize()))); + + end = end > last ? last: end; + + this.prev = start > 1; + this.next = totalCount > end * pageRequest.getSize(); + + this.pageNumList = IntStream.rangeClosed(start,end).boxed().collect(Collectors.toList()); + + if(prev) { + this.prevPage = start -1; + } + + if(next) { + this.nextPage = end + 1; + } + + this.totalPage = this.pageNumList.size(); + + this.current = pageRequest.getPage(); + + } +} + diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/PaymentApi.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/PaymentApi.java new file mode 100644 index 0000000..9043583 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/PaymentApi.java @@ -0,0 +1,49 @@ +package gcu.web.paymentservice.platform.adapter.in.web; + +import gcu.web.paymentservice.common.response.ApiResponse; +import gcu.web.paymentservice.platform.adapter.in.web.dto.request.CancelPaymentRequest; +import gcu.web.paymentservice.platform.adapter.in.web.dto.request.ConfirmPaymentRequest; +import gcu.web.paymentservice.platform.adapter.in.web.dto.response.PaymentResponse; +import gcu.web.paymentservice.platform.adapter.in.web.swagger.PaymentApiSpec; +import gcu.web.paymentservice.platform.application.in.PaymentUseCase; +import gcu.web.paymentservice.platform.domain.Payment; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +@Slf4j +@RestController +@RequestMapping("/api/v1/payments") +@RequiredArgsConstructor +public class PaymentApi implements PaymentApiSpec { + + private final PaymentUseCase paymentService; + + /// 리액트에서 결제한 내용 얻기 + @PostMapping("/confirm") + public ApiResponse createPayment(@RequestBody ConfirmPaymentRequest request) throws Exception { + + log.info("createPayment called with paymentKey: {}", request.paymentKey()); + + // 토스에게 결제 승인 요청 + Payment payment = paymentService.savePayment(request); + + + return ApiResponse.created(PaymentResponse.from(payment), "결제가 정상적으로 성공되었습니다."); + } + + /// 결제 취소 요청 + @DeleteMapping("/refund") + public ApiResponse cancelPayment(@RequestBody CancelPaymentRequest request) throws Exception { + + log.info("cancelPayment called with paymentKey: {}", request.paymentKey()); + + // 토스에게 결제 취소 요청 + paymentService.deletePayment(request); + + // 모임 서비스에게 취소 요청을 보낸다. + + return ApiResponse.ok(null, "취소 되었습니다."); + } + +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/dto/request/CancelPaymentRequest.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/dto/request/CancelPaymentRequest.java new file mode 100644 index 0000000..84d84a1 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/dto/request/CancelPaymentRequest.java @@ -0,0 +1,5 @@ +package gcu.web.paymentservice.platform.adapter.in.web.dto.request; + +public record CancelPaymentRequest( + String paymentKey, String cancelReason) { +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/dto/request/ConfirmPaymentRequest.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/dto/request/ConfirmPaymentRequest.java new file mode 100644 index 0000000..372c04b --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/dto/request/ConfirmPaymentRequest.java @@ -0,0 +1,6 @@ +package gcu.web.paymentservice.platform.adapter.in.web.dto.request; + +public record ConfirmPaymentRequest( + String paymentKey, String orderId, int amount +) { +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/dto/response/PaymentResponse.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/dto/response/PaymentResponse.java new file mode 100644 index 0000000..89c3138 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/dto/response/PaymentResponse.java @@ -0,0 +1,48 @@ +package gcu.web.paymentservice.platform.adapter.in.web.dto.response; + +import gcu.web.paymentservice.platform.domain.Payment; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Builder; + +@Builder +public record PaymentResponse( + @Schema(example = "1") + Long paymentId, + + @Schema(example = "tgen_20250520130928ZcAV7") + String paymentKey, + + @Schema(example = "ORDER-08f1fc98-dbc5-4859-b77f-bacfd97aaf2c") + String orderId, + + @Schema(example = "간편결제") + String method, + + @Schema(example = "VIP회원권 외 2건") + String orderName, + + @Schema(example = "DONE") + String status, + + @Schema(example = "10000") + int totalAmount, + + @Schema(example = "2025-05-20T13:09:28+09:00") + String requestedAt +) { + + public static PaymentResponse from(Payment payment) { + return PaymentResponse.builder() + .paymentId(payment.getId()) + .paymentKey(payment.getPaymentKey()) + .orderId(payment.getOrderId()) + .method(payment.getPaymentMethod()) + .orderName(payment.getOrderName()) + .status(payment.getStatus().toString()) + .totalAmount(payment.getAmount()) + .requestedAt(payment.getCreatedAt()) + .build(); + } + +} + diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/swagger/PaymentApiSpec.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/swagger/PaymentApiSpec.java new file mode 100644 index 0000000..58300a1 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/in/web/swagger/PaymentApiSpec.java @@ -0,0 +1,29 @@ +package gcu.web.paymentservice.platform.adapter.in.web.swagger; + +import gcu.web.paymentservice.common.response.ApiResponse; +import gcu.web.paymentservice.platform.adapter.in.web.dto.request.CancelPaymentRequest; +import gcu.web.paymentservice.platform.adapter.in.web.dto.request.ConfirmPaymentRequest; +import gcu.web.paymentservice.platform.adapter.in.web.dto.response.PaymentResponse; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.web.bind.annotation.RequestBody; + +@Tag(name = "결제 서버 API", description = "결제 승인 및 취소를 하는 API 입니다.") +public interface PaymentApiSpec { + + @Operation( + summary = "결제 요청 API", + description = "리액트의 코드를 바탕으로 결제 요청을 진행합니다." + ) + ApiResponse createPayment( + @RequestBody ConfirmPaymentRequest request + ) throws Exception; + + + @Operation( + summary = "결제 취소 API", + description = "결제취소 요청을 받으면 토스에게 결제 취소를 진행합니다." + ) + ApiResponse cancelPayment( + @RequestBody CancelPaymentRequest request) throws Exception; +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/PaymentPersistenceAdapter.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/PaymentPersistenceAdapter.java new file mode 100644 index 0000000..e61d2b8 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/PaymentPersistenceAdapter.java @@ -0,0 +1,51 @@ +package gcu.web.paymentservice.platform.adapter.out; + +import gcu.web.paymentservice.platform.adapter.out.jpa.payment.PaymentJpaEntity; +import gcu.web.paymentservice.platform.adapter.out.jpa.payment.PaymentJpaRepository; +import gcu.web.paymentservice.platform.application.out.PaymentPort; +import gcu.web.paymentservice.platform.domain.Payment; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Component; + +import java.util.Optional; + +@Component +@RequiredArgsConstructor +public class PaymentPersistenceAdapter implements PaymentPort { + + private final PaymentJpaRepository repository; + + @Override + public Payment savePayment(Payment payment) { + var entity = PaymentJpaEntity.from(payment); + + return repository.save(entity) + .toDomain(); + } + + // 결제 상세 조회 + @Override + public Optional loadPayment(Long id) { + + return repository.findById(id) + .map(PaymentJpaEntity::toDomain); + } + + @Override + public Optional loadPaymentByPaymentKey(String paymentKey) { + return repository.findByPaymentKey(paymentKey) + .map(PaymentJpaEntity::toDomain); + } + + @Override + public Page loadPaymentsByUserId(Long userId, Pageable pageable) { + return null; + } + + @Override + public void deletePayment(Long paymentId) { + repository.deleteById(paymentId); + } +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/external/order/OrderFeignPort.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/external/order/OrderFeignPort.java new file mode 100644 index 0000000..2872cdd --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/external/order/OrderFeignPort.java @@ -0,0 +1,24 @@ +package gcu.web.paymentservice.platform.adapter.out.external.order; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; + + +@FeignClient(name = "order-service", url = "http://54.66.149.225:8100") +public interface OrderFeignPort { + + /* + - 오더 서비스에게 메세지 전송을 하는 포트를 정의한다. + */ + + @PostMapping("/api/v1/orders/{orderId}/cancel") + String cancelOrder(@PathVariable("orderId") String orderId); + + @PutMapping("/api/v1/orders/{orderId}/submit") + String completeOrder(@PathVariable("orderId") Long orderId); + + +} + diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/jpa/payment/PaymentJpaEntity.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/jpa/payment/PaymentJpaEntity.java new file mode 100644 index 0000000..d152e7f --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/jpa/payment/PaymentJpaEntity.java @@ -0,0 +1,67 @@ +package gcu.web.paymentservice.platform.adapter.out.jpa.payment; + +import gcu.web.paymentservice.platform.domain.Payment; +import gcu.web.paymentservice.platform.domain.PaymentStatus; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@AllArgsConstructor +@NoArgsConstructor +@Builder +@Getter +public class PaymentJpaEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String orderId; + + private String orderName; + + private String paymentMethod; + + private String paymentKey; + + private int amount; + + private PaymentStatus status; + + private String createdAt; + + + /// From + public static PaymentJpaEntity from(Payment payment) { + return PaymentJpaEntity.builder() + .orderId(payment.getOrderId()) + .orderName(payment.getOrderName()) + .paymentMethod(payment.getPaymentMethod()) + .paymentKey(payment.getPaymentKey()) + .amount(payment.getAmount()) + .status(payment.getStatus()) + .createdAt(payment.getCreatedAt()) + .build(); + } + + /// ToDomain + public Payment toDomain() { + return Payment.builder() + .id(id) + .orderId(orderId) + .orderName(orderName) + .paymentMethod(paymentMethod) + .paymentKey(paymentKey) + .amount(amount) + .status(status) + .createdAt(createdAt) + .build(); + + } +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/jpa/payment/PaymentJpaRepository.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/jpa/payment/PaymentJpaRepository.java new file mode 100644 index 0000000..a387791 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/jpa/payment/PaymentJpaRepository.java @@ -0,0 +1,11 @@ +package gcu.web.paymentservice.platform.adapter.out.jpa.payment; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface PaymentJpaRepository extends JpaRepository { + + Optional findByPaymentKey(String paymentKey); + +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/pg/toss/TossPaymentAdapter.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/pg/toss/TossPaymentAdapter.java new file mode 100644 index 0000000..b2648b5 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/adapter/out/pg/toss/TossPaymentAdapter.java @@ -0,0 +1,78 @@ +package gcu.web.paymentservice.platform.adapter.out.pg.toss; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import gcu.web.paymentservice.platform.adapter.in.web.dto.request.ConfirmPaymentRequest; +import gcu.web.paymentservice.platform.application.out.pg.PaymentExternalPort; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +@Component +@RequiredArgsConstructor +public class TossPaymentAdapter implements PaymentExternalPort { + + private final ObjectMapper objectMapper; + + String widgetSecretKey = "test_gsk_docs_OaPz8L5KdmQXkzRz3y47BMw6"; + Base64.Encoder encoder = Base64.getEncoder(); + byte[] encodedBytes = encoder.encode((widgetSecretKey + ":").getBytes(StandardCharsets.UTF_8)); + String authorizations = "Basic " + new String(encodedBytes); + + + /// 결제 요청 + @Override + public HttpResponse requestConfirm(ConfirmPaymentRequest confirmPaymentRequest) throws IOException, InterruptedException { + String tossOrderId = confirmPaymentRequest.orderId(); + int tossAmount = confirmPaymentRequest.amount(); + String tossPaymentKey = confirmPaymentRequest.paymentKey(); + + // 승인 요청에 사용할 JSON 객체를 만듭니다. + JsonNode requestObj = objectMapper.createObjectNode() + .put("paymentKey", tossPaymentKey) + .put("orderId", tossOrderId) + .put("amount", tossAmount); + + // ObjectMapper를 사용하여 JSON 객체를 문자열로 변환 + String requestBody = objectMapper.writeValueAsString(requestObj); + + // 결제 승인 API를 호출 + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://api.tosspayments.com/v1/payments/confirm")) + .header("Authorization", authorizations) + .header("Content-Type", "application/json") + .method("POST", HttpRequest.BodyPublishers.ofString(requestBody)) + .build(); +// log.info("Authorization : " + authorizations); + return HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + + } + + /// 결제 취소 요청 + public HttpResponse requestPaymentCancel(String paymentKey, String cancelReason) throws IOException, InterruptedException { + System.out.println(paymentKey); + + // 승인 요청에 사용할 JSON 객체 생성 + JsonNode requestObj = objectMapper.createObjectNode() + .put("cancelReason", cancelReason); // paymentKey는 URL에 포함되어 있으므로 요청 바디에 포함할 필요 없음 + + String requestBody = objectMapper.writeValueAsString(requestObj); // JSON 문자열로 변환 + + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://api.tosspayments.com/v1/payments/" + paymentKey + "/cancel")) + .header("Authorization", authorizations) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(requestBody)) + .build(); + + return HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + } + +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/application/in/PaymentUseCase.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/application/in/PaymentUseCase.java new file mode 100644 index 0000000..6bc3abf --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/application/in/PaymentUseCase.java @@ -0,0 +1,33 @@ +package gcu.web.paymentservice.platform.application.in; + +import gcu.web.paymentservice.platform.adapter.in.web.dto.request.CancelPaymentRequest; +import gcu.web.paymentservice.platform.adapter.in.web.dto.request.ConfirmPaymentRequest; +import gcu.web.paymentservice.platform.domain.Payment; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.io.IOException; + +public interface PaymentUseCase { + + /* + 결제 진행 - 방 참가를 위한 결제 진행 - 토스페이 API를 활용하여 결제를 요청합니다. + 결제 완료 - 결제 완료 - 토스페이를 통해 결제를 완료합니다. + 결제 환불 - 미달로 인한 결제 환불 - 최소 주문금액이 모집되지않았기에 결제가 환불 됩니다. + 결제 환불 - 취소로 인한 결제 환불 - 방장이 취소하였기에 결제가 환불 됩니다. + 나의 결제 - 목록 확인 - 결제 목록에서 [결제 시간, 금액, 주문 가게, 시킨 음식] 의 정보를 확인할 수 있습니다. + */ + + /// 결제 생성 + // 리액트에게 결과 리턴 + Payment savePayment(ConfirmPaymentRequest confirmPaymentRequest) throws Exception; + + /// 결제 조회 + // 내 결제 목록 가져오기 + Page findMyPayments(Long memberId, Pageable pageable); + + /// 결제 취소 + void deletePayment(CancelPaymentRequest request) throws IOException, InterruptedException; + + +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/application/out/PaymentPort.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/application/out/PaymentPort.java new file mode 100644 index 0000000..95f2160 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/application/out/PaymentPort.java @@ -0,0 +1,25 @@ +package gcu.web.paymentservice.platform.application.out; + +import gcu.web.paymentservice.platform.domain.Payment; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.Optional; + +public interface PaymentPort { + + /// 결제 저장 + Payment savePayment(Payment payment); + + /// 결제 조회 + // 결제 상세 조회 + Optional loadPayment(Long id); + + Optional loadPaymentByPaymentKey(String paymentKey); + + // 유저 아이디 바탕 결제 조회 + Page loadPaymentsByUserId(Long userId, Pageable pageable); + + // 결제 삭제 + void deletePayment(Long paymentId); +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/application/out/pg/PaymentExternalPort.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/application/out/pg/PaymentExternalPort.java new file mode 100644 index 0000000..6ccacfb --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/application/out/pg/PaymentExternalPort.java @@ -0,0 +1,20 @@ +package gcu.web.paymentservice.platform.application.out.pg; + +import gcu.web.paymentservice.platform.adapter.in.web.dto.request.ConfirmPaymentRequest; + +import java.io.IOException; +import java.net.http.HttpResponse; + +public interface PaymentExternalPort { + + /* + PG 결제를 위한 포트 + */ + + /// 결제 검증 요청 + HttpResponse requestConfirm(ConfirmPaymentRequest request) throws IOException, InterruptedException; + + /// 결제 취소 요청 + HttpResponse requestPaymentCancel(String paymentKey, String cancelReason) throws IOException, InterruptedException; + +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/application/service/PaymentService.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/application/service/PaymentService.java new file mode 100644 index 0000000..29060c2 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/application/service/PaymentService.java @@ -0,0 +1,124 @@ +package gcu.web.paymentservice.platform.application.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import gcu.web.paymentservice.common.response.ErrorCode; +import gcu.web.paymentservice.platform.adapter.in.web.dto.request.CancelPaymentRequest; +import gcu.web.paymentservice.platform.adapter.in.web.dto.request.ConfirmPaymentRequest; +import gcu.web.paymentservice.platform.adapter.out.external.order.OrderFeignPort; +import gcu.web.paymentservice.platform.application.in.PaymentUseCase; +import gcu.web.paymentservice.platform.application.out.pg.PaymentExternalPort; +import gcu.web.paymentservice.platform.application.out.PaymentPort; +import gcu.web.paymentservice.platform.domain.Payment; +import gcu.web.paymentservice.platform.domain.PaymentStatus; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.net.http.HttpResponse; + +@Slf4j +@Service +@Transactional +public class PaymentService implements PaymentUseCase { + + private final ObjectMapper objectMapper; + + // DB에 저장 + private final PaymentPort paymentPort; + + // 외부 토스 의존 + private final PaymentExternalPort pgPort; + + // 주문 서비스 연동 + private final OrderFeignPort orderFeignPort; + + public PaymentService(ObjectMapper objectMapper, PaymentPort paymentPort, PaymentExternalPort pgPort, OrderFeignPort orderFeignPort) { + this.objectMapper = objectMapper; + this.paymentPort = paymentPort; + this.pgPort = pgPort; + this.orderFeignPort = orderFeignPort; + } + + + // 리액트에게 결과 리턴 + @Override + public Payment savePayment(ConfirmPaymentRequest confirmPaymentRequest) throws Exception { + + /// 토스에게 요청 + HttpResponse response = pgPort.requestConfirm(confirmPaymentRequest); + JsonNode responseBody = objectMapper.readTree(response.body()); + + log.info("response body: {}", responseBody.toString()); + + /// 응답값 DB에 저장 + if (response.statusCode() == 200) { + // 객체 저장 + Payment payment = createPayment(confirmPaymentRequest, responseBody); + + Payment saved = paymentPort.savePayment(payment); + + // 주문 정보 전달 + orderFeignPort.completeOrder(Long.valueOf(saved.getOrderId())); + + return saved; + + } else { + log.error("response status code: {}", response.statusCode()); + throw new IllegalStateException(ErrorCode.BAD_REQUEST.getMessage()); + } + } + + // 내 결제 목록 가져오기 + @Override + public Page findMyPayments(Long memberId, Pageable pageable) { + return null; + } + + @Override + public void deletePayment(CancelPaymentRequest request) throws IOException, InterruptedException { + + /// 존재 예외처리 + Payment payment = paymentPort.loadPaymentByPaymentKey(request.paymentKey()) + .orElseThrow(() -> new IllegalStateException(ErrorCode.NOT_FOUND_EXIST_PAYMENT.getMessage())); + + /// 토스에게 요청 + HttpResponse response = pgPort.requestPaymentCancel(request.paymentKey(), request.cancelReason()); + JsonNode responseBody = objectMapper.readTree(response.body()); + + log.info("response body: {}", responseBody.toString()); + + /// 응답값 DB에 저장 + if (response.statusCode() == 200) { + + // 객체 삭제 + paymentPort.deletePayment(payment.getId()); + + // 주문 취소 정보 전달 + orderFeignPort.cancelOrder(payment.getOrderId()); + + } else { + log.error("response status code: {}", response.statusCode()); + throw new IllegalStateException(ErrorCode.BAD_REQUEST.getMessage()); + } + + } + + /// 내부 메서드 + private static Payment createPayment(ConfirmPaymentRequest confirmPaymentRequest, JsonNode responseBody) { + return Payment.builder() + .paymentKey(responseBody.get("paymentKey").asText()) + .orderId(confirmPaymentRequest.orderId()) + .paymentMethod(responseBody.get("method").asText()) + .amount(responseBody.get("totalAmount").asInt()) + .orderName(responseBody.get("orderName").asText()) + .status(PaymentStatus.PAID) + .createdAt(responseBody.get("requestedAt").asText()) + .build(); + } + +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/domain/Payment.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/domain/Payment.java new file mode 100644 index 0000000..1977ba2 --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/domain/Payment.java @@ -0,0 +1,43 @@ +package gcu.web.paymentservice.platform.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@NoArgsConstructor +@AllArgsConstructor +@Builder +@Getter +public class Payment { + + private Long id; + + private String orderId; + + private String orderName; + + private String paymentMethod; + + private String paymentKey; + + private int amount; + + private PaymentStatus status; + + private String createdAt; + + + public static Payment of(String orderId, String orderName, String paymentMethod, String paymentKey, int amount, String createdAt, PaymentStatus status) { + return Payment.builder() + .orderId(orderId) + .orderName(orderName) + .paymentMethod(paymentMethod) + .paymentKey(paymentKey) + .amount(amount) + .status(status) + .createdAt(createdAt) + .build(); + } + +} diff --git a/payment-service/src/main/java/gcu/web/paymentservice/platform/domain/PaymentStatus.java b/payment-service/src/main/java/gcu/web/paymentservice/platform/domain/PaymentStatus.java new file mode 100644 index 0000000..9804c2a --- /dev/null +++ b/payment-service/src/main/java/gcu/web/paymentservice/platform/domain/PaymentStatus.java @@ -0,0 +1,9 @@ +package gcu.web.paymentservice.platform.domain; + +public enum PaymentStatus { + + PAID, + PENDING, + REFUNDED, + +} diff --git a/payment-service/src/main/resources/static/index.html b/payment-service/src/main/resources/static/index.html new file mode 100644 index 0000000..4775a69 --- /dev/null +++ b/payment-service/src/main/resources/static/index.html @@ -0,0 +1,56 @@ + + + + + + 고급 웹프로그래밍 결제 서버 + + + + +
+

고급 웹프로그래밍 결제 서버에 오신 것을 환영합니다.

+

이곳은 고급 웹프로그래밍 결제 서버입니다.

+ 스웨거로 이동하기 +
+ + + diff --git a/payment-service/src/test/java/gcu/web/paymentservice/PaymentServiceApplicationTests.java b/payment-service/src/test/java/gcu/web/paymentservice/PaymentServiceApplicationTests.java new file mode 100644 index 0000000..9bd2817 --- /dev/null +++ b/payment-service/src/test/java/gcu/web/paymentservice/PaymentServiceApplicationTests.java @@ -0,0 +1,12 @@ +package gcu.web.paymentservice; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +class PaymentServiceApplicationTests { + + @Test + void contextLoads() { + } + +}