liulin
2025-07-03 fb2f11d7d502ceacbe7fbed176bea4ab0f152f69
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package com.lunhan.water.host.controller.notify;
 
import com.google.gson.Gson;
import com.lunhan.water.common.ConstantFactory;
import com.lunhan.water.common.ExecutedResult;
import com.lunhan.water.common.config.SysConfig;
import com.lunhan.water.common.enums.ELogger;
import com.lunhan.water.common.util.LocalDateTimeUtil;
import com.lunhan.water.common.util.LoggerUtil;
import com.lunhan.water.common.util.SerializeUtil;
import com.lunhan.water.common.util.StringUtil;
import com.lunhan.water.common.wechat.WechatPayV3Util;
import com.lunhan.water.entity.dto.pay.WeiXinPayNotifyDto;
import com.lunhan.water.entity.dto.pay.WeiXinRefundNotifyDto;
import com.lunhan.water.entity.enums.EPaymentChannel;
import com.lunhan.water.entity.response.pay.ResWeiXinPayNotify;
import com.lunhan.water.host.api.NonLogin;
import com.lunhan.water.service.PaymentServices;
import com.lunhan.water.service.ThirdNotifyService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
 
/**
 * 10010.异步通知相关接口
 *
 * @order 10010
 */
@NonLogin
@RestController
@RequestMapping("notify")
public class NotifyController {
    private Logger logger = LoggerUtil.get(ELogger.PAY_SERVICE);
    @Autowired
    private PaymentServices paymentService;
    @Autowired
    private ThirdNotifyService thirdNotifyService;
 
    /**
     * 微信支付结果通知
     *
     * @param reqBody 请求参数列表
     */
    @PostMapping(value = "pay/{channel}/{payWay}/{businessType}")
    public Object pay(@RequestBody Map<String, Object> reqBody, @PathVariable Integer channel, @PathVariable Integer payWay, @PathVariable Integer businessType) {
        String action = "pay";
 
        if (Objects.isNull(reqBody) || reqBody.isEmpty()) {
            logger.error(action + ", body cant't be null.");
            return "body cant't be null.";
        }
        String body = SerializeUtil.toJson(reqBody);
        logger.info(action + "-notify, channel: " + channel + "; payWay: " + payWay + "; body: " + body);
 
        EPaymentChannel findChannel = EPaymentChannel.getByValue(channel);
        if (Objects.isNull(findChannel)) {
            return "支付渠道不支持." + channel;
        }
        Object result;
        switch (findChannel) {
            case WE_CHAT:
                result = this.doWeiXinPayNotify(reqBody, body, businessType);
                break;
 
            case ALI_PAY:
                // TODO
                result = "支付宝支付待实现";
                break;
 
            default:
                result = "支付渠道不支持." + channel;
                break;
        }
        return result;
    }
 
