feat[支付模块]:支付回调逻辑
This commit is contained in:
@@ -96,7 +96,6 @@
|
||||
<version>0.2.15</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.binarywang</groupId>
|
||||
<artifactId>weixin-java-miniapp</artifactId>
|
||||
|
||||
+11
-11
@@ -2,6 +2,7 @@ package com.central.order.config;
|
||||
|
||||
import com.wechat.pay.java.core.Config;
|
||||
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
|
||||
import com.wechat.pay.java.core.notification.NotificationConfig;
|
||||
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
@@ -47,15 +48,14 @@ public class TencentPayConfiguration {
|
||||
return new JsapiServiceExtension.Builder().config(config).build();
|
||||
}
|
||||
|
||||
// public RequestParam initRequestParam() {
|
||||
// // 构造 RequestParam
|
||||
// RequestParam requestParam = new RequestParam.Builder()
|
||||
// .serialNumber(wechatPaySerial)
|
||||
// .nonce(wechatpayNonce)
|
||||
// .signature(wechatSignature)
|
||||
// .timestamp(wechatTimestamp)
|
||||
// .body(requestBody)
|
||||
// .build();
|
||||
//
|
||||
// }
|
||||
@Bean
|
||||
public NotificationConfig initialNotificationConfig() {
|
||||
// . 如果你仍在使用微信支付平台证书,则使用 RSAAutoCertificateConfig
|
||||
return new RSAAutoCertificateConfig.Builder()
|
||||
.merchantId(merchantId)
|
||||
.privateKeyFromPath(privateKeyPath)
|
||||
.merchantSerialNumber(merchantSerialNumber)
|
||||
.apiV3Key(apiV3Key)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
+41
-18
@@ -5,14 +5,14 @@ import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.model.PageResult;
|
||||
import com.central.common.model.Result;
|
||||
import com.central.common.model.SysUser;
|
||||
import com.central.order.enums.OrderStatus;
|
||||
import com.central.order.feign.UserCenterService;
|
||||
import com.central.order.model.Order;
|
||||
import com.central.order.service.IOrderService;
|
||||
import com.wechat.pay.java.core.exception.ServiceException;
|
||||
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
|
||||
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
|
||||
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
|
||||
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
|
||||
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
|
||||
import com.wechat.pay.java.service.payments.jsapi.model.*;
|
||||
import com.wechat.pay.java.service.payments.model.Transaction;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.Parameters;
|
||||
@@ -127,18 +127,41 @@ public class OrderController {
|
||||
return Result.succeed("排队订单处理已启动");
|
||||
}
|
||||
|
||||
// public void getTencentOrderById(String setTransactionId) {
|
||||
// QueryOrderByIdRequest queryRequest = new QueryOrderByIdRequest();
|
||||
// queryRequest.setMchid("190000****");
|
||||
// queryRequest.setTransactionId("4200001569202208304701234567");
|
||||
//
|
||||
// try {
|
||||
// Transaction result = service.queryOrderById(queryRequest);
|
||||
// System.out.println(result.getTradeState());
|
||||
// } catch (ServiceException e) {
|
||||
// // API返回失败, 例如ORDER_NOT_EXISTS
|
||||
// System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
|
||||
// System.out.printf("reponse body=[%s]\n", e.getResponseBody());
|
||||
// }
|
||||
// }
|
||||
@PostMapping("/update")
|
||||
public Result<String> updateOrderStatus(@RequestBody String orderNo) {
|
||||
Transaction transaction = queryOrderByOutTradeNo(orderNo);
|
||||
if (transaction != null && transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)){
|
||||
Order order = orderService.getOrderByNumber(transaction.getOutTradeNo());
|
||||
order.setOrderStatus(OrderStatus.PAID.getId());
|
||||
boolean res = orderService.updateOrder(order);
|
||||
if (res){
|
||||
return Result.succeed("更新成功");
|
||||
}
|
||||
}
|
||||
return Result.failed("未查询到订单数据");
|
||||
}
|
||||
|
||||
/** 商户订单号查询订单 */
|
||||
public Transaction queryOrderByOutTradeNo(String outTradeNo) {
|
||||
|
||||
QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
|
||||
// 调用request.setXxx(val)设置所需参数,具体参数可见Request定义
|
||||
request.setOutTradeNo(outTradeNo);
|
||||
return service.queryOrderByOutTradeNo(request);
|
||||
}
|
||||
|
||||
public void getTencentOrderById(String setTransactionId) {
|
||||
QueryOrderByIdRequest queryRequest = new QueryOrderByIdRequest();
|
||||
queryRequest.setMchid("190000****");
|
||||
queryRequest.setTransactionId("4200001569202208304701234567");
|
||||
|
||||
try {
|
||||
Transaction result = service.queryOrderById(queryRequest);
|
||||
System.out.println(result.getTradeState());
|
||||
} catch (ServiceException e) {
|
||||
// API返回失败, 例如ORDER_NOT_EXISTS
|
||||
System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
|
||||
System.out.printf("reponse body=[%s]\n", e.getResponseBody());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -46,7 +46,7 @@ public class TourismController {
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public Result<Tourism> createOrder(@RequestBody Tourism tourism) {
|
||||
public Result<Tourism> createTourism(@RequestBody Tourism tourism) {
|
||||
|
||||
boolean result = tourismService.createTourism(tourism);
|
||||
if (result) {
|
||||
@@ -56,7 +56,8 @@ public class TourismController {
|
||||
}
|
||||
}
|
||||
|
||||
public Result<Tourism> getOrderFile(@PathVariable("id") Long id) {
|
||||
@GetMapping("/{id}")
|
||||
public Result<Tourism> getTourism(@PathVariable("id") Long id) {
|
||||
Tourism tourism = tourismService.getTourismById(id);
|
||||
if (tourism == null) {
|
||||
return Result.failed("暂无数据");
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package com.central.order.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.central.order.enums.OrderStatus;
|
||||
import com.central.order.model.Order;
|
||||
import com.central.order.service.IOrderService;
|
||||
import com.central.order.util.HttpServletUtils;
|
||||
import com.wechat.pay.java.core.exception.MalformedMessageException;
|
||||
import com.wechat.pay.java.core.exception.ValidationException;
|
||||
import com.wechat.pay.java.core.notification.NotificationConfig;
|
||||
import com.wechat.pay.java.core.notification.NotificationParser;
|
||||
import com.wechat.pay.java.core.notification.RequestParam;
|
||||
import com.wechat.pay.java.service.payments.model.Transaction;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/wechat")
|
||||
public class WxPayController {
|
||||
|
||||
@Autowired
|
||||
private NotificationConfig notificationConfig;
|
||||
@Autowired
|
||||
private IOrderService orderService;
|
||||
|
||||
/**
|
||||
* 支付回调
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
@PostMapping("/payNotify")
|
||||
public String wechatPayNotify(HttpServletRequest request) throws IOException {
|
||||
log.info("------收到微信支付回调通知------");
|
||||
return payNotify(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 支付回调
|
||||
* <pre>
|
||||
* 注意:
|
||||
* 对后台通知交互时,如果微信收到应答不是成功或超时,微信认为通知失败,微信会通过一定的策略定期重新发起通知,尽可能提高通知的成功率,但微信不保证通知最终能成功
|
||||
*
|
||||
* 同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。 推荐的做法是,当商户系统收到通知进行处理时,先检查对应业务数据的状态,并判断该通知是否已经处理。如果未处理,则再进行处理;如果已处理,则直接返回结果成功。在对业务数据进行状态检查和处理之前,要采用数据锁进行并发控制,以避免函数重入造成的数据混乱。
|
||||
* 如果在所有通知频率后没有收到微信侧回调。商户应调用查询订单接口确认订单状态。
|
||||
* </pre>
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public String payNotify(HttpServletRequest request) throws IOException {
|
||||
// 请求头Wechatpay-Signature
|
||||
String signature = request.getHeader("Wechatpay-Signature");
|
||||
// 请求头Wechatpay-nonce
|
||||
String nonce = request.getHeader("Wechatpay-Nonce");
|
||||
// 请求头Wechatpay-Timestamp
|
||||
String timestamp = request.getHeader("Wechatpay-Timestamp");
|
||||
// 微信支付证书序列号
|
||||
String serial = request.getHeader("Wechatpay-Serial");
|
||||
// 签名方式
|
||||
String signType = request.getHeader("Wechatpay-Signature-Type");
|
||||
// 构造 RequestParam
|
||||
RequestParam requestParam = new RequestParam.Builder()
|
||||
.serialNumber(serial)
|
||||
.nonce(nonce)
|
||||
.signature(signature)
|
||||
.timestamp(timestamp)
|
||||
.signType(signType)
|
||||
.body(HttpServletUtils.getRequestBody(request))
|
||||
.build();
|
||||
log.info("微信支付回调body信息:{}", requestParam.getBody());
|
||||
// 初始化 NotificationParser
|
||||
NotificationParser parser = new NotificationParser((NotificationConfig) notificationConfig);
|
||||
// 以支付通知回调为例,验签、解密并转换成 Transaction
|
||||
log.info("验签参数:{}", JSONObject.toJSONString(requestParam));
|
||||
Map<String, String> returnMap = new HashMap<>(2);
|
||||
returnMap.put("code", "FAIL");
|
||||
returnMap.put("message", "失败");
|
||||
Transaction transaction = null;
|
||||
try {
|
||||
transaction = parser.parse(requestParam, Transaction.class);
|
||||
} catch (MalformedMessageException e) {
|
||||
log.error("验签失败,解析微信支付应答或回调报文异常,返回信息:", e);
|
||||
return JSONObject.toJSONString(returnMap);
|
||||
} catch (ValidationException e) {
|
||||
log.error("验签失败,验证签名失败,返回信息:", e);
|
||||
return JSONObject.toJSONString(returnMap);
|
||||
} catch (Exception e) {
|
||||
log.error("验签失败,返回信息:", e);
|
||||
return JSONObject.toJSONString(returnMap);
|
||||
}
|
||||
log.info("验签成功!-支付回调结果:{}", transaction.toString());
|
||||
// 判断订单状态
|
||||
if (Transaction.TradeStateEnum.SUCCESS != transaction.getTradeState()) {
|
||||
log.info("内部订单号【{}】,微信支付订单号【{}】支付未成功", transaction.getOutTradeNo(), transaction.getTransactionId());
|
||||
return JSONObject.toJSONString(returnMap);
|
||||
}
|
||||
// TODO 修改订单信息
|
||||
Order order = orderService.getOrderByNumber(transaction.getOutTradeNo());
|
||||
order.setOrderStatus(OrderStatus.PAID.getId());
|
||||
orderService.updateOrder(order);
|
||||
returnMap.put("code", "SUCCESS");
|
||||
returnMap.put("message", "成功");
|
||||
return JSONObject.toJSONString(returnMap);
|
||||
}
|
||||
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package com.central.order.controller;
|
||||
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.wechat.pay.java.core.exception.ValidationException;
|
||||
import com.wechat.pay.java.core.notification.NotificationConfig;
|
||||
import com.wechat.pay.java.core.notification.NotificationParser;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
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.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/pay")
|
||||
public class WxPayNotifyController {
|
||||
|
||||
|
||||
NotificationConfig config;
|
||||
|
||||
@PostMapping("/notify")
|
||||
public Result<ResponseEntity> payNotify(HttpServletRequest request, @RequestBody String body) throws Exception {
|
||||
// 初始化 NotificationParser
|
||||
NotificationParser parser = new NotificationParser(config);
|
||||
|
||||
try {
|
||||
// 以支付通知回调为例,验签、解密并转换成 Transaction
|
||||
// Transaction transaction = parser.parse(requestParam, Transaction.class);
|
||||
} catch (ValidationException e) {
|
||||
// 签名验证失败,返回 401 UNAUTHORIZED 状态码
|
||||
// logger.error("sign verification failed", e);
|
||||
// return ResponseEntity.status(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
// 如果处理失败,应返回 4xx/5xx 的状态码,例如 500 INTERNAL_SERVER_ERROR
|
||||
if (true) {
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
// 处理成功,返回 200 OK 状态码
|
||||
return ResponseEntity.status(HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
@@ -57,5 +57,12 @@ public interface IOrderService extends ISuperService<Order> {
|
||||
* @return
|
||||
*/
|
||||
Order getOrderByNumber(String orderNumber);
|
||||
|
||||
/**
|
||||
* 订单信息更新
|
||||
* @param order
|
||||
* @return
|
||||
*/
|
||||
boolean updateOrder(Order order);
|
||||
}
|
||||
|
||||
|
||||
+10
@@ -131,6 +131,16 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
||||
return baseMapper.getOrderByNumber(orderNumber);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateOrder(Order order) {
|
||||
try {
|
||||
return super.saveOrUpdateIdempotency(order, lock
|
||||
, ORDER_LOCK+order.getOrderNo(), new QueryWrapper<Order>().eq("order_no", order.getOrderNo()), "订单已存在");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
// 生成订单编号
|
||||
public String generateOrderNumber(Long tourismId) {
|
||||
// 获取当前日期,格式化为 yyyyMMdd
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.central.order.util;
|
||||
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* HttpServletRequest 获取请求体
|
||||
* </p>
|
||||
*
|
||||
* @author songfayuan
|
||||
* @date 2024/9/30 19:11
|
||||
*/
|
||||
public class HttpServletUtils {
|
||||
|
||||
/**
|
||||
* 获取请求体
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String getRequestBody(HttpServletRequest request) throws IOException {
|
||||
ServletInputStream stream = null;
|
||||
BufferedReader reader = null;
|
||||
StringBuffer sb = new StringBuffer();
|
||||
try {
|
||||
stream = request.getInputStream();
|
||||
// 获取响应
|
||||
reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IOException("读取返回支付接口数据流出现异常!");
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,10 +5,10 @@ zlt.datasource.username=root
|
||||
zlt.datasource.password=ZXC_zxc!@#123+
|
||||
|
||||
##### redis配置
|
||||
spring.data.redis.host=119.45.169.13
|
||||
spring.data.redis.host=124.222.128.40
|
||||
#spring.data.redis.host=127.0.0.1
|
||||
spring.data.redis.port=6379
|
||||
#spring.data.redis.password=iot123456@
|
||||
#spring.data.redis.password=6FtZxeMM6LlTXeMuuBS7chR8tfgyqifk
|
||||
spring.data.redis.database=0
|
||||
spring.data.redis.timeout=5000
|
||||
|
||||
@@ -31,9 +31,29 @@ zlt.s3.accessKeySecret=mmfSh4gjJm8dck0KaG6fKItpIM3tenWVHS4Ygjlm
|
||||
zlt.s3.endpoint=http://81.70.164.178:9000
|
||||
zlt.s3.bucketName=gofly
|
||||
|
||||
#### cos配置
|
||||
zlt.cos.secretId=AKIDBF6whIkz2tcCZmsnW3OUN0QcZKsDKCrH
|
||||
zlt.cos.secretKey=FRTJxdFgy8IKAl7F8nDoHagXCdrtiKhq
|
||||
zlt.cos.endpoint=gofly-1301649813.cos.ap-nanjing.myqcloud.com
|
||||
zlt.cos.bucketName=gofly-1301649813
|
||||
zlt.cos.region=ap-nanjing
|
||||
|
||||
##### 日志链路追踪
|
||||
zlt.trace.enable=true
|
||||
|
||||
zlt.security.tencent.appId=wx30a3c8de94a85584
|
||||
zlt.security.tencent.appSecret=e64d6e3dcfe88d0daee50e77f5a2ee69
|
||||
zlt.security.tencent.jscode2sessionUrl=https://api.weixin.qq.com/sns/jscode2session
|
||||
|
||||
# 微信支付商户号
|
||||
zlt.wxpay.merchantId=1703796518
|
||||
# 商户证书序列号
|
||||
zlt.wxpay.merchantSerialNumber=11F4AC03C50EB582D3EDE082591D1F9A65388D51
|
||||
# 微信支付申请的应用ID
|
||||
zlt.wxpay.appId=wx30a3c8de94a85584
|
||||
# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致)
|
||||
zlt.wxpay.notifyUrl=http://your_domain/weixin/pay/notify
|
||||
# 商户API私钥路径
|
||||
zlt.wxpay.privateKeyPath=/data/zlt/cert/apiclient_key.pem
|
||||
# 商户APIV3密钥
|
||||
zlt.wxpay.apiV3Key=aIt5Vw3cYXSCSd4L5h14kIyDsoXBow7r
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
########################## bootstrap级别通用配置 ##########################
|
||||
# 默认开发环境
|
||||
spring.profiles.active=dev
|
||||
spring.profiles.active=prod
|
||||
|
||||
##### nacos(注册中心和配置中心)地址
|
||||
#spring.cloud.nacos.server-addr=47.94.136.130:8848
|
||||
spring.cloud.nacos.server-addr=127.0.0.1:8848
|
||||
spring.cloud.nacos.server-addr=47.94.136.130:8848
|
||||
#spring.cloud.nacos.server-addr=127.0.0.1:8848
|
||||
spring.cloud.nacos.username=nacos
|
||||
spring.cloud.nacos.password=nacos
|
||||
spring.cloud.nacos.config.file-extension=yml
|
||||
|
||||
Reference in New Issue
Block a user