rk
4 天以前 e39dda2f25df9680e66c9e0dd3a606149e21bcc5
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
package com.doumee.api.web;
 
import com.doumee.config.wx.WxMiniConfig;
import com.doumee.config.wx.WxPayV3Service;
import com.doumee.core.constants.Constants;
import com.doumee.core.utils.ID;
import com.doumee.core.utils.aliyun.AliSmsService;
import com.doumee.dao.business.MemberMapper;
import com.doumee.dao.business.OrdersRefundMapper;
import com.doumee.dao.business.OrdersMapper;
import com.doumee.dao.business.SmsrecordMapper;
import com.doumee.dao.business.model.Member;
import com.doumee.dao.business.model.Notice;
import com.doumee.dao.business.model.Orders;
import com.doumee.dao.business.model.OrdersRefund;
import com.doumee.dao.business.model.Smsrecord;
import com.alibaba.fastjson.JSONObject;
import com.doumee.service.business.NoticeService;
import com.doumee.service.business.OrdersService;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.refund.model.RefundNotification;
import com.wechat.pay.java.service.refund.model.Status;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * 支付回调
 *
 * @Author : Rk
 * @create 2023/3/24 16:57
 */
@Slf4j
@RestController
@CrossOrigin
public class PaymentCallback extends ApiController {
 
    @Autowired
    private OrdersService ordersService;
 
    @Autowired
    private WxPayV3Service wxPayV3Service;
 
    @Autowired
    private OrdersRefundMapper ordersRefundMapper;
 
    @Autowired
    private OrdersMapper ordersMapper;
 
    @Autowired
    private NoticeService noticeService;
 
    @Autowired
    private SmsrecordMapper smsrecordMapper;
 
    @Autowired
    private MemberMapper memberMapper;
 
 
    // ==================== V2 回调 ====================
 
