feat[支付模块]:腾讯官方v3支付集成,替代第三方集成支付

This commit is contained in:
2025-01-14 17:44:35 +08:00
parent 5f51e9c6f9
commit 04177acfaf
8 changed files with 169 additions and 188 deletions
+3 -14
View File
@@ -89,22 +89,11 @@
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId> <artifactId>hibernate-validator</artifactId>
</dependency> </dependency>
<!-- okhttp依赖,用于发送HTTP请求 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<!-- 微信支付Java开发工具包 -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-pay</artifactId>
<version>4.1.0</version>
</dependency>
<dependency> <dependency>
<groupId>com.egzosn</groupId> <groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>pay-java-wx</artifactId> <artifactId>wechatpay-java</artifactId>
<version>2.14.7</version> <version>0.2.15</version>
</dependency> </dependency>
@@ -0,0 +1,61 @@
package com.central.order.config;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 支付配置类
*
* @author lsl
* @date 2025-01-14
*
*/
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "tencent")
public class TencentPayConfiguration {
private String merchantId;
private String merchantSerialNumber;
private String apiV3Key;
private String privateKeyPath;
/**
* jsapi支付方式 支持小程序公众号支付
* @return
*/
@Bean
public JsapiServiceExtension initialJsapiServiceExtension() {
Config config =
new RSAAutoCertificateConfig.Builder()
.merchantId(merchantId)
.privateKeyFromPath(privateKeyPath)
.merchantSerialNumber(merchantSerialNumber)
.apiV3Key(apiV3Key)
.build();
// 构建service
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();
//
// }
}
@@ -8,26 +8,23 @@ import com.central.common.model.SysUser;
import com.central.order.feign.UserCenterService; import com.central.order.feign.UserCenterService;
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.egzosn.pay.common.api.PayService; import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.egzosn.pay.common.bean.PayOrder; import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.egzosn.pay.wx.bean.WxTransactionType; import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.egzosn.pay.wx.v3.api.WxPayConfigStorage; import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.egzosn.pay.wx.v3.api.WxPayService; import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
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.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID;
/** /**
* Order information * Order information
@@ -44,27 +41,11 @@ public class OrderController {
@Autowired @Autowired
private IOrderService orderService; private IOrderService orderService;
private PayService payService;
@Autowired @Autowired
private UserCenterService userCenterService; private UserCenterService userCenterService;
/**
* 这里对 PayService 与 router进行构造
*/
@PostConstruct
public void init() {
WxPayConfigStorage wxPayConfigStorage = new WxPayConfigStorage(); @Autowired
wxPayConfigStorage.setMchId("1703796518"); private JsapiServiceExtension service;
wxPayConfigStorage.setAppId("wx30a3c8de94a85584");
// wxPayConfigStorage.setKeyPublic("转账公钥,转账时必填");
// wxPayConfigStorage.setApiKey("密钥");
wxPayConfigStorage.setNotifyUrl("https://img.goflytec.com/pay/unifiedorder");
wxPayConfigStorage.setReturnUrl("https://img.goflytec.com/pay/unifiedorder");
wxPayConfigStorage.setSignType("MD5");
wxPayConfigStorage.setInputCharset("utf-8");
payService = new WxPayService(wxPayConfigStorage);
}
/** /**
* 列表 * 列表
*/ */
@@ -81,10 +62,10 @@ public class OrderController {
// 创建订单--》 // 创建订单--》
// 返回前端订单信息--》 // 返回前端订单信息--》
// 前端发起支付(api-order/unifiedOrder)--》 // 前端发起支付(PUT api-order/{id}/pay)--》
// 等待回调更新订单状态(微信支付回调接口/api-order/pay/notify)--》 // 等待回调更新订单状态(微信支付回调接口/api-order/pay/notify)--》
// 前端支付成功后创建支付记录(/api-order/payment) // 同时创建支付记录(/api-order/payment)
// 进入排队队列中(/api-order/queue)已支付订单列表 // 前端进入排队队列中(/api-order/queue)已支付订单列表
// 设备执行完成后更新订单状态已完成(根据设备上报状态触发或者设备直接调用接口进行更新任务状态) // 设备执行完成后更新订单状态已完成(根据设备上报状态触发或者设备直接调用接口进行更新任务状态)
@PostMapping @PostMapping
public Result<Order> createOrder(@RequestBody Order order) { public Result<Order> createOrder(@RequestBody Order order) {
@@ -107,20 +88,29 @@ public class OrderController {
* @return 返回jsapi所需参数 * @return 返回jsapi所需参数
*/ */
@PutMapping("/{orderId}/pay") @PutMapping("/{orderId}/pay")
public Result<Map> payOrder(@PathVariable("orderId") Long orderId) { public Result<PrepayWithRequestPaymentResponse> payOrder(@PathVariable("orderId") Long orderId) {
SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId()); SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId());
Order order = orderService.getById(orderId);
PayOrder order = new PayOrder("订单title", "摘要", new BigDecimal(0.01) , UUID.randomUUID().toString().replace("-", "")); // request.setXxx(val)设置所需参数,具体参数可见Request定义
//公众号支付 PrepayRequest request = new PrepayRequest();
order.setTransactionType(WxTransactionType.JSAPI); Amount amount = new Amount();
//微信公众号对应微信付款用户的唯一标识 amount.setTotal(100);
order.setOpenid(user.getOpenId()); request.setAmount(amount);
request.setAppid("wx30a3c8de94a85584");
request.setMchid("1703796518");
request.setDescription("测试商品标题");
request.setNotifyUrl("https://notify_url");
request.setOutTradeNo(order.getOrderNo());
Payer payer = new Payer();
payer.setOpenid(user.getOpenId());
request.setPayer(payer);
// 调用下单方法,得到应答
// response包含了调起支付所需的所有参数,可直接用于前端调起支付
PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
Map orderInfo = payService.orderInfo(order); return Result.succeed(response,"成功");
orderInfo.put("code", 0);
return Result.succeed(orderInfo,"成功");
} }
// 获取排队中的订单列表 // 获取排队中的订单列表
@@ -136,4 +126,19 @@ public class OrderController {
orderService.processOrdersInQueue(); orderService.processOrdersInQueue();
return Result.succeed("排队订单处理已启动"); 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());
// }
// }
} }
@@ -1,77 +0,0 @@
package com.central.order.controller;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
/**
* pay information
*
* @author lsl
* @date 2024-12-19 17:51:47
*/
@Slf4j
@RestController
@Tag(name = "Pay information")
@RequiredArgsConstructor
public class WeixinPayController {
// 此处简单示例,实际可从配置中心等获取配置构建WxPayService
private static final WxPayService wxPayService = new WxPayServiceImpl();
static {
WxPayConfig payConfig = new WxPayConfig();
payConfig.setMchId("YOUR_MCH_ID");
payConfig.setMchKey("YOUR_MCH_KEY");
payConfig.setAppId("YOUR_APP_ID");
payConfig.setNotifyUrl("http://your_domain/weixin/pay/notify");
// 设置证书等其他配置信息(如果需要)
((WxPayServiceImpl) wxPayService).setConfig(payConfig);
}
// 接收前端传来的订单信息,调用微信支付统一下单接口
@PostMapping("/unifiedOrder")
public Map<String, Object> unifiedOrder(@RequestBody Map<String, Object> orderInfo) {
try {
String orderNumber = (String) orderInfo.get("orderNumber");
BigDecimal amount = new BigDecimal((String) orderInfo.get("amount"));
WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
request.setBody("商品描述"); // 可根据实际订单详情填写更准确的描述
request.setOutTradeNo(orderNumber);
request.setTotalFee(amount.multiply(new BigDecimal(100)).intValue()); // 微信支付金额单位为分
// request.setSpbillCreateDate(System.currentTimeMillis() / 1000 + "");
request.setNotifyUrl("http://your_domain/weixin/pay/notify");
request.setTradeType("JSAPI"); // 这里以公众号支付为例,根据实际情况选择支付类型,如APP支付、小程序支付等
WxPayUnifiedOrderResult result = wxPayService.unifiedOrder(request);
if ("SUCCESS".equals(result.getReturnCode()) && "SUCCESS".equals(result.getResultCode())) {
Map<String, Object> response = new HashMap<>();
response.put("prepayId", result.getPrepayId());
// 此处还需按照微信支付要求对返回信息进行进一步处理,生成前端调起支付所需的完整参数,如签名等,此处简化示例
return response;
} else {
// 处理统一下单失败情况,返回相应错误信息给前端
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("errorMsg", "统一下单失败");
return errorResponse;
}
} catch (Exception e) {
e.printStackTrace();
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("errorMsg", "支付请求处理异常");
return errorResponse;
}
}
}
@@ -1,43 +1,46 @@
//package com.central.order.controller; package com.central.order.controller;
//
//
//import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse; import com.central.common.model.Result;
//import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult; import com.wechat.pay.java.core.exception.ValidationException;
//import com.github.binarywang.wxpay.service.WxPayService; import com.wechat.pay.java.core.notification.NotificationConfig;
//import org.springframework.beans.factory.annotation.Autowired; import com.wechat.pay.java.core.notification.NotificationParser;
//import org.springframework.web.bind.annotation.PostMapping; import org.springframework.http.HttpStatus;
//import org.springframework.web.bind.annotation.RequestBody; import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.PostMapping;
// import org.springframework.web.bind.annotation.RequestBody;
//import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.RequestMapping;
//import java.util.HashMap; import org.springframework.web.bind.annotation.RestController;
//import java.util.Map;
// import javax.servlet.http.HttpServletRequest;
//@RestController
//public class WxPayNotifyController { @RestController
// @RequestMapping("/pay")
//// @Autowired public class WxPayNotifyController {
// private WxPayService wxPayService;
////
// @PostMapping("/pay/notify") NotificationConfig config;
// public String payNotify(HttpServletRequest request, @RequestBody String body) throws Exception {
// // 将XML格式的请求体转换为Map @PostMapping("/notify")
// Map<String, String> params = new HashMap<>(); public Result<ResponseEntity> payNotify(HttpServletRequest request, @RequestBody String body) throws Exception {
// // 这里需要你自己实现一个将XML转换为Map的工具方法 // 初始化 NotificationParser
// // 例如使用Dom4j或JAXB等库来解析XML NotificationParser parser = new NotificationParser(config);
//
// // 验证签名 try {
// boolean signVerified = wxPayService.verifyNotify(params); // 以支付通知回调为例,验签、解密并转换成 Transaction
// if (!signVerified) { // Transaction transaction = parser.parse(requestParam, Transaction.class);
// return WxPayNotifyResponse.fail("签名验证失败").toXml(); } catch (ValidationException e) {
// } // 签名验证失败,返回 401 UNAUTHORIZED 状态码
// // logger.error("sign verification failed", e);
// // 转换为WxPayOrderNotifyResult对象(可选,但推荐) // return ResponseEntity.status(HttpStatus.UNAUTHORIZED);
// WxPayOrderNotifyResult notifyResult = WxPayOrderNotifyResult.fromXml(body); }
//
// // 处理支付结果 // 如果处理失败,应返回 4xx/5xx 的状态码,例如 500 INTERNAL_SERVER_ERROR
// // 根据notifyResult中的数据进行业务处理,如更新订单状态等 if (true) {
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
// return WxPayNotifyResponse.success("处理成功").toXml(); }
// }
//} // 处理成功,返回 200 OK 状态码
return ResponseEntity.status(HttpStatus.OK);
}
}
@@ -38,7 +38,7 @@ public class Order extends SuperEntity {
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime; private Date updateTime;
private Long createId; private String tenantId;
private String company; private String company;
private Integer isDel; private Integer isDel;
@@ -26,18 +26,18 @@ knife4j:
swagger-model-name: 订单中心接口文档 swagger-model-name: 订单中心接口文档
# 微信支付商户号 # 微信支付商户号
wxpay: tencent:
mchId: ${zlt.wxpay.mchId} merchantId: ${zlt.wxpay.merchantId}
# 微信支付商户密钥 # 微信支付商户密钥
mchKey: ${zlt.wxpay.mchKey} merchantSerialNumber: ${zlt.wxpay.merchantSerialNumber}
# 微信支付申请的应用ID # 微信支付申请的应用ID
appId: ${zlt.wxpay.appId} appId: ${zlt.wxpay.appId}
# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致) # 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致)
notifyUrl: ${zlt.wxpay.notifyUrl} notifyUrl: ${zlt.wxpay.notifyUrl}
# 微信支付API证书路径(如果需要证书的情况下,这里填写证书相关文件的路径) # 微信支付API证书路径(如果需要证书的情况下,这里填写证书相关文件的路径)
certPath: ${zlt.wxpay.certPath} privateKeyPath: ${zlt.wxpay.privateKeyPath}
# 微信支付API证书密码(如果有) apiV3Key: ${zlt.wxpay.apiV3Key}
certPassword: ${zlt.wxpay.certPassword}
#审计日志 #审计日志
# audit-log: # audit-log:
# enabled: true # enabled: true
@@ -54,14 +54,14 @@ zlt.security.tencent.appSecret=9d344e6c86b42105b6e4a018f242e233
zlt.security.tencent.jscode2sessionUrl=https://api.weixin.qq.com/sns/jscode2session zlt.security.tencent.jscode2sessionUrl=https://api.weixin.qq.com/sns/jscode2session
# 微信支付商户号 # 微信支付商户号
zlt.wxpay.mchId=YOUR_MCH_ID zlt.wxpay.merchantId=1703796518
# 微信支付商户密钥 # 商户证书序列号
zlt.wxpay.mchKey=YOUR_MCH_KEY zlt.wxpay.merchantSerialNumber=11F4AC03C50EB582D3EDE082591D1F9A65388D51
# 微信支付申请的应用ID # 微信支付申请的应用ID
zlt.wxpay.appId=YOUR_APP_ID zlt.wxpay.appId=wx30a3c8de94a85584
# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致) # 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致)
zlt.wxpay.notifyUrl=http://your_domain/weixin/pay/notify zlt.wxpay.notifyUrl=http://your_domain/weixin/pay/notify
# 微信支付API证书路径(如果需要证书的情况下,这里填写证书相关文件的路径) # 商户API私钥路径
zlt.wxpay.certPath=/path/to/your/cert.pem zlt.wxpay.privateKeyPath=D:\\wx\\WXCertUtil\\cert\\1703796518_20250114_cert\\apiclient_key.pem
# 微信支付API证书密码(如果有) # 商户APIV3密钥
zlt.wxpay.certPassword=YOUR_CERT_PASSWORD zlt.wxpay.apiV3Key=aIt5Vw3cYXSCSd4L5h14kIyDsoXBow7r