!4 fix(服务商模式支付管理): 服务商支付流程打通
Merge pull request !4 from Iamasoldier/develop-hot-local
This commit is contained in:
+35
-1
@@ -56,4 +56,38 @@ UPDATE qrcodes SET material_count = 1 WHERE material_count IS NULL;
|
|||||||
-- 素材数量字段说明:
|
-- 素材数量字段说明:
|
||||||
-- - material_count > 0:表示该二维码需要上传的素材数量
|
-- - material_count > 0:表示该二维码需要上传的素材数量
|
||||||
-- - 当订单的文件数量达到或超过此数量时,订单状态将自动更新为"素材上传完成"
|
-- - 当订单的文件数量达到或超过此数量时,订单状态将自动更新为"素材上传完成"
|
||||||
-- - 默认值为1,表示每个二维码至少需要1个素材文件
|
-- - 默认值为1,表示每个二维码至少需要1个素材文件
|
||||||
|
|
||||||
|
-- ========== 微信平台证书序列号字段迁移脚本 ==========
|
||||||
|
-- 执行时间:2024-01-XX
|
||||||
|
-- 说明:为sys_wechat_config表添加微信平台证书序列号字段
|
||||||
|
|
||||||
|
-- 1. 添加微信平台证书序列号字段
|
||||||
|
ALTER TABLE sys_wechat_config ADD COLUMN serial_number VARCHAR(64) COMMENT '微信平台证书序列号(用于回调验证)';
|
||||||
|
|
||||||
|
-- 2. 创建索引以提高查询性能
|
||||||
|
CREATE INDEX idx_wechat_config_serial_number ON sys_wechat_config(serial_number);
|
||||||
|
|
||||||
|
-- 3. 添加注释说明
|
||||||
|
-- 微信平台证书序列号字段说明:
|
||||||
|
-- - serial_number:微信平台证书的序列号,用于验证回调请求的签名
|
||||||
|
-- - 在微信支付回调时,通过此字段可以快速定位对应的配置信息
|
||||||
|
-- - 与回调请求头中的 Wechatpay-Serial 字段对应
|
||||||
|
-- - 支持一个商户配置多个平台证书,通过序列号区分
|
||||||
|
|
||||||
|
-- ========== wechat_config表微信平台证书序列号字段迁移脚本 ==========
|
||||||
|
-- 执行时间:2024-01-XX
|
||||||
|
-- 说明:为wechat_config表添加微信平台证书序列号字段
|
||||||
|
|
||||||
|
-- 1. 添加微信平台证书序列号字段
|
||||||
|
ALTER TABLE wechat_config ADD COLUMN serial_number VARCHAR(64) COMMENT '微信平台证书序列号(用于回调验证)';
|
||||||
|
|
||||||
|
-- 2. 创建索引以提高查询性能
|
||||||
|
CREATE INDEX idx_wechat_config_serial_number_2 ON wechat_config(serial_number);
|
||||||
|
|
||||||
|
-- 3. 添加注释说明
|
||||||
|
-- 微信平台证书序列号字段说明:
|
||||||
|
-- - serial_number:微信平台证书的序列号,用于验证回调请求的签名
|
||||||
|
-- - 在微信支付回调时,通过此字段可以快速定位对应的配置信息
|
||||||
|
-- - 与回调请求头中的 Wechatpay-Serial 字段对应
|
||||||
|
-- - 支持一个商户配置多个平台证书,通过序列号区分
|
||||||
+56
-283
@@ -1,13 +1,10 @@
|
|||||||
package com.central.order.controller;
|
package com.central.order.controller;
|
||||||
|
|
||||||
import com.central.order.constants.ProfitSharingConstants;
|
|
||||||
import com.central.order.enums.OrderStatus;
|
import com.central.order.enums.OrderStatus;
|
||||||
import com.central.order.enums.RefundState;
|
import com.central.order.enums.RefundState;
|
||||||
import com.central.order.model.Order;
|
import com.central.order.model.Order;
|
||||||
import com.central.order.model.ProfitSharing;
|
|
||||||
import com.central.order.model.QrCode;
|
import com.central.order.model.QrCode;
|
||||||
import com.central.order.service.IOrderService;
|
import com.central.order.service.IOrderService;
|
||||||
import com.central.order.service.IProfitSharingService;
|
|
||||||
import com.central.order.service.IQrCodeService;
|
import com.central.order.service.IQrCodeService;
|
||||||
import com.central.order.service.IRefundService;
|
import com.central.order.service.IRefundService;
|
||||||
import com.central.wechat.config.WxPayConfigFactory;
|
import com.central.wechat.config.WxPayConfigFactory;
|
||||||
@@ -19,18 +16,13 @@ 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.RefundNotification;
|
||||||
import com.wechat.pay.java.service.refund.model.Status;
|
import com.wechat.pay.java.service.refund.model.Status;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import lombok.Data;
|
|
||||||
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.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RestController
|
@RestController
|
||||||
@@ -44,8 +36,6 @@ public class WxPayController {
|
|||||||
private IRefundService refundService;
|
private IRefundService refundService;
|
||||||
@Autowired
|
@Autowired
|
||||||
private IQrCodeService qrCodeService;
|
private IQrCodeService qrCodeService;
|
||||||
@Autowired
|
|
||||||
private IProfitSharingService profitSharingService;
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private WxPayConfigFactory wxPayConfigFactory;
|
private WxPayConfigFactory wxPayConfigFactory;
|
||||||
@@ -74,13 +64,11 @@ public class WxPayController {
|
|||||||
.build();
|
.build();
|
||||||
log.info("------收到微信支付成功回调通知------");
|
log.info("------收到微信支付成功回调通知------");
|
||||||
log.info(requestParam.toString());
|
log.info(requestParam.toString());
|
||||||
|
|
||||||
// 根据证书序列号获取配置
|
// 根据证书序列号获取配置
|
||||||
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
|
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
|
||||||
String tenantId = defaultTenantId;
|
Assert.notNull(config,"支付配置参数为空,请确认参数是否正确配置");
|
||||||
if (config != null) {
|
String tenantId = config.getTenantId();
|
||||||
tenantId = config.getTenantId();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 创建通知解析器
|
// 创建通知解析器
|
||||||
NotificationParser notificationParser;
|
NotificationParser notificationParser;
|
||||||
@@ -91,7 +79,7 @@ public class WxPayController {
|
|||||||
// 普通商户模式:根据租户ID创建通知解析器
|
// 普通商户模式:根据租户ID创建通知解析器
|
||||||
notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
|
notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析通知
|
// 解析通知
|
||||||
Transaction transaction = notificationParser.parse(requestParam, Transaction.class);
|
Transaction transaction = notificationParser.parse(requestParam, Transaction.class);
|
||||||
|
|
||||||
@@ -112,9 +100,9 @@ public class WxPayController {
|
|||||||
*/
|
*/
|
||||||
private void handlePaymentResult(Transaction transaction, WechatConfig config) {
|
private void handlePaymentResult(Transaction transaction, WechatConfig config) {
|
||||||
try {
|
try {
|
||||||
log.info("处理支付结果,交易号:{}, 商户订单号:{}",
|
log.info("处理支付结果,交易号:{}, 商户订单号:{}",
|
||||||
transaction.getTransactionId(), transaction.getOutTradeNo());
|
transaction.getTransactionId(), transaction.getOutTradeNo());
|
||||||
|
|
||||||
// 根据是否为服务商模式处理不同的逻辑
|
// 根据是否为服务商模式处理不同的逻辑
|
||||||
if (Boolean.TRUE.equals(config.getIsServiceMode())) {
|
if (Boolean.TRUE.equals(config.getIsServiceMode())) {
|
||||||
// 服务商模式:处理子商户订单
|
// 服务商模式:处理子商户订单
|
||||||
@@ -134,7 +122,7 @@ public class WxPayController {
|
|||||||
private void handleSubMerchantPaymentResult(Transaction transaction, WechatConfig config) {
|
private void handleSubMerchantPaymentResult(Transaction transaction, WechatConfig config) {
|
||||||
// TODO: 实现服务商模式下的支付结果处理逻辑
|
// TODO: 实现服务商模式下的支付结果处理逻辑
|
||||||
log.info("处理服务商模式支付结果,子商户号:{}", config.getSubMchId());
|
log.info("处理服务商模式支付结果,子商户号:{}", config.getSubMchId());
|
||||||
|
|
||||||
// 1. 更新订单状态
|
// 1. 更新订单状态
|
||||||
// 2. 处理分账逻辑(如果需要)
|
// 2. 处理分账逻辑(如果需要)
|
||||||
// 3. 发送通知
|
// 3. 发送通知
|
||||||
@@ -144,48 +132,39 @@ public class WxPayController {
|
|||||||
* 处理普通商户模式下的支付结果
|
* 处理普通商户模式下的支付结果
|
||||||
*/
|
*/
|
||||||
private void handleMerchantPaymentResult(Transaction transaction, WechatConfig config) {
|
private void handleMerchantPaymentResult(Transaction transaction, WechatConfig config) {
|
||||||
// TODO: 实现普通商户模式下的支付结果处理逻辑
|
|
||||||
log.info("处理普通商户模式支付结果,商户号:{}", config.getMerchantId());
|
log.info("处理普通商户模式支付结果,商户号:{}", config.getMerchantId());
|
||||||
|
|
||||||
// 1. 更新订单状态
|
|
||||||
// 2. 处理分账逻辑(如果需要)
|
|
||||||
// 3. 发送通知
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
String outTradeNo = transaction.getOutTradeNo();
|
||||||
* 检查是否开启分润
|
String tradeState = transaction.getTradeState().toString();
|
||||||
*/
|
|
||||||
private boolean isEnableProfit(QrCode qrCode) {
|
|
||||||
return qrCode != null &&
|
|
||||||
Integer.valueOf(1).equals(qrCode.getEnableProfit()) &&
|
|
||||||
qrCode.getPayeeStatus() != null &&
|
|
||||||
qrCode.getPayeeStatus() == 1 && // 确保分账账号已验证
|
|
||||||
qrCode.getPayeeAccount() != null && // 确保有收款账号
|
|
||||||
qrCode.getProfitRate() != null; // 确保有分润比例
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送分账异常告警
|
|
||||||
*/
|
|
||||||
private void sendProfitSharingAlert(Order order, String errorMessage) {
|
|
||||||
try {
|
try {
|
||||||
String alertMessage = String.format(
|
if ("SUCCESS".equals(tradeState)) {
|
||||||
"分账处理异常告警\n" +
|
// 1. 获取订单和二维码信息
|
||||||
"订单号:%s\n" +
|
Order order = orderService.getOrderByNumber(outTradeNo);
|
||||||
"异常信息:%s\n" +
|
if (order == null) {
|
||||||
"时间:%s",
|
log.error("订单不存在: {}", outTradeNo);
|
||||||
order.getOrderNo(),
|
return;
|
||||||
errorMessage,
|
}
|
||||||
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
|
|
||||||
);
|
|
||||||
|
|
||||||
log.error(alertMessage);
|
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
|
||||||
// TODO: 实现具体的告警通知逻辑
|
if (qrCode == null) {
|
||||||
} catch (Exception e) {
|
log.error("二维码不存在: {}", order.getCodeId());
|
||||||
log.error("发送分账异常告警失败", e);
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 更新订单状态
|
||||||
|
order.setOrderStatus(OrderStatus.PAID.getId());
|
||||||
|
order.setPayTime(new Date());
|
||||||
|
orderService.updateOrder(order);
|
||||||
|
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@PostMapping("/refund/notify")
|
@PostMapping("/refund/notify")
|
||||||
public String refundCallback(@RequestHeader("Wechatpay-Signature") String signature,
|
public String refundCallback(@RequestHeader("Wechatpay-Signature") String signature,
|
||||||
@RequestHeader("Wechatpay-Timestamp") String timestamp,
|
@RequestHeader("Wechatpay-Timestamp") String timestamp,
|
||||||
@@ -220,7 +199,7 @@ public class WxPayController {
|
|||||||
// 普通商户模式:根据租户ID创建通知解析器
|
// 普通商户模式:根据租户ID创建通知解析器
|
||||||
notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
|
notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析通知
|
// 解析通知
|
||||||
RefundNotification notification = notificationParser.parse(requestParam, RefundNotification.class);
|
RefundNotification notification = notificationParser.parse(requestParam, RefundNotification.class);
|
||||||
|
|
||||||
@@ -241,9 +220,9 @@ public class WxPayController {
|
|||||||
*/
|
*/
|
||||||
private void handleRefundResult(RefundNotification notification, WechatConfig config) {
|
private void handleRefundResult(RefundNotification notification, WechatConfig config) {
|
||||||
try {
|
try {
|
||||||
log.info("处理退款结果,退款单号:{}, 商户退款单号:{}",
|
log.info("处理退款结果,退款单号:{}, 商户退款单号:{}",
|
||||||
notification.getRefundId(), notification.getOutRefundNo());
|
notification.getRefundId(), notification.getOutRefundNo());
|
||||||
|
|
||||||
// 根据是否为服务商模式处理不同的逻辑
|
// 根据是否为服务商模式处理不同的逻辑
|
||||||
if (Boolean.TRUE.equals(config.getIsServiceMode())) {
|
if (Boolean.TRUE.equals(config.getIsServiceMode())) {
|
||||||
// 服务商模式:处理子商户退款
|
// 服务商模式:处理子商户退款
|
||||||
@@ -263,7 +242,7 @@ public class WxPayController {
|
|||||||
private void handleSubMerchantRefundResult(RefundNotification notification, WechatConfig config) {
|
private void handleSubMerchantRefundResult(RefundNotification notification, WechatConfig config) {
|
||||||
// TODO: 实现服务商模式下的退款结果处理逻辑
|
// TODO: 实现服务商模式下的退款结果处理逻辑
|
||||||
log.info("处理服务商模式退款结果,子商户号:{}", config.getSubMchId());
|
log.info("处理服务商模式退款结果,子商户号:{}", config.getSubMchId());
|
||||||
|
|
||||||
// 1. 更新退款状态
|
// 1. 更新退款状态
|
||||||
// 2. 处理相关业务逻辑
|
// 2. 处理相关业务逻辑
|
||||||
}
|
}
|
||||||
@@ -272,214 +251,31 @@ public class WxPayController {
|
|||||||
* 处理普通商户模式下的退款结果
|
* 处理普通商户模式下的退款结果
|
||||||
*/
|
*/
|
||||||
private void handleMerchantRefundResult(RefundNotification notification, WechatConfig config) {
|
private void handleMerchantRefundResult(RefundNotification notification, WechatConfig config) {
|
||||||
// TODO: 实现普通商户模式下的退款结果处理逻辑
|
|
||||||
log.info("处理普通商户模式退款结果,商户号:{}", config.getMerchantId());
|
log.info("处理普通商户模式退款结果,商户号:{}", config.getMerchantId());
|
||||||
|
|
||||||
// 1. 更新退款状态
|
|
||||||
// 2. 处理相关业务逻辑
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
// 获取退款通知中的关键信息
|
||||||
* 构建请求参数
|
String outRefundNo = notification.getOutRefundNo();
|
||||||
*/
|
|
||||||
private RequestParam buildRequestParam(Map<String, String> headers, String body) {
|
|
||||||
return new RequestParam.Builder()
|
|
||||||
.serialNumber(headers.get("Wechatpay-Serial"))
|
|
||||||
.nonce(headers.get("Wechatpay-Nonce"))
|
|
||||||
.signature(headers.get("Wechatpay-Signature"))
|
|
||||||
.timestamp(headers.get("Wechatpay-Timestamp"))
|
|
||||||
.body(body)
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
log.info("回调返回结果"+notification);
|
||||||
* 解析通知数据
|
// 根据退款状态进行相应处理
|
||||||
*/
|
if (Status.SUCCESS.equals(notification.getRefundStatus())) {
|
||||||
private ProfitSharingNotification parseNotification(RequestParam requestParam) {
|
// 退款成功,更新订单状态等操作
|
||||||
try {
|
com.central.order.model.Refund refund = refundService.getRefundByNo(outRefundNo);
|
||||||
NotificationParser parser = wxPayConfigFactory.createNotificationParser(defaultTenantId);
|
Assert.notNull(refund,"退款订单数据不存在");
|
||||||
// 解析为Map后转换为ProfitSharingNotification对象
|
refund.setStatus(OrderStatus.REFUNDED.getId());
|
||||||
Map<String, Object> result = parser.parse(requestParam, Map.class);
|
refund.setState(RefundState.APPROVED.getId());
|
||||||
|
refund.setRefundTime(new Date());
|
||||||
|
refundService.updateById(refund);
|
||||||
|
|
||||||
ProfitSharingNotification notification = new ProfitSharingNotification();
|
Order order = orderService.getOrderByNumber(refund.getOrderNo());
|
||||||
notification.setMchid((String) result.get("mchid"));
|
Assert.notNull(order,"订单数据不存在");
|
||||||
notification.setTransactionId((String) result.get("transaction_id"));
|
order.setOrderStatus(OrderStatus.REFUNDED.getId());
|
||||||
notification.setOutOrderNo((String) result.get("out_order_no"));
|
orderService.updateOrder(order);
|
||||||
notification.setState((String) result.get("state"));
|
} else if ("CLOSED".equals(notification.getRefundStatus())) {
|
||||||
notification.setFailReason((String) result.get("fail_reason"));
|
// 退款关闭,处理退款关闭逻辑
|
||||||
|
|
||||||
// 处理接收方列表
|
|
||||||
if (result.containsKey("receivers")) {
|
|
||||||
List<Map<String, Object>> receiversMap = (List<Map<String, Object>>) result.get("receivers");
|
|
||||||
List<ProfitSharingNotification.Receiver> receivers = new ArrayList<>();
|
|
||||||
|
|
||||||
for (Map<String, Object> receiverMap : receiversMap) {
|
|
||||||
ProfitSharingNotification.Receiver receiver = new ProfitSharingNotification.Receiver();
|
|
||||||
receiver.setType((String) receiverMap.get("type"));
|
|
||||||
receiver.setAccount((String) receiverMap.get("account"));
|
|
||||||
receiver.setAmount(Long.valueOf(receiverMap.get("amount").toString()));
|
|
||||||
receiver.setDescription((String) receiverMap.get("description"));
|
|
||||||
receiver.setResult((String) receiverMap.get("result"));
|
|
||||||
receiver.setFailReason((String) receiverMap.get("fail_reason"));
|
|
||||||
receiver.setDetailId((String) receiverMap.get("detail_id"));
|
|
||||||
receivers.add(receiver);
|
|
||||||
}
|
|
||||||
notification.setReceivers(receivers);
|
|
||||||
}
|
|
||||||
|
|
||||||
return notification;
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("解析分账回调通知失败", e);
|
|
||||||
throw new RuntimeException("解析分账回调通知失败", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 优化后的分账回调处理方法
|
|
||||||
*/
|
|
||||||
@PostMapping("/profitsharing/notify")
|
|
||||||
public String handleProfitSharingNotify(@RequestHeader Map<String, String> headers,
|
|
||||||
@RequestBody String body) {
|
|
||||||
log.info("收到分账回调通知: headers={}, body={}", headers, body);
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 1. 验证通知签名
|
|
||||||
RequestParam requestParam = buildRequestParam(headers, body);
|
|
||||||
|
|
||||||
// 2. 解析通知数据
|
|
||||||
ProfitSharingNotification notification = parseNotification(requestParam);
|
|
||||||
|
|
||||||
// 3. 处理分账结果
|
|
||||||
handleProfitSharingNotification(notification);
|
|
||||||
|
|
||||||
// 4. 返回成功响应
|
|
||||||
return buildSuccessResponse();
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("处理分账回调失败", e);
|
|
||||||
return buildErrorResponse();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleProfitSharingNotification(ProfitSharingNotification notification) {
|
|
||||||
String orderNo = notification.getOutOrderNo();
|
|
||||||
String state = notification.getState();
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 1. 获取分账记录
|
|
||||||
ProfitSharing profitSharing = profitSharingService.getByOrderNo(orderNo);
|
|
||||||
if (profitSharing == null) {
|
|
||||||
log.error("分账记录不存在: {}", orderNo);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 根据状态处理
|
|
||||||
switch (state) {
|
|
||||||
case "FINISHED":
|
|
||||||
// 分账成功
|
|
||||||
handleProfitSharingSuccess(profitSharing, notification);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "FAILED":
|
|
||||||
// 分账失败
|
|
||||||
handleProfitSharingFailure(profitSharing, notification);
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
log.warn("未知的分账状态: orderNo={}, state={}", orderNo, state);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("处理分账回调异常: orderNo={}", orderNo, e);
|
|
||||||
// 确保更新状态
|
|
||||||
profitSharingService.updateProfitSharingStatus(
|
|
||||||
orderNo,
|
|
||||||
ProfitSharingConstants.Status.FAILED
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 处理分账成功
|
|
||||||
*/
|
|
||||||
private void handleProfitSharingSuccess(ProfitSharing profitSharing,
|
|
||||||
ProfitSharingNotification notification) {
|
|
||||||
// 1. 更新分账状态
|
|
||||||
profitSharing.setStatus(ProfitSharingConstants.Status.SUCCESS);
|
|
||||||
profitSharing.setFinishTime(new Date());
|
|
||||||
|
|
||||||
// 2. 如果有接收方信息,更新接收方结果
|
|
||||||
if (notification.getReceivers() != null && !notification.getReceivers().isEmpty()) {
|
|
||||||
ProfitSharingNotification.Receiver receiver = notification.getReceivers().get(0);
|
|
||||||
profitSharing.setReceiverAmount(receiver.getAmount());
|
|
||||||
profitSharing.setProfitSharingId(receiver.getDetailId());
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 保存更新
|
|
||||||
profitSharingService.updateById(profitSharing);
|
|
||||||
|
|
||||||
log.info("分账成功: orderNo={}", profitSharing.getOrderNo());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 处理分账失败
|
|
||||||
*/
|
|
||||||
private void handleProfitSharingFailure(ProfitSharing profitSharing,
|
|
||||||
ProfitSharingNotification notification) {
|
|
||||||
// 1. 更新分账状态和失败原因
|
|
||||||
profitSharing.setStatus(ProfitSharingConstants.Status.FAILED);
|
|
||||||
profitSharing.setFailReason(notification.getFailReason());
|
|
||||||
profitSharing.setUpdateTime(new Date());
|
|
||||||
|
|
||||||
// 2. 判断是否需要重试
|
|
||||||
if (profitSharing.canRetry()) {
|
|
||||||
log.info("准备重试分账: orderNo={}, retryTimes={}",
|
|
||||||
profitSharing.getOrderNo(), profitSharing.getRetryTimes());
|
|
||||||
|
|
||||||
// 更新重试信息
|
|
||||||
profitSharing.setRetryTimes(profitSharing.getRetryTimes() + 1);
|
|
||||||
profitSharing.setLastRetryTime(new Date());
|
|
||||||
profitSharingService.updateById(profitSharing);
|
|
||||||
|
|
||||||
// 发起重试
|
|
||||||
profitSharingService.retryFailedProfitSharing(profitSharing.getOrderNo());
|
|
||||||
} else {
|
} else {
|
||||||
log.warn("分账失败且不再重试: orderNo={}, retryTimes={}",
|
// 其他退款状态,如退款中、失败等
|
||||||
profitSharing.getOrderNo(), profitSharing.getRetryTimes());
|
|
||||||
|
|
||||||
// 发送告警
|
|
||||||
sendFailureAlert(profitSharing);
|
|
||||||
|
|
||||||
// 保存最终状态
|
|
||||||
profitSharingService.updateById(profitSharing);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送失败告警
|
|
||||||
*/
|
|
||||||
private void sendFailureAlert(ProfitSharing profitSharing) {
|
|
||||||
try {
|
|
||||||
String alertMessage = String.format(
|
|
||||||
"分账失败告警\n" +
|
|
||||||
"订单号:%s\n" +
|
|
||||||
"交易号:%s\n" +
|
|
||||||
"失败原因:%s\n" +
|
|
||||||
"重试次数:%d\n" +
|
|
||||||
"分账金额:%d分\n" +
|
|
||||||
"失败时间:%s",
|
|
||||||
profitSharing.getOrderNo(),
|
|
||||||
profitSharing.getTransactionId(),
|
|
||||||
profitSharing.getFailReason(),
|
|
||||||
profitSharing.getRetryTimes(),
|
|
||||||
profitSharing.getQrCodeAmount(),
|
|
||||||
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
|
|
||||||
);
|
|
||||||
|
|
||||||
log.error(alertMessage);
|
|
||||||
// TODO: 实现具体的告警通知逻辑,如发送邮件、钉钉消息等
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("发送分账失败告警异常", e);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -490,28 +286,5 @@ public class WxPayController {
|
|||||||
private String buildErrorResponse() {
|
private String buildErrorResponse() {
|
||||||
return "{\"code\":\"FAIL\",\"message\":\"失败\"}";
|
return "{\"code\":\"FAIL\",\"message\":\"失败\"}";
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 分账通知解析实体类
|
|
||||||
*/
|
|
||||||
@Data
|
|
||||||
class ProfitSharingNotification {
|
|
||||||
private String mchid; // 商户号
|
|
||||||
private String transactionId; // 微信订单号
|
|
||||||
private String outOrderNo; // 商户分账单号
|
|
||||||
private String state; // 分账状态
|
|
||||||
private String failReason; // 失败原因
|
|
||||||
private List<Receiver> receivers; // 分账接收方列表
|
|
||||||
|
|
||||||
@Data
|
|
||||||
public static class Receiver {
|
|
||||||
private String type; // 分账接收方类型
|
|
||||||
private String account; // 分账接收方账号
|
|
||||||
private Long amount; // 分账金额
|
|
||||||
private String description; // 分账描述
|
|
||||||
private String result; // 分账结果
|
|
||||||
private String failReason; // 分账失败原因
|
|
||||||
private String detailId; // 分账明细单号
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-13
@@ -6,9 +6,6 @@ import com.central.common.model.Result;
|
|||||||
import com.central.user.service.WechatConfigService;
|
import com.central.user.service.WechatConfigService;
|
||||||
import com.central.wechat.entity.WechatConfig;
|
import com.central.wechat.entity.WechatConfig;
|
||||||
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.Parameters;
|
|
||||||
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 lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -23,7 +20,7 @@ import java.util.Map;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@Tag(name = "微信配置管理")
|
@Tag(name = "微信配置管理")
|
||||||
@RequestMapping("/wechat/config")
|
@RequestMapping("/wechat/config")
|
||||||
public class SysWechatConfigController {
|
public class WechatConfigController {
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
private WechatConfigService wechatConfigService;
|
private WechatConfigService wechatConfigService;
|
||||||
@@ -43,10 +40,10 @@ public class SysWechatConfigController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "根据类型和租户ID查询微信配置")
|
@Operation(summary = "根据类型和租户ID查询微信配置")
|
||||||
@GetMapping("/{type}")
|
@GetMapping("/type/{type}")
|
||||||
public Result<WechatConfig> getConfig(@PathVariable String type, @RequestParam String tenantId) {
|
public WechatConfig getConfig(@PathVariable String type, @RequestParam String tenantId) {
|
||||||
WechatConfig config = wechatConfigService.getConfig(type, tenantId);
|
WechatConfig config = wechatConfigService.getConfig(type, tenantId);
|
||||||
return Result.succeed(config);
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "保存微信配置")
|
@Operation(summary = "保存微信配置")
|
||||||
@@ -74,23 +71,23 @@ public class SysWechatConfigController {
|
|||||||
|
|
||||||
@Operation(summary = "获取服务商配置")
|
@Operation(summary = "获取服务商配置")
|
||||||
@GetMapping("/service/{tenantId}")
|
@GetMapping("/service/{tenantId}")
|
||||||
public Result<WechatConfig> getServiceConfig(@PathVariable String tenantId) {
|
public WechatConfig getServiceConfig(@PathVariable String tenantId) {
|
||||||
WechatConfig config = wechatConfigService.getServiceConfig(tenantId);
|
WechatConfig config = wechatConfigService.getServiceConfig(tenantId);
|
||||||
return Result.succeed(config);
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "根据子商户号查询配置")
|
@Operation(summary = "根据子商户号查询配置")
|
||||||
@GetMapping("/sub/{subMchId}")
|
@GetMapping("/sub/{subMchId}")
|
||||||
public Result<WechatConfig> getConfigBySubMchId(@PathVariable String subMchId) {
|
public WechatConfig getConfigBySubMchId(@PathVariable String subMchId) {
|
||||||
WechatConfig config = wechatConfigService.getConfigBySubMchId(subMchId);
|
WechatConfig config = wechatConfigService.getConfigBySubMchId(subMchId);
|
||||||
return Result.succeed(config);
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取指定服务商下的所有子商户配置")
|
@Operation(summary = "获取指定服务商下的所有子商户配置")
|
||||||
@GetMapping("/submerchants/{serviceMchId}")
|
@GetMapping("/submerchants/{serviceMchId}")
|
||||||
public Result<java.util.List<WechatConfig>> getSubMerchantConfigs(@PathVariable String serviceMchId) {
|
public java.util.List<WechatConfig> getSubMerchantConfigs(@PathVariable String serviceMchId) {
|
||||||
java.util.List<WechatConfig> configs = wechatConfigService.getSubMerchantConfigs(serviceMchId);
|
java.util.List<WechatConfig> configs = wechatConfigService.getSubMerchantConfigs(serviceMchId);
|
||||||
return Result.succeed(configs);
|
return configs;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "保存服务商配置")
|
@Operation(summary = "保存服务商配置")
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
package com.central.user.model;
|
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.IdType;
|
|
||||||
import com.baomidou.mybatisplus.annotation.TableId;
|
|
||||||
import com.baomidou.mybatisplus.annotation.TableName;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@TableName("sys_wechat_config")
|
|
||||||
public class SysWechatConfig {
|
|
||||||
|
|
||||||
@TableId(type = IdType.AUTO)
|
|
||||||
private Long id;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 租户ID
|
|
||||||
*/
|
|
||||||
private String tenantId;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 配置类型:MP-公众号,MINI-小程序,PAY-支付
|
|
||||||
*/
|
|
||||||
private String type;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 商户ID
|
|
||||||
*/
|
|
||||||
private String merchantId;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 应用ID
|
|
||||||
*/
|
|
||||||
private String appId;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 应用密钥
|
|
||||||
*/
|
|
||||||
private String appSecret;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 商户API密钥
|
|
||||||
*/
|
|
||||||
private String mchKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 商户证书序列号
|
|
||||||
*/
|
|
||||||
private String mchSerialNo;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 商户私钥文件路径
|
|
||||||
*/
|
|
||||||
private String privateKeyPath;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* APIv3密钥
|
|
||||||
*/
|
|
||||||
private String apiV3Key;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 支付回调地址
|
|
||||||
*/
|
|
||||||
private String notifyUrl;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 微信公众号token
|
|
||||||
*/
|
|
||||||
private String token;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 微信公众号aesKey
|
|
||||||
*/
|
|
||||||
private String aesKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 支付成功通知模板ID
|
|
||||||
*/
|
|
||||||
private String paymentSuccessTemplateId;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 视频处理完成通知模板ID
|
|
||||||
*/
|
|
||||||
private String videoCompleteTemplateId;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 视频处理失败通知模板ID
|
|
||||||
*/
|
|
||||||
private String videoFailTemplateId;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 是否启用分账
|
|
||||||
*/
|
|
||||||
private Boolean profitSharingEnabled;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 是否启用异步处理
|
|
||||||
*/
|
|
||||||
private Boolean asyncEnabled;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 异步处理线程池大小
|
|
||||||
*/
|
|
||||||
private Integer asyncPoolSize;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 状态:0-禁用,1-启用
|
|
||||||
*/
|
|
||||||
private Integer status;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 备注
|
|
||||||
*/
|
|
||||||
private String remark;
|
|
||||||
}
|
|
||||||
+1
-1
@@ -48,7 +48,7 @@ public class WechatConfigServiceImpl extends ServiceImpl<WechatConfigMapper, Wec
|
|||||||
@Override
|
@Override
|
||||||
public WechatConfig getConfigBySerialNumber(String serialNumber) {
|
public WechatConfig getConfigBySerialNumber(String serialNumber) {
|
||||||
return getOne(new LambdaQueryWrapper<WechatConfig>()
|
return getOne(new LambdaQueryWrapper<WechatConfig>()
|
||||||
.eq(WechatConfig::getMchSerialNo, serialNumber)
|
.eq(WechatConfig::getSerialNumber, serialNumber)
|
||||||
.eq(WechatConfig::getStatus, 1));
|
.eq(WechatConfig::getStatus, 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+5
@@ -49,6 +49,11 @@ public class WechatConfig {
|
|||||||
*/
|
*/
|
||||||
private String mchSerialNo;
|
private String mchSerialNo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 微信平台证书序列号(用于回调验证)
|
||||||
|
*/
|
||||||
|
private String serialNumber;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 商户私钥文件路径
|
* 商户私钥文件路径
|
||||||
*/
|
*/
|
||||||
|
|||||||
+1
-1
@@ -22,7 +22,7 @@ public interface WechatConfigService {
|
|||||||
* @param type
|
* @param type
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
@GetMapping(value = "/wechat/config/{type}")
|
@GetMapping(value = "/wechat/config/type/{type}")
|
||||||
WechatConfig getConfig(@PathVariable("type") String type,@RequestParam("tenantId") String tenantId);
|
WechatConfig getConfig(@PathVariable("type") String type,@RequestParam("tenantId") String tenantId);
|
||||||
|
|
||||||
@GetMapping(value = "/wechat/config/app/{id}")
|
@GetMapping(value = "/wechat/config/app/{id}")
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@ public class WechatConfigServiceFallbackFactory implements FallbackFactory<Wecha
|
|||||||
@Override
|
@Override
|
||||||
public WechatConfig getConfig(String type,String tenantId) {
|
public WechatConfig getConfig(String type,String tenantId) {
|
||||||
|
|
||||||
return new WechatConfig();
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -0,0 +1,606 @@
|
|||||||
|
# WebSocket接口协议文档
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
本文档描述了设备运维平台中使用的WebSocket接口协议,用于实时设备监控、控制和数据通信。
|
||||||
|
|
||||||
|
## 服务器信息
|
||||||
|
|
||||||
|
- **WebSocket服务器地址**: `ws://119.45.169.13:8848/messaging/{token}`
|
||||||
|
- **Token获取地址**: `http://119.45.169.13:9900/api-device/token/query`
|
||||||
|
- **Token有效期**: 默认3600秒(1小时),可配置
|
||||||
|
|
||||||
|
## 连接流程
|
||||||
|
|
||||||
|
### 1. 获取Token
|
||||||
|
|
||||||
|
**请求方式**: GET
|
||||||
|
**URL**: `/api-device/token/query`
|
||||||
|
**参数**:
|
||||||
|
- `expires`: Token有效期(秒),可选,默认3600
|
||||||
|
|
||||||
|
**响应格式**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"resp_code": 0,
|
||||||
|
"resp_msg": "success",
|
||||||
|
"data": {
|
||||||
|
"result": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
|
||||||
|
"message": "success",
|
||||||
|
"status": 200,
|
||||||
|
"timestamp": 1640995200000,
|
||||||
|
"expires": 3600
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 建立WebSocket连接
|
||||||
|
|
||||||
|
**连接URL**: `ws://119.45.169.13:8848/messaging/{token}`
|
||||||
|
|
||||||
|
**连接状态**:
|
||||||
|
- `WebSocket.OPEN`: 连接已建立
|
||||||
|
- `WebSocket.CLOSED`: 连接已关闭
|
||||||
|
- `WebSocket.CONNECTING`: 正在连接
|
||||||
|
- `WebSocket.CLOSING`: 正在关闭
|
||||||
|
|
||||||
|
## 消息格式
|
||||||
|
|
||||||
|
### 通用消息结构
|
||||||
|
|
||||||
|
所有WebSocket消息都遵循以下JSON格式:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "消息类型",
|
||||||
|
"topic": "主题路径",
|
||||||
|
"parameter": {
|
||||||
|
"messageType": "消息类型",
|
||||||
|
"properties": {
|
||||||
|
"method": "方法名",
|
||||||
|
"data": {}
|
||||||
|
},
|
||||||
|
"headers": {
|
||||||
|
"async": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": "唯一标识符"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 消息类型
|
||||||
|
|
||||||
|
### 1. 订阅消息 (sub)
|
||||||
|
|
||||||
|
用于订阅设备状态、属性上报、事件等消息。
|
||||||
|
|
||||||
|
#### 设备属性上报订阅
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device/*/*/message/property/report",
|
||||||
|
"parameter": {},
|
||||||
|
"id": "sub_property_all_{timestamp}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 设备事件订阅
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device/*/*/message/event/fire_alarm",
|
||||||
|
"parameter": {},
|
||||||
|
"id": "sub_event_all_{timestamp}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 设备上线状态订阅
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device/*/*/online",
|
||||||
|
"parameter": {},
|
||||||
|
"id": "sub_online_all_{timestamp}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 设备离线状态订阅
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device/*/*/offline",
|
||||||
|
"parameter": {},
|
||||||
|
"id": "sub_offline_all_{timestamp}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 指定设备订阅
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device/*/{deviceSn}/message/property/report",
|
||||||
|
"parameter": {},
|
||||||
|
"id": "property-sub-{timestamp}-{deviceSn}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 取消订阅消息 (unsub)
|
||||||
|
|
||||||
|
用于取消已订阅的消息。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "unsub",
|
||||||
|
"id": "订阅ID"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 设备控制消息
|
||||||
|
|
||||||
|
用于向设备发送控制指令。
|
||||||
|
|
||||||
|
#### 通用控制指令
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device-message-sender/D-Dock2/{deviceSn}",
|
||||||
|
"parameter": {
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"properties": {
|
||||||
|
"method": "方法名",
|
||||||
|
"data": {}
|
||||||
|
},
|
||||||
|
"headers": {
|
||||||
|
"async": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": "control_{method}_{deviceSn}_{timestamp}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 摇杆控制指令
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device-message-sender/D-Dock2/{deviceSn}",
|
||||||
|
"parameter": {
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"properties": {
|
||||||
|
"method": "stick_control",
|
||||||
|
"data": {
|
||||||
|
"roll": 1024, // 右手左右控制(范围:0-2048,1024为中立位)
|
||||||
|
"pitch": 1024, // 右手上下控制(范围:0-2048,1024为中立位)
|
||||||
|
"throttle": 1024, // 左手上下控制(范围:0-2048,1024为中立位)
|
||||||
|
"yaw": 1024, // 左手左右控制(范围:1024±100)
|
||||||
|
"gimbal_pitch": 1024 // 云台画面上下划(范围:0-2048,1024为中立位)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"headers": {
|
||||||
|
"async": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": "control_stick_control_{deviceSn}_{timestamp}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 心跳消息 (ping/pong)
|
||||||
|
|
||||||
|
用于保持连接活跃。
|
||||||
|
|
||||||
|
**发送心跳**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "ping",
|
||||||
|
"timestamp": 1640995200000
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**心跳响应**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "pong"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 响应消息
|
||||||
|
|
||||||
|
### 1. 订阅结果响应
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "result",
|
||||||
|
"topic": "/device/{productId}/{deviceSn}/message/property/report",
|
||||||
|
"payload": {
|
||||||
|
"headers": {
|
||||||
|
"deviceName": "设备名称",
|
||||||
|
"productName": "产品名称",
|
||||||
|
"productId": "产品ID"
|
||||||
|
},
|
||||||
|
"messageId": "消息ID",
|
||||||
|
"deviceId": "设备ID",
|
||||||
|
"timestamp": 1640995200000,
|
||||||
|
"data": {
|
||||||
|
"data": {
|
||||||
|
// 环境数据
|
||||||
|
"temperature": 25.5,
|
||||||
|
"humidity": 60.2,
|
||||||
|
"wind_speed": 3.2,
|
||||||
|
"rainfall": 0.0,
|
||||||
|
"environment_temperature": 26.1,
|
||||||
|
"latitude": 39.9042,
|
||||||
|
"longitude": 116.4074,
|
||||||
|
"height": 100.5,
|
||||||
|
"heading": 180.0,
|
||||||
|
|
||||||
|
// 设备状态
|
||||||
|
"drone_charge_state": {
|
||||||
|
"capacity_percent": 85,
|
||||||
|
"state": 1
|
||||||
|
},
|
||||||
|
"position_state": {
|
||||||
|
"is_calibration": 0,
|
||||||
|
"rtk_number": 8,
|
||||||
|
"gps_number": 12,
|
||||||
|
"is_fixed": 1,
|
||||||
|
"quality": 95
|
||||||
|
},
|
||||||
|
"network_state": {
|
||||||
|
"rate": 1000,
|
||||||
|
"type": 1,
|
||||||
|
"quality": 90
|
||||||
|
},
|
||||||
|
"drone_in_dock": 1,
|
||||||
|
|
||||||
|
// 飞行任务数据
|
||||||
|
"flighttask_step_code": 0,
|
||||||
|
"sdr": {
|
||||||
|
"frequency_band": 2,
|
||||||
|
"up_quality": 95,
|
||||||
|
"down_quality": 92
|
||||||
|
},
|
||||||
|
"tilt_angle": {
|
||||||
|
"valid": 1,
|
||||||
|
"value": 0.5
|
||||||
|
},
|
||||||
|
"wireless_link": {
|
||||||
|
"sdr_link_state": 1,
|
||||||
|
"4g_freq_band": 1,
|
||||||
|
"4g_quality": 85,
|
||||||
|
"link_workmode": 1,
|
||||||
|
"sdr_quality": 90,
|
||||||
|
"4g_uav_quality": 88,
|
||||||
|
"sdr_freq_band": 2,
|
||||||
|
"4g_link_state": 1,
|
||||||
|
"4g_gnd_quality": 87,
|
||||||
|
"dongle_number": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"deviceId": "设备ID",
|
||||||
|
"timestamp": 1640995200000
|
||||||
|
},
|
||||||
|
"messageType": "REPORT_PROPERTY"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 设备事件响应
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "result",
|
||||||
|
"topic": "/device/{productId}/{deviceSn}/message/event/fire_alarm",
|
||||||
|
"payload": {
|
||||||
|
"headers": {
|
||||||
|
"deviceName": "设备名称",
|
||||||
|
"productName": "产品名称",
|
||||||
|
"productId": "产品ID"
|
||||||
|
},
|
||||||
|
"messageId": "消息ID",
|
||||||
|
"deviceId": "设备ID",
|
||||||
|
"timestamp": 1640995200000,
|
||||||
|
"event": "fire_alarm",
|
||||||
|
"data": {
|
||||||
|
"alarm_level": 1,
|
||||||
|
"alarm_type": "smoke",
|
||||||
|
"location": "building_1",
|
||||||
|
"description": "烟雾报警"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 设备状态响应
|
||||||
|
|
||||||
|
#### 设备上线
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "result",
|
||||||
|
"topic": "/device/{productId}/{deviceSn}/online",
|
||||||
|
"payload": {
|
||||||
|
"deviceId": "设备ID",
|
||||||
|
"timestamp": 1640995200000,
|
||||||
|
"status": "online"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 设备离线
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "result",
|
||||||
|
"topic": "/device/{productId}/{deviceSn}/offline",
|
||||||
|
"payload": {
|
||||||
|
"deviceId": "设备ID",
|
||||||
|
"timestamp": 1640995200000,
|
||||||
|
"status": "offline"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 主题路径说明
|
||||||
|
|
||||||
|
### 主题格式
|
||||||
|
|
||||||
|
```
|
||||||
|
/device/{productId}/{deviceSn}/{messageType}/{eventType}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 主题示例
|
||||||
|
|
||||||
|
- `/device/D-Dock2/DEVICE001/message/property/report` - 设备属性上报
|
||||||
|
- `/device/D-Dock2/DEVICE001/message/event/fire_alarm` - 火警事件
|
||||||
|
- `/device/D-Dock2/DEVICE001/online` - 设备上线
|
||||||
|
- `/device/D-Dock2/DEVICE001/offline` - 设备离线
|
||||||
|
|
||||||
|
### 通配符使用
|
||||||
|
|
||||||
|
- `*` - 匹配任意字符串
|
||||||
|
- `/device/*/*/message/property/report` - 订阅所有设备的属性上报
|
||||||
|
- `/device/*/*/online` - 订阅所有设备的上线状态
|
||||||
|
|
||||||
|
## 错误处理
|
||||||
|
|
||||||
|
### 连接错误
|
||||||
|
|
||||||
|
当WebSocket连接出现错误时,系统会自动尝试重连:
|
||||||
|
|
||||||
|
1. 连接断开后等待5秒
|
||||||
|
2. 自动重新获取Token
|
||||||
|
3. 重新建立WebSocket连接
|
||||||
|
4. 重新订阅之前的消息
|
||||||
|
|
||||||
|
### 消息错误
|
||||||
|
|
||||||
|
如果消息格式错误或处理失败,服务器会返回错误响应:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "error",
|
||||||
|
"id": "消息ID",
|
||||||
|
"error": {
|
||||||
|
"code": "ERROR_CODE",
|
||||||
|
"message": "错误描述"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
### 1. 连接管理
|
||||||
|
|
||||||
|
- 实现自动重连机制
|
||||||
|
- 定期发送心跳保持连接
|
||||||
|
- 在页面卸载时正确关闭连接
|
||||||
|
|
||||||
|
### 2. 消息处理
|
||||||
|
|
||||||
|
- 为每个消息生成唯一的ID
|
||||||
|
- 实现消息超时处理
|
||||||
|
- 正确处理异步消息
|
||||||
|
|
||||||
|
### 3. 错误处理
|
||||||
|
|
||||||
|
- 实现完善的错误处理机制
|
||||||
|
- 记录错误日志便于调试
|
||||||
|
- 提供用户友好的错误提示
|
||||||
|
|
||||||
|
### 4. 性能优化
|
||||||
|
|
||||||
|
- 合理使用通配符订阅
|
||||||
|
- 及时取消不需要的订阅
|
||||||
|
- 避免频繁发送控制指令
|
||||||
|
|
||||||
|
## 示例代码
|
||||||
|
|
||||||
|
### JavaScript/TypeScript 示例
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
class WebSocketClient {
|
||||||
|
private ws: WebSocket | null = null;
|
||||||
|
private token: string = '';
|
||||||
|
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||||
|
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
// 获取Token
|
||||||
|
async getToken(): Promise<string> {
|
||||||
|
const response = await fetch('/api-device/token/query?expires=3600');
|
||||||
|
const data = await response.json();
|
||||||
|
if (data.resp_code === 0) {
|
||||||
|
return data.data.result;
|
||||||
|
}
|
||||||
|
throw new Error('获取Token失败');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 连接WebSocket
|
||||||
|
async connect(): Promise<void> {
|
||||||
|
try {
|
||||||
|
this.token = await this.getToken();
|
||||||
|
const wsUrl = `ws://119.45.169.13:8848/messaging/${this.token}`;
|
||||||
|
|
||||||
|
this.ws = new WebSocket(wsUrl);
|
||||||
|
|
||||||
|
this.ws.onopen = () => {
|
||||||
|
console.log('WebSocket连接已建立');
|
||||||
|
this.startHeartbeat();
|
||||||
|
this.subscribeToMessages();
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ws.onmessage = (event) => {
|
||||||
|
const data = JSON.parse(event.data);
|
||||||
|
this.handleMessage(data);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ws.onclose = () => {
|
||||||
|
console.log('WebSocket连接已关闭');
|
||||||
|
this.scheduleReconnect();
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ws.onerror = (error) => {
|
||||||
|
console.error('WebSocket错误:', error);
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('连接失败:', error);
|
||||||
|
this.scheduleReconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送消息
|
||||||
|
sendMessage(message: any): void {
|
||||||
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
||||||
|
this.ws.send(JSON.stringify(message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 订阅消息
|
||||||
|
subscribeToMessages(): void {
|
||||||
|
const subscriptions = [
|
||||||
|
{
|
||||||
|
type: 'sub',
|
||||||
|
topic: '/device/*/*/message/property/report',
|
||||||
|
id: `sub_property_${Date.now()}`
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'sub',
|
||||||
|
topic: '/device/*/*/online',
|
||||||
|
id: `sub_online_${Date.now()}`
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
subscriptions.forEach(sub => this.sendMessage(sub));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送控制指令
|
||||||
|
sendControlCommand(deviceSn: string, method: string, data: any = {}): void {
|
||||||
|
const message = {
|
||||||
|
type: 'sub',
|
||||||
|
topic: `/device-message-sender/D-Dock2/${deviceSn}`,
|
||||||
|
parameter: {
|
||||||
|
messageType: 'WRITE_PROPERTY',
|
||||||
|
properties: { method, data },
|
||||||
|
headers: { async: false }
|
||||||
|
},
|
||||||
|
id: `control_${method}_${deviceSn}_${Date.now()}`
|
||||||
|
};
|
||||||
|
|
||||||
|
this.sendMessage(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 心跳检测
|
||||||
|
startHeartbeat(): void {
|
||||||
|
this.heartbeatTimer = setInterval(() => {
|
||||||
|
this.sendMessage({
|
||||||
|
type: 'ping',
|
||||||
|
timestamp: Date.now()
|
||||||
|
});
|
||||||
|
}, 30000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重连机制
|
||||||
|
scheduleReconnect(): void {
|
||||||
|
if (this.reconnectTimer) {
|
||||||
|
clearTimeout(this.reconnectTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.reconnectTimer = setTimeout(() => {
|
||||||
|
console.log('尝试重新连接...');
|
||||||
|
this.connect();
|
||||||
|
}, 5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理消息
|
||||||
|
handleMessage(data: any): void {
|
||||||
|
switch (data.type) {
|
||||||
|
case 'result':
|
||||||
|
this.handleResultMessage(data);
|
||||||
|
break;
|
||||||
|
case 'pong':
|
||||||
|
console.log('收到心跳响应');
|
||||||
|
break;
|
||||||
|
case 'error':
|
||||||
|
console.error('收到错误消息:', data.error);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
console.log('收到未知消息:', data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理结果消息
|
||||||
|
handleResultMessage(data: any): void {
|
||||||
|
const { topic, payload } = data;
|
||||||
|
|
||||||
|
if (topic.includes('/message/property/report')) {
|
||||||
|
console.log('设备属性上报:', payload);
|
||||||
|
} else if (topic.includes('/online')) {
|
||||||
|
console.log('设备上线:', payload);
|
||||||
|
} else if (topic.includes('/offline')) {
|
||||||
|
console.log('设备离线:', payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭连接
|
||||||
|
disconnect(): void {
|
||||||
|
if (this.heartbeatTimer) {
|
||||||
|
clearInterval(this.heartbeatTimer);
|
||||||
|
}
|
||||||
|
if (this.reconnectTimer) {
|
||||||
|
clearTimeout(this.reconnectTimer);
|
||||||
|
}
|
||||||
|
if (this.ws) {
|
||||||
|
this.ws.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用示例
|
||||||
|
const wsClient = new WebSocketClient();
|
||||||
|
wsClient.connect();
|
||||||
|
|
||||||
|
// 发送控制指令
|
||||||
|
wsClient.sendControlCommand('DEVICE001', 'stick_control', {
|
||||||
|
roll: 1024,
|
||||||
|
pitch: 1024,
|
||||||
|
throttle: 1024,
|
||||||
|
yaw: 1024
|
||||||
|
});
|
||||||
|
|
||||||
|
// 页面卸载时关闭连接
|
||||||
|
window.addEventListener('beforeunload', () => {
|
||||||
|
wsClient.disconnect();
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. **Token管理**: Token有过期时间,需要定期刷新
|
||||||
|
2. **连接稳定性**: 实现自动重连和心跳机制
|
||||||
|
3. **消息处理**: 正确处理各种类型的消息
|
||||||
|
4. **错误处理**: 完善的错误处理机制
|
||||||
|
5. **资源清理**: 及时清理定时器和连接
|
||||||
|
6. **安全性**: 确保Token的安全性,不要在客户端存储敏感信息
|
||||||
|
|
||||||
|
## 更新日志
|
||||||
|
|
||||||
|
- **v1.0.0**: 初始版本,包含基本的连接、订阅、控制功能
|
||||||
|
- **v1.1.0**: 添加心跳机制和自动重连
|
||||||
|
- **v1.2.0**: 完善错误处理和消息格式
|
||||||
|
- **v1.3.0**: 添加设备状态监控和事件处理
|
||||||
@@ -9,43 +9,43 @@
|
|||||||
export default {
|
export default {
|
||||||
dev: {
|
dev: {
|
||||||
'/api-uaa/': {
|
'/api-uaa/': {
|
||||||
target: 'http://119.45.169.13:9900',
|
// target: 'http://119.45.169.13:9900',
|
||||||
// target: 'http://127.0.0.1:9900',
|
target: 'http://127.0.0.1:9900',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
'/api-user/': {
|
'/api-user/': {
|
||||||
target: 'http://119.45.169.13:9900',
|
// target: 'http://119.45.169.13:9900',
|
||||||
// target: 'http://127.0.0.1:9900',
|
target: 'http://127.0.0.1:9900',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
'/api-log/': {
|
'/api-log/': {
|
||||||
target: 'http://119.45.169.13:9900',
|
// target: 'http://119.45.169.13:9900',
|
||||||
// target: 'http://127.0.0.1:9900',
|
target: 'http://127.0.0.1:9900',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
'/api-search/': {
|
'/api-search/': {
|
||||||
target: 'http://119.45.169.13:9900',
|
// target: 'http://119.45.169.13:9900',
|
||||||
// target: 'http://127.0.0.1:9900',
|
target: 'http://127.0.0.1:9900',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
'/api-generator/': {
|
'/api-generator/': {
|
||||||
target: 'http://119.45.169.13:9900',
|
// target: 'http://119.45.169.13:9900',
|
||||||
// target: 'http://127.0.0.1:9900',
|
target: 'http://127.0.0.1:9900',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
'/api-file/': {
|
'/api-file/': {
|
||||||
target: 'http://119.45.169.13:9900',
|
// target: 'http://119.45.169.13:9900',
|
||||||
// target: 'http://127.0.0.1:9900',
|
target: 'http://127.0.0.1:9900',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
'/api-order/': {
|
'/api-order/': {
|
||||||
target: 'http://119.45.169.13:9900',
|
// target: 'http://119.45.169.13:9900',
|
||||||
// target: 'http://127.0.0.1:9900',
|
target: 'http://127.0.0.1:9900',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
'/api-device/': {
|
'/api-device/': {
|
||||||
target: 'http://119.45.169.13:9900',
|
// target: 'http://119.45.169.13:9900',
|
||||||
// target: 'http://127.0.0.1:9900',
|
target: 'http://127.0.0.1:9900',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
+199
@@ -0,0 +1,199 @@
|
|||||||
|
# 微信平台证书序列号配置说明
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
在微信支付回调中,微信会通过请求头 `Wechatpay-Serial` 传递平台证书的序列号,用于验证回调请求的签名。为了支持多个平台证书的场景,系统新增了 `serialNumber` 字段来存储微信平台证书的序列号。
|
||||||
|
|
||||||
|
## 字段说明
|
||||||
|
|
||||||
|
### serialNumber 字段
|
||||||
|
- **用途**: 存储微信平台证书的序列号
|
||||||
|
- **来源**: 微信支付回调请求头中的 `Wechatpay-Serial` 字段
|
||||||
|
- **作用**: 用于快速定位对应的微信配置信息
|
||||||
|
- **支持**: 一个商户可以配置多个平台证书,通过序列号区分
|
||||||
|
|
||||||
|
## 配置流程
|
||||||
|
|
||||||
|
### 1. 获取微信平台证书序列号
|
||||||
|
|
||||||
|
#### 方法一:通过微信支付API获取
|
||||||
|
```bash
|
||||||
|
# 获取平台证书列表
|
||||||
|
curl -X GET "https://api.mch.weixin.qq.com/v3/certificates" \
|
||||||
|
-H "Accept: application/json" \
|
||||||
|
-H "Authorization: WECHATPAY2-SHA256-RSA2048 ..."
|
||||||
|
```
|
||||||
|
|
||||||
|
响应示例:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"serial_no": "5157F09EFDC096DE15EBE81A47057A7232F1B8E1",
|
||||||
|
"effective_time": "2018-06-08T10:34:56+08:00",
|
||||||
|
"expire_time": "2023-06-08T10:34:56+08:00",
|
||||||
|
"encrypt_certificate": {
|
||||||
|
"algorithm": "AEAD_AES_256_GCM",
|
||||||
|
"nonce": "61f9c719728a",
|
||||||
|
"associated_data": "certificate",
|
||||||
|
"ciphertext": "..."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 方法二:从回调请求头获取
|
||||||
|
在微信支付回调时,请求头中会包含:
|
||||||
|
```
|
||||||
|
Wechatpay-Serial: 5157F09EFDC096DE15EBE81A47057A7232F1B8E1
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 配置到系统
|
||||||
|
|
||||||
|
#### 通过管理后台配置
|
||||||
|
1. 登录管理后台
|
||||||
|
2. 进入"微信配置管理"
|
||||||
|
3. 选择对应的租户和配置类型
|
||||||
|
4. 在"微信平台证书序列号"字段中填入获取到的序列号
|
||||||
|
5. 保存配置
|
||||||
|
|
||||||
|
#### 通过API配置
|
||||||
|
```http
|
||||||
|
PUT /wechat/config
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"tenantId": "webApp",
|
||||||
|
"type": "PAY",
|
||||||
|
"serialNumber": "5157F09EFDC096DE15EBE81A47057A7232F1B8E1",
|
||||||
|
"merchantId": "1900000109",
|
||||||
|
"appId": "wx1234567890abcdef",
|
||||||
|
"mchSerialNo": "1234567890ABCDEF",
|
||||||
|
"privateKey": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----",
|
||||||
|
"apiV3Key": "your_api_v3_key",
|
||||||
|
"notifyUrl": "https://your.domain.com/notify",
|
||||||
|
"status": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 回调处理流程
|
||||||
|
|
||||||
|
### 1. 接收回调请求
|
||||||
|
```java
|
||||||
|
@PostMapping("/pay/notify")
|
||||||
|
public String handleCallback(@RequestHeader("Wechatpay-Signature") String signature,
|
||||||
|
@RequestHeader("Wechatpay-Timestamp") String timestamp,
|
||||||
|
@RequestHeader("Wechatpay-Nonce") String nonce,
|
||||||
|
@RequestHeader("Wechatpay-Serial") String serial,
|
||||||
|
@RequestBody String body) {
|
||||||
|
// serial 参数就是微信平台证书的序列号
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 根据序列号获取配置
|
||||||
|
```java
|
||||||
|
// 根据证书序列号获取配置
|
||||||
|
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
|
||||||
|
if (config == null) {
|
||||||
|
log.error("未找到对应的微信配置,序列号: {}", serial);
|
||||||
|
return "{\"code\":\"FAIL\",\"message\":\"配置不存在\"}";
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 验证回调签名
|
||||||
|
```java
|
||||||
|
// 创建通知解析器
|
||||||
|
NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser(config.getTenantId());
|
||||||
|
|
||||||
|
// 构建请求参数
|
||||||
|
RequestParam requestParam = new RequestParam
|
||||||
|
.Builder()
|
||||||
|
.body(body)
|
||||||
|
.nonce(nonce)
|
||||||
|
.signature(signature)
|
||||||
|
.serialNumber(serial) // 使用平台证书序列号
|
||||||
|
.timestamp(timestamp)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// 解析通知
|
||||||
|
Transaction transaction = notificationParser.parse(requestParam, Transaction.class);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 多证书支持
|
||||||
|
|
||||||
|
### 场景说明
|
||||||
|
当一个商户需要支持多个平台证书时(例如证书轮换),可以通过配置多个 `serialNumber` 来支持:
|
||||||
|
|
||||||
|
### 配置示例
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"tenantId": "webApp",
|
||||||
|
"type": "PAY",
|
||||||
|
"serialNumber": "5157F09EFDC096DE15EBE81A47057A7232F1B8E1",
|
||||||
|
"merchantId": "1900000109",
|
||||||
|
"appId": "wx1234567890abcdef",
|
||||||
|
"status": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"tenantId": "webApp",
|
||||||
|
"type": "PAY",
|
||||||
|
"serialNumber": "5157F09EFDC096DE15EBE81A47057A7232F1B8E2",
|
||||||
|
"merchantId": "1900000109",
|
||||||
|
"appId": "wx1234567890abcdef",
|
||||||
|
"status": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 处理逻辑
|
||||||
|
系统会根据回调请求中的 `Wechatpay-Serial` 自动匹配对应的配置:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Override
|
||||||
|
public WechatConfig getConfigBySerialNumber(String serialNumber) {
|
||||||
|
return getOne(new LambdaQueryWrapper<WechatConfig>()
|
||||||
|
.eq(WechatConfig::getSerialNumber, serialNumber)
|
||||||
|
.eq(WechatConfig::getStatus, 1));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
### 1. 证书有效期
|
||||||
|
- 微信平台证书有有效期限制
|
||||||
|
- 需要在证书过期前更新配置
|
||||||
|
- 建议配置证书过期提醒
|
||||||
|
|
||||||
|
### 2. 序列号唯一性
|
||||||
|
- 每个平台证书的序列号是唯一的
|
||||||
|
- 同一租户下不能配置重复的序列号
|
||||||
|
- 建议在配置时进行唯一性校验
|
||||||
|
|
||||||
|
### 3. 配置验证
|
||||||
|
- 配置完成后建议进行测试
|
||||||
|
- 可以通过模拟回调请求验证配置是否正确
|
||||||
|
- 确保回调处理逻辑能正常工作
|
||||||
|
|
||||||
|
### 4. 日志记录
|
||||||
|
- 建议记录证书序列号的使用情况
|
||||||
|
- 便于排查问题和监控系统状态
|
||||||
|
- 可以统计各证书的使用频率
|
||||||
|
|
||||||
|
## 错误处理
|
||||||
|
|
||||||
|
### 常见错误
|
||||||
|
1. **配置不存在**: 回调请求中的序列号在系统中找不到对应配置
|
||||||
|
2. **证书过期**: 使用的平台证书已过期
|
||||||
|
3. **签名验证失败**: 回调请求的签名验证失败
|
||||||
|
|
||||||
|
### 处理建议
|
||||||
|
1. 记录详细的错误日志
|
||||||
|
2. 提供配置检查工具
|
||||||
|
3. 实现自动化的证书更新机制
|
||||||
|
4. 建立监控告警机制
|
||||||
Reference in New Issue
Block a user