PayServiceClient.java
8.95 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
package com.infoloop.tianting.service.client;
import cn.hutool.core.convert.Convert;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.infoloop.tianting.clientcustomerorderservice.ClientCustomerOrderModification;
import com.infoloop.tianting.clientcustomerorderservice.PayStatusEnum;
import com.infoloop.tianting.config.BusinessConfig;
import com.infoloop.tianting.model.dto.PayDTO.PayInformRequestDto;
import com.infoloop.tianting.model.dto.PayDTO.PayResponseDto;
import com.infoloop.tianting.model.dto.PayDTO.ThirdPartyPayInformRequestDto;
import com.infoloop.tianting.model.dto.PaymentCallbackDTO;
import com.infoloop.tianting.model.dto.PaymentCallbackResult;
import com.infoloop.tianting.utils.DateUtil;
import com.infoloop.tianting.utils.EncryptionUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDateTime;
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PayServiceClient {
private final RestTemplate restTemplate;
private final BusinessConfig businessConfig;
private final OrderServiceRpcClient orderServiceRpcClient;
private final XmlMapper xmlMapper = new XmlMapper();
@Value("${payment.client-id:Order0001}")
private String clientId;
public PayResponseDto payInform(PayInformRequestDto payRequestDto) {
String url = businessConfig.getPayUrl();
String requestDate = DateUtil.formatDate(LocalDateTime.now(), DateUtil.YMDHMS);
ThirdPartyPayInformRequestDto jsonData = buildRequestData(payRequestDto, requestDate);
String jsonDataString;
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
jsonDataString = objectMapper.writeValueAsString(jsonData);
} catch (JsonProcessingException e) {
log.error("Failed to serialize request data", e);
throw new IllegalArgumentException("支付信息获取失败: JSON 解析错误");
}
HttpEntity<String> requestEntity = new HttpEntity<>(jsonDataString, createHeaders());
log.info("payInform request: {}", jsonDataString);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
return processResponse(responseEntity);
}
private ThirdPartyPayInformRequestDto buildRequestData(PayInformRequestDto payRequestDto, String requestDate) {
ThirdPartyPayInformRequestDto jsonData = new ThirdPartyPayInformRequestDto();
jsonData.setClientId(clientId);
jsonData.setTradeId(payRequestDto.getOrderId());
jsonData.setRequestDate(requestDate);
jsonData.setRequestSource("OFWXApplet");
jsonData.setPayerOpenId(payRequestDto.getOpenId());
jsonData.setHospitalCode(payRequestDto.getHospitalCode());
jsonData.setPID(payRequestDto.getPhone());
jsonData.setRemark("");
jsonData.setTransAmount(payRequestDto.getPrice());
jsonData.setTradeDesc("");
jsonData.setSign(EncryptionUtil.sha1Encryption(clientId + payRequestDto.getOrderId() + requestDate + clientId));
return jsonData;
}
private HttpHeaders createHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
private PayResponseDto processResponse(ResponseEntity<String> responseEntity) {
if (!responseEntity.getStatusCode().is2xxSuccessful() || responseEntity.getBody() == null) {
log.error("payInform failed with response: {}", responseEntity.getBody());
throw new IllegalArgumentException("支付信息获取失败");
}
try {
log.info("processResponse response: {}", responseEntity.getBody());
return xmlMapper.readValue(responseEntity.getBody(), PayResponseDto.class);
} catch (Exception e) {
log.error("Failed to parse XML response", e);
throw new RuntimeException("支付信息结果解析失败", e);
}
}
public boolean callback(PaymentCallbackDTO paymentCallbackDTO) {
log.info("callback request received: {}", paymentCallbackDTO);
try {
final var paymentCallbackResult = xmlMapper.readValue(paymentCallbackDTO.getPayResult(), PaymentCallbackResult.class);
log.info("Parsed paymentCallbackResult: {}", paymentCallbackResult);
final var orderId = Integer.parseInt(paymentCallbackResult.getTradeId());
final var orderById = orderServiceRpcClient.getOrderById(orderId);
if (orderById == null) {
log.error("Order not found, orderId: {}", orderId);
return false;
}
if (orderById.getPayStatus() != PayStatusEnum.IN_PROGRESS) {
log.info("Order {} already processed, skipping.", orderId);
return true;
}
long payTime;
try {
payTime = DateUtil.parseDate(paymentCallbackResult.getTransDate(), "yyyyMMddHHmmss").getTime();
} catch (ParseException e) {
log.error("Failed to parse TransDate: {}", paymentCallbackResult.getTransDate(), e);
throw new IllegalArgumentException("支付时间格式错误: " + paymentCallbackResult.getTransDate(), e);
}
BigDecimal realAmount;
try {
realAmount = Convert.toBigDecimal(paymentCallbackResult.getRealAmount());
if (realAmount == null) {
throw new NumberFormatException("RealAmount is null or empty");
}
} catch (NumberFormatException e) {
log.error("Invalid RealAmount value: {}", paymentCallbackResult.getRealAmount(), e);
throw new IllegalArgumentException("支付金额错误: " + paymentCallbackResult.getRealAmount(), e);
}
final var build = ClientCustomerOrderModification.newBuilder()
.setId(orderId)
.setShouldUpdatePayTime(true).setPayTime(payTime)
.setShouldUpdatePayPrice(true).setPayPrice(realAmount.multiply(new BigDecimal("100")).intValue())
.setShouldUpdatePayStatus(true).setPayStatus(PayStatusEnum.SUCCEED)
.setShouldUpdateTransactionId(true).setTransactionId(paymentCallbackResult.getTransSN())
.build();
final var updateResponse = orderServiceRpcClient.updateClientCustomerOrderPaymentResult(orderById, build);
log.info("callback updateClientCustomerOrder result: {}", updateResponse.getIsUpdated());
return updateResponse.getIsUpdated();
} catch (JsonProcessingException e) {
log.error("Failed to parse XML response, raw XML: {}", paymentCallbackDTO.getPayResult(), e);
throw new RuntimeException("支付通知结果解析失败", e);
} catch (Exception e) {
log.error("Unexpected error in callback, request: {}", paymentCallbackDTO, e);
throw new RuntimeException("支付通知处理失败", e);
}
}
public boolean waiting(Integer orderId) {
final var orderById = orderServiceRpcClient.getOrderById(orderId);
if (orderById == null) {
log.error("waiting Order not found, orderId: {}", orderId);
return false;
}
if (orderById.getPayStatus() != PayStatusEnum.TO_PAY) {
log.info("waiting Order {} already processed, skipping.", orderId);
return false;
}
final var build = ClientCustomerOrderModification.newBuilder()
.setId(orderId)
.setShouldUpdatePayStatus(true).setPayStatus(PayStatusEnum.IN_PROGRESS)
.build();
final var updateResponse = orderServiceRpcClient.updateClientCustomerOrderPaymentResult(orderById, build);
log.info("waiting updateClientCustomerOrder result: {}", updateResponse.getIsUpdated());
return updateResponse.getIsUpdated();
}
}