订单退款逻辑新增

This commit is contained in:
2025-02-24 10:21:57 +08:00
parent b9f7036f06
commit 59677f1c5f
9 changed files with 156 additions and 51 deletions
@@ -3,6 +3,7 @@ package com.central.order.config;
import com.wechat.pay.java.core.Config; import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig; import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig; import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension; import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.refund.RefundService; import com.wechat.pay.java.service.refund.RefundService;
import lombok.Getter; import lombok.Getter;
@@ -44,28 +45,32 @@ public class TencentPayConfiguration {
*/ */
@Bean @Bean
public JsapiServiceExtension initialJsapiServiceExtension() { public JsapiServiceExtension initialJsapiServiceExtension() {
Config config =
new RSAAutoCertificateConfig.Builder()
.merchantId(merchantId)
.privateKeyFromPath(privateKeyPath)
.merchantSerialNumber(merchantSerialNumber)
.apiV3Key(apiV3Key)
.build();
// 构建service // 构建service
return new JsapiServiceExtension.Builder().config(config).build(); return new JsapiServiceExtension.Builder().config(getConfig()).build();
} }
@Bean @Bean
public RefundService initialRefundService() { public RefundService initialRefundService() {
Config config = // 构建service
new RSAAutoCertificateConfig.Builder() return new RefundService.Builder().config(getConfig()).build();
}
/**
* 微信支付配置获取
* @return
*/
private Config getConfig() {
return new RSAAutoCertificateConfig.Builder()
.merchantId(merchantId) .merchantId(merchantId)
.privateKeyFromPath(privateKeyPath) .privateKeyFromPath(privateKeyPath)
.merchantSerialNumber(merchantSerialNumber) .merchantSerialNumber(merchantSerialNumber)
.apiV3Key(apiV3Key) .apiV3Key(apiV3Key)
.build(); .build();
// 构建service }
return new RefundService.Builder().config(config).build();
@Bean
public NotificationParser initialNotificationParser() {
return new NotificationParser(initialNotificationConfig());
} }
@Bean @Bean
@@ -1,6 +1,7 @@
package com.central.order.controller; package com.central.order.controller;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.order.enums.OrderStatus;
import com.central.order.model.Order; import com.central.order.model.Order;
import com.central.order.service.IOrderService; import com.central.order.service.IOrderService;
import com.central.order.service.IRefundService; import com.central.order.service.IRefundService;
@@ -10,14 +11,16 @@ import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund; import com.wechat.pay.java.service.refund.model.Refund;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; 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.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("/orders") @RequestMapping("/refund")
public class OrderRefundController { public class OrderRefundController {
@Autowired @Autowired
@@ -29,39 +32,56 @@ public class OrderRefundController {
@Autowired @Autowired
private IRefundService refundService; private IRefundService refundService;
@Value("${tencent.refund-notify-url}")
private String refundNotifyUrl;
@Operation(summary = "微信支付退款") @Operation(summary = "微信支付退款")
@PostMapping("/{orderId}/refund") @PostMapping()
public Result<Refund> refundOrder(@PathVariable("orderId") Long orderId) { @Transactional(rollbackFor = Exception.class)
Order order = orderService.getById(orderId); public Result<Refund> refundOrder(@RequestBody String orderNo) {
Assert.notNull(order,"ORDER DATA不存在"); try {
CreateRequest request = new CreateRequest(); // 检查订单是否存在
request.setOutTradeNo(order.getOrderNo()); Order order = orderService.getOrderByNumber(orderNo);
request.setOutRefundNo("RF"+order.getOrderNo()); Assert.notNull(order, "ORDER DATA不存在");
request.setReason("用户申请退款");
// 退款结果回调通知地址
request.setNotifyUrl("your_notify_url");
// 设置退款金额 // 创建微信退款请求
AmountReq amount = new AmountReq(); CreateRequest request = new CreateRequest();
// 订单总金额,单位为分 request.setOutTradeNo(order.getOrderNo());
amount.setTotal(100l); request.setOutRefundNo("RF" + order.getOrderNo());
// 退款金额,单位为分 request.setReason("用户申请退款");
amount.setRefund(100l); // 从配置文件中获取退款结果回调通知地址
request.setNotifyUrl(refundNotifyUrl);
request.setAmount(amount); // 设置退款金额
AmountReq amount = new AmountReq();
// 订单总金额,单位为分
amount.setTotal(Long.valueOf(order.getOrderAmount()));
// 退款金额,单位为分
amount.setRefund(Long.valueOf(order.getOrderAmount()));
request.setAmount(amount);
// 发起退款请求 // 发起退款请求
Refund response = service.create(request); Refund response = service.create(request);
Assert.notNull(response, "退款失败");
Assert.notNull(response,"退款失败"); // 创建退款订单
com.central.order.model.Refund refund = new com.central.order.model.Refund();
refund.setRefundNo("RF" + order.getOrderNo());
refund.setOrderNo(order.getOrderNo());
refund.setUserId(order.getUserId());
refund.setStatus(OrderStatus.REFUNDING.getId());
//创建退款订单 boolean res = refundService.createRefund(refund);
com.central.order.model.Refund refund = new com.central.order.model.Refund(); if (res) {
refund.setRefundReason(refund.getRefundReason()); return Result.succeed("退款成功");
refund.setRefundNo(refund.getRefundNo()); }
refund.setOrderNo(order.getOrderNo()); throw new RuntimeException("创建退款订单失败");
refund.setUserId(order.getUserId()); } catch (Exception e) {
refundService.createRefund(refund); // 记录异常信息
return Result.succeed("退款成功"); e.printStackTrace();
return Result.failed("退款失败:" + e.getMessage());
}
} }
} }
@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONObject;
import com.central.order.enums.OrderStatus; import com.central.order.enums.OrderStatus;
import com.central.order.model.Order; import com.central.order.model.Order;
import com.central.order.service.IOrderService; import com.central.order.service.IOrderService;
import com.central.order.service.IRefundService;
import com.central.order.util.HttpServletUtils; import com.central.order.util.HttpServletUtils;
import com.wechat.pay.java.core.exception.MalformedMessageException; import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ValidationException; import com.wechat.pay.java.core.exception.ValidationException;
@@ -11,11 +12,14 @@ import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser; import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam; import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction; import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.refund.model.RefundNotification;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@@ -34,6 +38,10 @@ public class WxPayController {
private NotificationConfig notificationConfig; private NotificationConfig notificationConfig;
@Autowired @Autowired
private IOrderService orderService; private IOrderService orderService;
@Autowired
private IRefundService refundService;
@Autowired
private NotificationParser notificationParser;
/** /**
* 支付回调 * 支付回调
@@ -115,8 +123,6 @@ public class WxPayController {
order.setOrderStatus(OrderStatus.PAID.getId()); order.setOrderStatus(OrderStatus.PAID.getId());
boolean res = orderService.updateOrder(order); boolean res = orderService.updateOrder(order);
if (res){ if (res){
returnMap.put("code", "SUCCESS"); returnMap.put("code", "SUCCESS");
returnMap.put("message", "成功"); returnMap.put("message", "成功");
@@ -129,4 +135,71 @@ public class WxPayController {
return JSONObject.toJSONString(returnMap); return JSONObject.toJSONString(returnMap);
} }
@PostMapping("/refund/Notify")
public String refundCallback(@RequestHeader("Wechatpay-Signature") String signature,
@RequestHeader("Wechatpay-Timestamp") String timestamp,
@RequestHeader("Wechatpay-Nonce") String nonce,
@RequestHeader("Wechatpay-Serial") String serial,
String body) {
log.info("------收到微信退款回调通知------");
try {
// 构建请求参数
RequestParam requestParam = new RequestParam
.Builder()
.body(body)
.nonce(nonce)
.signature(signature)
.serialNumber(serial)
.timestamp(timestamp)
.build();
// 解析通知
RefundNotification notification = notificationParser.parse(requestParam, RefundNotification.class);
// 处理退款结果
handleRefundResult(notification);
// 返回成功响应
return buildSuccessResponse();
} catch (Exception e) {
// 处理异常,记录日志等
e.printStackTrace();
return buildErrorResponse();
}
}
/**
* 退款订单结果处理逻辑
* @param notification
*/
private void handleRefundResult(RefundNotification notification) {
// 获取退款通知中的关键信息
String outRefundNo = notification.getOutRefundNo();
String refundStatus = notification.getRefundStatus().name();
// 根据退款状态进行相应处理
if ("SUCCESS".equals(refundStatus)) {
// 退款成功,更新订单状态等操作
com.central.order.model.Refund refund = refundService.getRefundByNo(outRefundNo);
Assert.notNull(refund,"退款订单数据不存在");
refund.setStatus(OrderStatus.REFUNDED.getId());
refundService.updateById(refund);
Order order = orderService.getOrderByNumber(refund.getOrderNo());
Assert.notNull(order,"订单数据不存在");
order.setOrderStatus(OrderStatus.REFUNDED.getId());
orderService.updateOrder(order);
} else if ("CLOSED".equals(refundStatus)) {
// 退款关闭,处理退款关闭逻辑
} else {
// 其他退款状态,如退款中、失败等
}
}
private String buildSuccessResponse() {
return "{\"code\":\"SUCCESS\",\"message\":\"成功\"}";
}
private String buildErrorResponse() {
return "{\"code\":\"FAIL\",\"message\":\"失败\"}";
}
} }
@@ -22,13 +22,13 @@ public class OrderTimeoutScheduler {
} }
// 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况 // 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况
@Scheduled(fixedRate = 1 * 1000) // @Scheduled(fixedRate = 1 * 1000)
public void checkOrderPaySuccess() { public void checkOrderPaySuccess() {
orderService.updateOrderStatus(); orderService.updateOrderStatus();
} }
// 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况 // 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况
@Scheduled(fixedRate = 60 * 1000) // @Scheduled(fixedRate = 60 * 1000)
public void processOrdersInQueue() { public void processOrdersInQueue() {
orderService.processOrdersInQueue(); orderService.processOrdersInQueue();
} }
@@ -30,9 +30,9 @@ public interface IRefundService extends ISuperService<Refund> {
/** /**
* *
* @param refundId * @param refundNo
*/ */
void updateRefund(Refund refundId) ; Refund getRefundByNo(String refundNo) ;
} }
@@ -1,5 +1,6 @@
package com.central.order.service.impl; package com.central.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.lock.DistributedLock; import com.central.common.lock.DistributedLock;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
@@ -69,8 +70,8 @@ public class RefundServiceImpl extends SuperServiceImpl<RefundMapper, Refund> im
} }
@Override @Override
public void updateRefund(Refund refund) { public Refund getRefundByNo(String refundNo) {
baseMapper.updateById(refund); return baseMapper.selectOne(new QueryWrapper<Refund>().eq("refund_no",refundNo));
} }
} }
@@ -42,6 +42,8 @@ tencent:
appSecret: ${zlt.security.tencent.app-secret} appSecret: ${zlt.security.tencent.app-secret}
accessTokenUrl: ${zlt.security.tencent.accessTokenUrl} accessTokenUrl: ${zlt.security.tencent.accessTokenUrl}
getwxacodeUrl: https://api.weixin.qq.com/wxa/getwxacode?access_token= getwxacodeUrl: https://api.weixin.qq.com/wxa/getwxacode?access_token=
# 微信退款通知地址
refund-notify-url: ${zlt.wxrefund.notifyUrl}
file: file:
oss-url: goflyapp.oss-cn-beijing.aliyuncs.com oss-url: goflyapp.oss-cn-beijing.aliyuncs.com
cdn-url: cdn.goflytec.com cdn-url: cdn.goflytec.com
@@ -72,7 +72,9 @@ zlt.wxpay.merchantSerialNumber=11F4AC03C50EB582D3EDE082591D1F9A65388D51
# 微信支付申请的应用ID # 微信支付申请的应用ID
zlt.wxpay.appId=wx30a3c8de94a85584 zlt.wxpay.appId=wx30a3c8de94a85584
# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致) # 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致)
zlt.wxpay.notifyUrl=http://img.goflytec.com/api-order/wechat/pay/notify zlt.wxpay.notifyUrl= https://img.goflytec.com/api-order/wechat/pay/Notify
# 微信退款异步通知地址(需外网可访问且与微信支付平台配置一致)
zlt.wxrefund.notifyUrl= https://img.goflytec.com/api-order/wechat/refund/Notify
# 商户API私钥路径 # 商户API私钥路径
zlt.wxpay.privateKeyPath=D:\\wx\\WXCertUtil\\cert\\1703796518_20250114_cert\\apiclient_key.pem zlt.wxpay.privateKeyPath=D:\\wx\\WXCertUtil\\cert\\1703796518_20250114_cert\\apiclient_key.pem
# 商户APIV3密钥 # 商户APIV3密钥
@@ -64,6 +64,8 @@ zlt.wxpay.merchantSerialNumber=11F4AC03C50EB582D3EDE082591D1F9A65388D51
zlt.wxpay.appId=wx30a3c8de94a85584 zlt.wxpay.appId=wx30a3c8de94a85584
# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致) # 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致)
zlt.wxpay.notifyUrl=http://your_domain/weixin/pay/notify zlt.wxpay.notifyUrl=http://your_domain/weixin/pay/notify
# 微信退款异步通知地址(需外网可访问且与微信支付平台配置一致)
zlt.wxrefund.notifyUrl= https://img.goflytec.com/api-order/wechat/refund/Notify
# 商户API私钥路径 # 商户API私钥路径
zlt.wxpay.privateKeyPath=/data/zlt/cert/apiclient_key.pem zlt.wxpay.privateKeyPath=/data/zlt/cert/apiclient_key.pem
# 商户APIV3密钥 # 商户APIV3密钥