    private ResWeiXinPayNotify doWeiXinPayNotify(Map<String, Object> reqBody, String body, Integer businessType) {
        String action = "doWeiXinPayNotify";
        ResWeiXinPayNotify result = new ResWeiXinPayNotify("FAILED", "unknown error.");
 
        ExecutedResult<Long> saveWinXinNotify = thirdNotifyService.saveWinXinPayNotify(EPaymentChannel.WE_CHAT, "PAY", body, businessType);
        if (saveWinXinNotify.isFailed()) {
            if (Objects.equals(saveWinXinNotify.getMsgCode(), ConstantFactory.MCODE_TOKENERROR)) {
                result.setCode("SUCCESS");
                result.setMessage("SUCCESS");
            } else {
                result.setMessage(saveWinXinNotify.getMsg());
            }
            return result;
        }
        Long notifyId = saveWinXinNotify.getData();
 
        // 处理微信支付结果通知
        try {
            if (reqBody.containsKey("event_type") && "TRANSACTION.SUCCESS".equals(reqBody.get("event_type").toString())) {
                this.doWeiXinPayResult(SerializeUtil.toJson(reqBody.get("resource")), notifyId);
            }
        } catch (Exception e) {
            logger.error(action, e);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setCode("SUCCESS");
        result.setMessage("SUCCESS");
        return result;
    }
 
    /**
     * 更新微信支付结果
     *
     * @param body     通知报文
     * @param notifyId 通知报文记录id
     */
    private void doWeiXinPayResult(String body, Long notifyId) throws Exception {
        String actionStr = "weiXinPay, ";
        Map<String, Object> data = new Gson().fromJson(body, Map.class);
        if (data.containsKey("algorithm") && "AEAD_AES_256_GCM".equals(data.get("algorithm").toString())) {
            String signParams = data.get("ciphertext").toString();
 
            String paramsStr = "";
 
            byte[] bufferKey = SysConfig.weiXinPay.getMerchantKey().getBytes(StandardCharsets.UTF_8);
            byte[] bufferAssociatedData = data.get("associated_data").toString().getBytes(StandardCharsets.UTF_8);
            byte[] bufferNonce = data.get("nonce").toString().getBytes(StandardCharsets.UTF_8);
            paramsStr = WechatPayV3Util.decryptToString(bufferAssociatedData, bufferNonce, signParams, bufferKey);
            logger.info(actionStr + "支付结果解密: " + paramsStr);
 
            WeiXinPayNotifyDto payInfo = SerializeUtil.toObject(paramsStr, WeiXinPayNotifyDto.class);
 
            // 更新通知报文业务编号
            thirdNotifyService.updateBusinessCode(notifyId, payInfo.getOut_trade_no());
 
            if ("SUCCESS".equalsIgnoreCase(payInfo.getTrade_state())) {
                LocalDateTime payTime = null;
                if (StringUtil.isNotNullOrEmpty(payInfo.getSuccess_time())) {
                    payTime = LocalDateTimeUtil.getDateTime(payInfo.getSuccess_time(), "yyyy-MM-d'T'HH:mm:ssXXX");
                }
                Integer paidAmount = payInfo.getAmount().getPayer_total();
 
                ExecutedResult<String> doPaidSuccess = paymentService.doPaidSuccess(
                        payInfo.getOut_trade_no(),
                        payInfo.getTransaction_id(),
                        new BigDecimal(paidAmount.toString()).divide(new BigDecimal(ConstantFactory.NUM100.toString())), // 微信支付金额乘了100
                        payTime
                );
                logger.info(actionStr + "支付成功更新支付结果: " + SerializeUtil.toJson(doPaidSuccess));
            } else if ("PAYERROR".equalsIgnoreCase(payInfo.getTrade_state())) {
                ExecutedResult<String> doPaidFailed = paymentService.doPaidFailed(
                        payInfo.getOut_trade_no(),
                        payInfo.getTransaction_id(),
                        payInfo.getTrade_state_desc()
                );
                logger.info(actionStr + "支付失败,更新支付结果: " + SerializeUtil.toJson(doPaidFailed));
            }
        } else {
            logger.error(actionStr + "报文加密方式未能识别!" + body);
        }
    }
 
 
    /**
     * 微信退款结果通知
     *
     * @param reqBody 请求参数列表
     */
    @PostMapping(value = "refund/{channel}/{payWay}/{businessType}")
    public Object refund(@RequestBody Map<String, Object> reqBody, @PathVariable Integer channel, @PathVariable Integer payWay, @PathVariable Integer businessType) {
        String action = "refund";
 
        if (Objects.isNull(reqBody)) {
            logger.error(action + ", body cant't be null.");
            return "请求正文不能为空.";
        }
        String body = SerializeUtil.toJson(reqBody);
        logger.info(action + "-notify, channel: " + channel + "; payWay: " + payWay + "; body: " + body);
 
        EPaymentChannel findChannel = EPaymentChannel.getByValue(channel);
        if (Objects.isNull(findChannel)) {
            return "支付渠道不支持." + channel;
        }
        Object result;
        switch (findChannel) {
            case WE_CHAT:
                result = this.doWeiXinRefundNotify(reqBody, body, businessType);
                break;
 
            case ALI_PAY:
                // TODO
                result = "支付宝支付待实现";
                break;
 
            default:
                result = "支付渠道不支持";
                break;
        }
        return result;
    }
 
    private Object doWeiXinRefundNotify(Map<String, Object> reqBody, String body, Integer businessType) {
        String action = "doWeiXinRefundNotify";
        ResWeiXinPayNotify result = new ResWeiXinPayNotify("FAILED", "unknown error.");
 
        ExecutedResult<Long> saveWinXinNotify = thirdNotifyService.saveWinXinPayNotify(EPaymentChannel.WE_CHAT, "REFUND", body, businessType);
        if (saveWinXinNotify.isFailed()) {
            if (Objects.equals(saveWinXinNotify.getMsgCode(), ConstantFactory.MCODE_TOKENERROR)) {
                result.setCode("SUCCESS");
                result.setMessage("SUCCESS");
            } else {
                result.setMessage(saveWinXinNotify.getMsg());
            }
            return result;
        }
        Long notifyId = saveWinXinNotify.getData();
 
        // 处理微信支付结果通知
        try {
            if (reqBody.containsKey("event_type") && "REFUND.SUCCESS".equals(reqBody.get("event_type").toString())) {
                this.doWeiXinRefundResult(SerializeUtil.toJson(reqBody.get("resource")), notifyId);
            }
        } catch (Exception e) {
            logger.error(action, e);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setCode("SUCCESS");
        result.setMessage("SUCCESS");
        return result;
    }
 
    /**
     * 更新微信退款结果
     *
     * @param body     通知报文
     * @param notifyId 通知报文记录id
     */
    private void doWeiXinRefundResult(String body, Long notifyId) throws Exception {
        String actionStr = "weiXinRefund, ";
        Map<String, Object> data = new Gson().fromJson(body, Map.class);
        if (data.containsKey("algorithm") && "AEAD_AES_256_GCM".equals(data.get("algorithm").toString())) {
            String signParams = data.get("ciphertext").toString();
 
 
            String paramsStr = "";
 
            byte[] bufferKey = SysConfig.weiXinPay.getMerchantKey().getBytes(StandardCharsets.UTF_8);
            byte[] bufferAssociatedData = data.get("associated_data").toString().getBytes(StandardCharsets.UTF_8);
            byte[] bufferNonce = data.get("nonce").toString().getBytes(StandardCharsets.UTF_8);
            paramsStr = WechatPayV3Util.decryptToString(bufferAssociatedData, bufferNonce, signParams, bufferKey);
            logger.info(actionStr + "退款结果解密: " + paramsStr);
 
            WeiXinRefundNotifyDto refundInfo = SerializeUtil.toObject(paramsStr, WeiXinRefundNotifyDto.class);
 
            // 更新通知报文业务编号
            thirdNotifyService.updateBusinessCode(notifyId, refundInfo.getOut_trade_no());
 
            if ("SUCCESS".equalsIgnoreCase(refundInfo.getRefund_status())) {
                LocalDateTime refundTime = null;
                if (StringUtil.isNotNullOrEmpty(refundInfo.getSuccess_time())) {
                    refundTime = LocalDateTimeUtil.getDateTime(refundInfo.getSuccess_time(), "yyyy-MM-d'T'HH:mm:ssXXX");
                }
                Integer paidAmount = refundInfo.getAmount().getPayer_refund();
 
                ExecutedResult<String> doRefundSuccess = paymentService.doRefundSuccess(
                        refundInfo.getOut_trade_no(),
                        refundInfo.getTransaction_id(),
                        new BigDecimal(paidAmount.toString()).divide(new BigDecimal(ConstantFactory.NUM100.toString())), // 微信支付金额乘了100
                        refundTime
                );
                logger.info(actionStr + "退款成功更新支付结果: " + SerializeUtil.toJson(doRefundSuccess));
            } else {
                String errorMsg = "refund_status: ABNORMAL. 退款异常,退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败,可前往【商户平台—>交易中心】,手动处理此笔退款";
                if ("CLOSED".equalsIgnoreCase(refundInfo.getRefund_status())) {
                    errorMsg = "refund_status: CLOSED. 退款关闭";
                }
                ExecutedResult<String> doRefundFailed = paymentService.doRefundFailed(
                        refundInfo.getOut_trade_no(),
                        refundInfo.getTransaction_id(),
                        errorMsg
                );
                logger.info(actionStr + "退款失败,更新退款结果: " + SerializeUtil.toJson(doRefundFailed));
            }
        } else {
            logger.error(actionStr + "报文加密方式未能识别!" + body);
        }
    }
}