-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPaymentController.java
More file actions
261 lines (218 loc) ยท 9.72 KB
/
PaymentController.java
File metadata and controls
261 lines (218 loc) ยท 9.72 KB
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
package com.kt.controller.payment;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import com.kt.common.exception.CustomException;
import com.kt.common.exception.ErrorCode;
import com.kt.common.request.Paging;
import com.kt.common.response.ApiResult;
import com.kt.common.support.SwaggerAssistance;
import com.kt.domain.order.Order;
import com.kt.domain.order.OrderStatus;
import com.kt.dto.payment.PaymentCreateRequest;
import com.kt.dto.payment.PaymentDetailResponse;
import com.kt.dto.payment.PaymentListResponse;
import com.kt.dto.payment.PaymentOrderInfoResponse;
import com.kt.dto.payment.PaymentTossCancelRequest;
import com.kt.dto.payment.PaymentTossCancelResponse;
import com.kt.dto.payment.PaymentTossConfirmRequest;
import com.kt.properties.TossPaymentsProperties;
import com.kt.security.CustomUserDetails;
import com.kt.service.order.OrderService;
import com.kt.service.payment.PaymentFacade;
import com.kt.service.payment.PaymentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
@Tag(name = "Payment", description = "Payment ์ฌ์ฉ์์ฉ API")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/payments")
public class PaymentController extends SwaggerAssistance {
private final PaymentService paymentService;
private final OrderService orderService;
private final PaymentFacade paymentFacade;
private final TossPaymentsProperties tossPaymentsProperties;
private final RestTemplate restTemplate = new RestTemplate();
@GetMapping
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "๊ฒฐ์ ๊ธฐ๋ก ๋ชฉ๋ก ์กฐํ")
public ApiResult<Page<PaymentListResponse>> getMyAllPayment(
@AuthenticationPrincipal CustomUserDetails currentUser,
Paging paging
) {
return ApiResult.ok(paymentService.getMyAllPayment(currentUser.getId(), paging.toPageable()));
}
@GetMapping("/{paymentId}")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "๊ฒฐ์ ๊ธฐ๋ก ์์ธ ์กฐํ")
public ApiResult<PaymentDetailResponse> getPayment(
@PathVariable("paymentId") Long paymentId,
@AuthenticationPrincipal CustomUserDetails currentUser
) {
return ApiResult.ok(paymentService.getPayment(currentUser.getId(), paymentId));
}
/*๊ฒฐ์ ๊ธฐ๋ก ๋ฑ๋ก -> toss ๊ฒฐ์ ์ดํ ์ฑ๊ณต ์ ๋ฑ๋ก ๋ณ๊ฒฝ*/
/*@PostMapping("")
@Operation(summary = "๊ฒฐ์ ๊ธฐ๋ก ๋ฑ๋ก")
public ApiResult<Void> create(@Valid @RequestBody PaymentCreateRequest request, @AuthenticationPrincipal CustomUserDetails currentUser) {
paymentService.create(request, currentUser.getId());
return ApiResult.ok();
}*/
@PostMapping("/confirm")
@Operation(summary = "Toss ๊ฒฐ์ ์น์ธ ์์ฒญ")
public ResponseEntity<?> confirmPayment(@RequestBody PaymentTossConfirmRequest request,
@AuthenticationPrincipal CustomUserDetails currentUser
) {
String orderId = request.orderId().split("-")[0];
Long orderIdLong = Long.parseLong(orderId);
String paymentKey = request.paymentKey();
try {
String url = tossPaymentsProperties.getApiUrl() + "/confirm";
String auth = tossPaymentsProperties.getSecretKey() + ":";
String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
var order = orderService.getOrderDetail(currentUser.getId(), orderIdLong);
if (order.orderStatus() != OrderStatus.PENDING_PAYMENT) {
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(Map.of(
"code", ErrorCode.ALREADY_PAID_ORDER.getStatus(),
"message", ErrorCode.ALREADY_PAID_ORDER.getMessage()
));
}
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + encodedAuth);
headers.setContentType(MediaType.APPLICATION_JSON);
System.out.println(request.toString());
Map<String, String> body = Map.of(
"paymentKey", request.paymentKey(),
"orderId", request.orderId(),
"amount", request.amount().toString()
);
HttpEntity<Map<String, String>> entity = new HttpEntity<>(body, headers);
ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);
if (response.getStatusCode() == HttpStatus.OK) {
Map<String, Object> tossPayment = response.getBody();
try {
Long paymentId = paymentFacade.completePayment(tossPayment, currentUser.getId(), orderIdLong);
Map<String, Object> responseBody = new HashMap<>(tossPayment);
responseBody.put("paymentId", paymentId);
return ResponseEntity.ok(responseBody);
} catch (Exception e) {
cancelTossPayment(paymentKey, "์์คํ
์ค๋ฅ๋ก ์ธํ ์๋ ์ทจ์");
orderService.rollback(orderIdLong);
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of(
"code", ErrorCode.PAYMENT_CANCEL_FAILED,
"message", "๊ฒฐ์ ๋ ์น์ธ๋์์ผ๋ ์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ฌ ์๋ ์ทจ์"
));
}
}
return ResponseEntity.ok(response.getBody());
} catch (HttpClientErrorException e) {
// Toss API์์ ๋ฐํํ ์๋ฌ ์๋ต์ ๊ทธ๋๋ก ์ ๋ฌ
return ResponseEntity
.status(e.getStatusCode())
.body(e.getResponseBodyAsString());
} catch (Exception e) {
e.printStackTrace();
orderService.rollback(orderIdLong);
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of(
"code", "INTERNAL_SERVER_ERROR",
"message", "๊ฒฐ์ ์น์ธ ์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: " + e.getMessage()
));
}
}
@GetMapping("/order/{orderId}")
@Operation(summary = "์ฃผ๋ฌธ ID๋ก ๊ฒฐ์ ์ ๋ณด ์กฐํ")
public ApiResult<PaymentDetailResponse> getPaymentByOrderId(
@PathVariable Long orderId,
@AuthenticationPrincipal CustomUserDetails currentUser
) {
return ApiResult.ok(paymentService.getPaymentByOrderId(currentUser.getId(), orderId));
}
@PostMapping("/{paymentId}/cancel")
@Operation(summary = "๊ฒฐ์ ์ทจ์")
public ResponseEntity<?> cancelPayment(
@PathVariable Long paymentId,
@RequestBody PaymentTossCancelRequest request,
@AuthenticationPrincipal CustomUserDetails currentUser) {
try {
String paymentKey = paymentService.getPaymentKey(paymentId, currentUser.getId());
String url = tossPaymentsProperties.getApiUrl() + "/" + paymentKey + "/cancel";
String auth = tossPaymentsProperties.getSecretKey() + ":";
String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + encodedAuth);
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> body = new HashMap<>();
body.put("cancelReason", request.cancelReason());
if (request.cancelAmount() != null) {
body.put("cancelAmount", request.cancelAmount());
}
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
ResponseEntity<Map> tossResponse = restTemplate.postForEntity(url, entity, Map.class);
if (tossResponse.getStatusCode() == HttpStatus.OK) {
PaymentTossCancelResponse response = paymentService.cancelPayment(request, currentUser.getId(), paymentId);
return ResponseEntity.ok(ApiResult.ok(response));
}
throw new CustomException(ErrorCode.PAYMENT_CANCEL_FAILED);
} catch (HttpClientErrorException e) {
// Toss API์์ ๋ฐํํ ์๋ฌ ์๋ต์ ๊ทธ๋๋ก ์ ๋ฌ
return ResponseEntity
.status(e.getStatusCode())
.body(e.getResponseBodyAsString());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of(
"code", "INTERNAL_SERVER_ERROR",
"message", "๊ฒฐ์ ์น์ธ ์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: " + e.getMessage()
));
}
}
@GetMapping("/order/{orderId}/info")
@Operation(summary = "์ฃผ๋ฌธ ๋ฒํธ๋ก ๊ฒฐ์ ์ ๋ณด ์กฐํ")
public ApiResult<PaymentOrderInfoResponse> getPaymentDetail(@PathVariable Long orderId,
@AuthenticationPrincipal CustomUserDetails currentUser) {
return ApiResult.ok(paymentService.getPaymentDetail(currentUser.getId(), orderId));
}
@GetMapping("/client-key")
@Operation(summary = "Toss ํด๋ผ์ด์ธํธ ํค ์กฐํ")
public ApiResult<Map<String, String>> getClientKey() {
return ApiResult.ok(Map.of("clientKey", tossPaymentsProperties.getClientKey()));
}
private void cancelTossPayment(String paymentKey, String cancelReason) {
String url = tossPaymentsProperties.getApiUrl() + "/" + paymentKey + "/cancel";
String auth = tossPaymentsProperties.getSecretKey() + ":";
String encodedAuth = java.util.Base64.getEncoder()
.encodeToString(auth.getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + encodedAuth);
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> body = Map.of("cancelReason", cancelReason);
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
restTemplate.postForEntity(url, entity, Map.class);
}
}