    @PostMapping("/web/api/wxPayNotify")
    public String wxPay_notify(@RequestBody String xmlResult) {
        String wxId = ID.nextGUID();
        log.info("V2支付回调信息(" + wxId + ") => " + xmlResult);
        if (StringUtils.isEmpty(xmlResult)) {
            return null;
        }
        try {
            WxPayOrderNotifyResult result = WxMiniConfig.wxPayService.parseOrderNotifyResult(xmlResult);
            String outTradeNo = result.getOutTradeNo();
            String paymentNo = result.getTransactionId();
 
            if (Constants.SUCCESS.equals(result.getReturnCode())) {
                switch (result.getAttach()) {
                    case "storageOrder": {
                        ordersService.handleStorageOrderPayNotify(outTradeNo, paymentNo);
                        break;
                    }
                    case "shopDeposit": {
                        ordersService.handleShopDepositPayNotify(outTradeNo, paymentNo);
                        break;
                    }
                    case "overdueFee": {
                        ordersService.handleOverdueFeePayNotify(outTradeNo, paymentNo);
                        break;
                    }
                }
                return WxPayNotifyResponse.success("处理成功!");
            }
            return WxPayNotifyResponse.fail(result.getReturnMsg());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("V2微信回调结果异常,异常原因{}", e.getLocalizedMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }
 
    // ==================== V3 回调 ====================
 
    /**
     * V3支付回调
     */
    @PostMapping("/web/api/wxPayV3Notify")
    public Map<String, String> wxPayV3Notify(
            @RequestHeader("Wechatpay-Serial") String serialNumber,
            @RequestHeader("Wechatpay-Timestamp") String timestamp,
            @RequestHeader("Wechatpay-Nonce") String nonce,
            @RequestHeader("Wechatpay-Signature") String signature,
            @RequestBody String body) {
        String wxId = ID.nextGUID();
        log.info("V3支付回调信息({}) => {}", wxId, body);
        try {
            Transaction transaction = wxPayV3Service.parsePayNotify(
                    serialNumber, timestamp, nonce, signature, body);
 
            String outTradeNo = transaction.getOutTradeNo();
            String paymentNo = transaction.getTransactionId();
 
            if (Transaction.TradeStateEnum.SUCCESS.equals(transaction.getTradeState())) {
                String attach = transaction.getAttach();
                if (StringUtils.isNotBlank(attach)) {
                    switch (attach) {
                        case "storageOrder":
                            ordersService.handleStorageOrderPayNotify(outTradeNo, paymentNo);
                            break;
                        case "shopDeposit":
                            ordersService.handleShopDepositPayNotify(outTradeNo, paymentNo);
                            break;
                        case "overdueFee":
                            ordersService.handleOverdueFeePayNotify(outTradeNo, paymentNo);
                            break;
                    }
                }
            }
 
            Map<String, String> response = new HashMap<>();
            response.put("code", "SUCCESS");
            response.put("message", "处理成功");
            return response;
        } catch (Exception e) {
            log.error("V3支付回调异常,异常原因{}", e.getLocalizedMessage());
            Map<String, String> response = new HashMap<>();
            response.put("code", "FAIL");
            response.put("message", e.getMessage());
            return response;
        }
    }
 
    /**
     * V3退款回调
     */
    @PostMapping("/web/api/wxRefundV3Notify")
    public Map<String, String> wxRefundV3Notify(
            @RequestHeader("Wechatpay-Serial") String serialNumber,
            @RequestHeader("Wechatpay-Timestamp") String timestamp,
            @RequestHeader("Wechatpay-Nonce") String nonce,
            @RequestHeader("Wechatpay-Signature") String signature,
            @RequestBody String body) {
        String wxId = ID.nextGUID();
        log.info("V3退款回调信息({}) => {}", wxId, body);
        try {
            RefundNotification refundNotification = wxPayV3Service.parseRefundNotify(
                    serialNumber, timestamp, nonce, signature, body);
 
            log.info("V3退款回调结果, outTradeNo={}, outRefundNo={}, refundStatus={}",
                    refundNotification.getOutTradeNo(),
                    refundNotification.getOutRefundNo(),
                    refundNotification.getRefundStatus());
 
            // 根据退款单号更新退款记录状态
            String outRefundNo = refundNotification.getOutRefundNo();
            OrdersRefund refundRecord = ordersRefundMapper.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<OrdersRefund>().lambda()
                            .eq(OrdersRefund::getRefundCode, outRefundNo)
                            .eq(OrdersRefund::getDeleted, Constants.ZERO)
                            .last("limit 1"));
            if (refundRecord != null) {
                Status refundStatus = refundNotification.getRefundStatus();
 
                // 幂等判断:已成功/已失败的不重复处理
                if (!Constants.equalsInteger(refundRecord.getStatus(), Constants.ZERO)) {
                    log.info("退款记录已处理, refundRecordId={}, status={}, 跳过", refundRecord.getId(), refundRecord.getStatus());
                } else {
                    if (Status.SUCCESS.equals(refundStatus)) {
                        refundRecord.setStatus(Constants.ONE); // 退款成功
                        refundRecord.setRefundTime(new java.util.Date());
                    } else if (Status.CLOSED.equals(refundStatus) || Status.ABNORMAL.equals(refundStatus)) {
                        refundRecord.setStatus(Constants.TWO); // 退款失败
                        refundRecord.setRemark("微信退款失败: " + refundStatus.name());
                    }
                    // PROCESSING 状态无变化,不更新
                    ordersRefundMapper.updateById(refundRecord);
                    log.info("退款记录状态已更新, refundRecordId={}, status={}", refundRecord.getId(), refundRecord.getStatus());
 
                    // 退款成功 → 通知会员
                    if (Status.SUCCESS.equals(refundStatus) && refundRecord.getOrderId() != null) {
                        Orders refundOrder = ordersMapper.selectById(refundRecord.getOrderId());
                        if (refundOrder != null) {
                            Notice notice = new Notice();
                            notice.setUserType(0);
                            notice.setUserId(refundOrder.getMemberId());
                            notice.setTitle(Constants.MemberOrderNotify.REFUNDED.getTitle());
                            notice.setContent(Constants.MemberOrderNotify.REFUNDED.format(
                                    "orderNo", refundOrder.getCode(),
                                    "amount", String.valueOf(Constants.getFormatMoney(refundOrder.getRefundAmount() != null ? refundOrder.getRefundAmount() : 0L))));
                            notice.setObjId(refundOrder.getId());
                            notice.setObjType(0);
                            notice.setStatus(0);
                            notice.setIsdeleted(Constants.ZERO);
                            notice.setCreateDate(new java.util.Date());
                            noticeService.create(notice);
 
                            // 短信通知会员:退款已完成
                            Member refundMember = memberMapper.selectById(refundOrder.getMemberId());
                            if (refundMember != null && StringUtils.isNotBlank(refundMember.getTelephone())) {
                                String smsContent = Constants.SmsNotify.MEMBER_REFUNDED.format(
                                        "orderNo", refundOrder.getCode(),
                                        "money", String.valueOf(Constants.getFormatMoney(
                                                refundOrder.getRefundAmount() != null ? refundOrder.getRefundAmount() : 0L)));
                                try {
                                    JSONObject templateParam = new JSONObject();
                                    templateParam.put("orderNo", refundOrder.getCode());
                                    templateParam.put("money", String.valueOf(Constants.getFormatMoney(
                                            refundOrder.getRefundAmount() != null ? refundOrder.getRefundAmount() : 0L)));
                                    boolean smsResult = AliSmsService.sendSms(refundMember.getTelephone(),
                                            Constants.SmsNotify.MEMBER_REFUNDED.getTemplateCode(),
                                            templateParam.toJSONString());
                                    if (smsResult) {
                                        log.info("退款短信发送成功: phone={}", refundMember.getTelephone());
                                    } else {
                                        log.warn("退款短信发送失败: phone={}", refundMember.getTelephone());
                                    }
                                    // 存储短信记录
                                    Smsrecord smsRecord = new Smsrecord();
                                    smsRecord.setPhone(refundMember.getTelephone());
                                    smsRecord.setContent(smsContent);
                                    smsRecord.setType(Constants.ONE);
                                    smsRecord.setStatus(smsResult ? Constants.ONE : Constants.ZERO);
                                    smsRecord.setCreateTime(new java.util.Date());
                                    smsRecord.setDeleted(Constants.ZERO);
                                    smsrecordMapper.insert(smsRecord);
                                } catch (Exception smsEx) {
                                    log.error("退款短信发送异常: {}", smsEx.getMessage());
                                    try {
                                        Smsrecord smsRecord = new Smsrecord();
                                        smsRecord.setPhone(refundMember.getTelephone());
                                        smsRecord.setContent(smsContent);
                                        smsRecord.setType(Constants.ONE);
                                        smsRecord.setStatus(Constants.ZERO);
                                        smsRecord.setCreateTime(new java.util.Date());
                                        smsRecord.setDeleted(Constants.ZERO);
                                        smsrecordMapper.insert(smsRecord);
                                    } catch (Exception ignored) {}
                                }
                            }
                        }
                    }
                }
            }
 
            Map<String, String> response = new HashMap<>();
            response.put("code", "SUCCESS");
            response.put("message", "处理成功");
            return response;
        } catch (Exception e) {
            log.error("V3退款回调异常,异常原因{}", e.getLocalizedMessage());
            Map<String, String> response = new HashMap<>();
            response.put("code", "FAIL");
            response.put("message", e.getMessage());
            return response;
        }
    }
 
}