package com.ruoyi.payment.interfaces.controller; import com.ruoyi.common.annotation.Anonymous; import com.ruoyi.payment.application.service.PaymentNotifyService; import com.ruoyi.payment.infrastructure.channel.alipay.AlipayUtil; import com.ruoyi.payment.infrastructure.channel.wechat.WxPayUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; /** * 渠道回调接口控制器 * * @author ruoyi */ @Slf4j @RestController @RequestMapping("/api/pay/notify") public class PaymentNotifyController { @Autowired private WxPayUtil wxPayUtil; @Autowired private AlipayUtil alipayUtil; @Autowired private PaymentNotifyService paymentNotifyService; /** * 微信支付回调 */ @Anonymous @PostMapping("/wechat") public String wechatNotify(HttpServletRequest request) { try { log.info("接收到微信支付回调"); // 1. 读取XML报文 String xmlData = readRequestBody(request); log.info("微信回调报文: {}", xmlData); // 2. 解析XML为Map Map params = wxPayUtil.xmlToMap(xmlData); // 3. 验证签名 if (!wxPayUtil.verifySign(params)) { log.error("微信回调签名验证失败"); return wxPayUtil.buildFailResponse("签名验证失败"); } log.info("微信回调签名验证通过"); // 4. 处理回调(更新订单状态、触发业务回调) paymentNotifyService.processWechatNotify(params, xmlData); // 5. 返回微信要求的XML应答 return wxPayUtil.buildSuccessResponse(); } catch (Exception e) { log.error("处理微信回调失败", e); return wxPayUtil.buildFailResponse("处理失败"); } } @Anonymous @GetMapping("/hello") public String hello() { return "hello"; } /** * 支付宝回调 */ @Anonymous @PostMapping("/alipay") public String alipayNotify(HttpServletRequest request) { try { log.info("接收到支付宝回调"); // 1. 获取所有参数 Map params = new HashMap<>(); Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = parameterNames.nextElement(); params.put(name, request.getParameter(name)); } log.info("支付宝回调参数: {}", params); // 2. 验证签名 if (!alipayUtil.verifySign(params)) { log.error("支付宝回调签名验证失败"); return "fail"; } log.info("支付宝回调签名验证通过"); // 3. 处理回调(更新订单状态、触发业务回调) paymentNotifyService.processAlipayNotify(params); // 4. 返回支付宝要求的应答 return "success"; } catch (Exception e) { log.error("处理支付宝回调失败", e); return "fail"; } } /** * 读取请求体 */ private String readRequestBody(HttpServletRequest request) throws Exception { StringBuilder sb = new StringBuilder(); try (BufferedReader reader = request.getReader()) { String line; while ((line = reader.readLine()) != null) { sb.append(line); } } return sb.toString(); } }