Test #2

Merged
duzhichao merged 34 commits from test into prod 2026-11-19 07:44:04 +00:00
8 changed files with 870 additions and 118 deletions
Showing only changes of commit ca41fe080c - Show all commits
+7 -1
View File
@@ -106,7 +106,13 @@
"Bash(grep -rn \"alipay\" zlt-business/order-center/src/main/resources/sql/)",
"Bash(ls zlt-business/order-center/src/main/resources/sql/)",
"WebFetch(domain:opendocs.alipay.com)",
"Bash(mvn -v)"
"Bash(mvn -v)",
"WebFetch(domain:mvnrepository.com)",
"WebFetch(domain:raw.githubusercontent.com)",
"Bash(xargs -I{} jar tf {})",
"Bash(locate alipay-sdk-java *)",
"Bash(jar tf *)",
"Bash(javap *)"
],
"deny": [],
"ask": []
@@ -6,6 +6,7 @@ import com.central.common.feign.UserService;
import com.central.common.model.*;
import com.central.order.constants.EditTaskStatus;
import com.central.order.enums.OrderStatus;
import com.central.order.enums.PayTypeEnum;
import com.central.order.feign.FileCenterService;
import com.central.order.model.*;
import com.central.order.model.params.FileDownloadRequest;
@@ -93,6 +94,9 @@ public class OrderFileController {
@Autowired
private WxMiniSubscribeService wxMiniSubscribeService;
@Autowired
private AlipayMiniSubscribeService alipayMiniSubscribeService;
@Autowired
private IEditTaskService editTaskService;
@@ -418,28 +422,37 @@ public class OrderFileController {
* @param tourism
*/
private void sendMessageForResouresUploaded(Order order, Tourism tourism) {
// 发送小程序订阅消息,用户素材上传完成
SysUser sysUser = userCenterService.findUserById(order.getUserId());
String orderName = tourism.getTourismName();
String pageUrl = "pages/album/album";
// 处理支付时间为空的情况
String payTimeStr = "";
if (order.getPayTime() != null) {
payTimeStr = DateUtils.sdf.format(order.getPayTime());
}
if (sysUser.getOpenId() != null) {
String tip = "素材上传完成";
String orderName = tourism.getTourismName();
String pageUrl = "pages/album/album";
// 处理支付时间为空的情况
String payTimeStr = "";
if (order.getPayTime() != null) {
payTimeStr = DateUtils.sdf.format(order.getPayTime());
// 根据 payType 发送小程序通知(微信 or 支付宝)
Integer payType = order.getPayType();
if (PayTypeEnum.WECHAT_PAY.getCode().equals(payType)) {
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser.getOpenId() != null) {
wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(),
orderName,
"素材上传完成",
order.getOrderNo(),
payTimeStr,
"",
pageUrl
);
}
} else if (PayTypeEnum.ALIPAY_PAY.getCode().equals(payType)) {
if (order.getTenantId() != null && !order.getTenantId().isEmpty()) {
alipayMiniSubscribeService.sendServiceProcessMsg(
order.getUserId(), order.getTenantId(),
orderName, "素材上传完成",
order.getOrderNo(), payTimeStr, pageUrl
);
}
wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(),
orderName,
tip,
order.getOrderNo(),
payTimeStr,
"",
pageUrl
);
}
}
@@ -248,7 +248,7 @@ public class RefundController {
return Result.succeed("已处理全额退款");
}
if (refundRequest.getState().equals(RefundState.PART.getId())){
dealCustomRefundAmountRequest(order,refundRequest.getRefundAmount());
routeRefundByPayType(order, refundRequest.getRefundAmount());
refundorder.setApproveReason(refundRequest.getApproveReason());
refundorder.setState(refundRequest.getState()); //部分退款
if(refundRequest.getRefundAmount()!=null){
@@ -11,6 +11,7 @@ import com.central.order.model.Message;
import com.central.order.model.Order;
import com.central.order.model.QrCode;
import com.central.order.model.Tourism;
import com.central.order.enums.PayTypeEnum;
import com.central.order.service.*;
import com.central.order.service.impl.FeipaiNotifyServiceImpl;
import com.central.order.util.DateUtils;
@@ -42,6 +43,8 @@ public class OrderStatusChangeListener {
@Autowired
private WxMiniSubscribeService wxMiniSubscribeService;
@Autowired
private AlipayMiniSubscribeService alipayMiniSubscribeService;
@Autowired
private FeipaiNotifyServiceImpl feipaiNotifyService;
@EventListener
@@ -164,27 +167,15 @@ public class OrderStatusChangeListener {
private void handlePaymentSuccess(Order order, Tourism tourism) {
try {
// 1. 发送微信通知
SysUser sysUser = userCenterService.findUserById(order.getUserId());
// 2. 查询订单排队信息
// 1. 查询订单排队信息
Integer queue = orderService.getOrderRankingByOrderIdAndDevice(order.getId(), order.getDeviceSn());
String orderName = tourism.getTourismName();
String pageUrl = "pages/task/task";
String tip = "支付成功,当前排第" + queue + "位";
String orderTime = DateUtils.sdf.format(order.getPayTime());
// 发送小程序订阅消息
if (sysUser.getOpenId() != null) {
String tip = "支付成功,当前排第"+queue+"位";
String orderName = tourism.getTourismName();
String pageUrl = "pages/task/task";
wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(),
orderName,
tip,
order.getOrderNo(),
DateUtils.sdf.format(order.getPayTime()),
"",
pageUrl
);
}
// 根据 payType 发送小程序通知(微信 or 支付宝)
sendSubscribeMsgByPayType(order, orderName, tip, order.getOrderNo(), orderTime, pageUrl);
// 2. 记录支付成功日志
log.info("订单支付成功: orderNo={}, amount={}, tourismName={}",
@@ -231,108 +222,74 @@ public class OrderStatusChangeListener {
/**
* 退款申请成功(退款中)通知
* @param order
* @param tourism
*/
private void sendMessageForRefunding(Order order, Tourism tourism) {
// 发送小程序订阅消息,用户素材上传完成
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser.getOpenId() != null) {
String tip = "您的订单正在退款中";
try {
String orderName = tourism.getTourismName();
String pageUrl = "pages/task/task";
wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(),
orderName,
tip,
order.getOrderNo(),
DateUtils.sdf.format(order.getPayTime()),
"",
pageUrl
);
String orderTime = DateUtils.sdf.format(order.getPayTime());
sendSubscribeMsgByPayType(order, orderName, "您的订单正在退款中",
order.getOrderNo(), orderTime, pageUrl);
} catch (Exception e) {
log.error("退款中通知发送失败,不影响主流程: orderNo={}", order.getOrderNo(), e);
}
}
/**
* 退款完成通知
* @param order
* @param tourism
*/
private void sendMessageForRefunded(Order order, Tourism tourism) {
// 发送小程序订阅消息,用户素材上传完成
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser.getOpenId() != null) {
String tip = "您的订单退款已完成";
try {
String orderName = tourism.getTourismName();
String pageUrl = "pages/task/task";
wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(),
orderName,
tip,
order.getOrderNo(),
DateUtils.sdf.format(order.getPayTime()),
"",
pageUrl
);
String orderTime = DateUtils.sdf.format(order.getPayTime());
sendSubscribeMsgByPayType(order, orderName, "您的订单退款已完成",
order.getOrderNo(), orderTime, pageUrl);
} catch (Exception e) {
log.error("退款完成通知发送失败,不影响主流程: orderNo={}", order.getOrderNo(), e);
}
}
/**
* 素材上传完成小程序通知
* @param order
* @param tourism
*/
private void sendMessageForResouresUploaded(Order order, Tourism tourism) {
// 发送小程序订阅消息,用户素材上传完成
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser.getOpenId() != null) {
String tip = "素材上传完成";
try {
String orderName = tourism.getTourismName();
String pageUrl = "pages/album/album";
wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(),
orderName,
tip,
order.getOrderNo(),
DateUtils.sdf.format(order.getPayTime()),
"",
pageUrl
);
String orderTime = "";
if (order.getPayTime() != null) {
orderTime = DateUtils.sdf.format(order.getPayTime());
}
sendSubscribeMsgByPayType(order, orderName, "素材上传完成",
order.getOrderNo(), orderTime, pageUrl);
} catch (Exception e) {
log.error("素材上传通知发送失败,不影响主流程: orderNo={}", order.getOrderNo(), e);
}
}
/**
* 订单完成后通知下一位用户
* @param order
* @param tourism
*/
private void sendMessageToNextOrderUser(Order order, Tourism tourism) {
// 新增:查找下一个排队用户
Order nextOrder = orderService.getNextQueueOrder(order.getTourismId(), order.getId());
if (nextOrder != null) {
SysUser nextUser = userCenterService.findUserById(nextOrder.getUserId());
if (nextUser != null && nextUser.getOpenId() != null && tourism != null) {
String activityName = tourism.getTourismName(); // 活动名称
try {
Order nextOrder = orderService.getNextQueueOrder(order.getTourismId(), order.getId());
if (nextOrder != null && tourism != null) {
String activityName = tourism.getTourismName();
String remark = "即将为您进行拍摄服务";
String activityNo = nextOrder.getOrderNo(); // 活动编号
String activityNo = nextOrder.getOrderNo();
String pageUrl = "pages/album/album";
wxMiniSubscribeService.sendServiceProcessMsg(
nextUser.getOpenId(),
activityName,
remark,
activityNo,
DateUtils.sdf.format(nextOrder.getPayTime()),
"",
pageUrl
);
log.info("已通知下一个排队用户: userId={}, openId={}, orderNo={}", nextUser.getId(), nextUser.getOpenId(), activityNo);
String orderTime = DateUtils.sdf.format(nextOrder.getPayTime());
sendSubscribeMsgByPayType(nextOrder, activityName, remark,
activityNo, orderTime, pageUrl);
log.info("已通知下一个排队用户: userId={}, orderNo={}", nextOrder.getUserId(), activityNo);
}
} catch (Exception e) {
log.error("通知下一位排队用户失败,不影响主流程: orderNo={}", order.getOrderNo(), e);
}
}
@@ -345,4 +302,35 @@ public class OrderStatusChangeListener {
&& qrCode.getEnableVideoEdit() == 1
&& qrCode.getTemplateId() != null; // 确保有模板ID
}
/**
* 根据订单支付类型发送小程序订阅消息
* payType=1 → 微信通知
* payType=4 → 支付宝通知
* 其他 → 不发送
*/
private void sendSubscribeMsgByPayType(Order order, String taskName, String processDesc,
String orderNo, String orderTime, String pageUrl) {
Integer payType = order.getPayType();
if (PayTypeEnum.WECHAT_PAY.getCode().equals(payType)) {
// 微信通知
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser != null && sysUser.getOpenId() != null) {
wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(), taskName, processDesc,
orderNo, orderTime, "", pageUrl);
}
} else if (PayTypeEnum.ALIPAY_PAY.getCode().equals(payType)) {
// 支付宝通知:服务内部按 tenantId 查询 MINI 配置并获取 appId
if (order.getTenantId() != null && !order.getTenantId().isEmpty()) {
alipayMiniSubscribeService.sendServiceProcessMsg(
order.getUserId(), order.getTenantId(), taskName, processDesc,
orderNo, orderTime, pageUrl);
} else {
log.warn("订单 tenantId 为空,跳过支付宝订阅消息: orderNo={}", orderNo);
}
}
// payType=2(优惠券) / 3(核销) 不发送小程序通知
}
}
@@ -0,0 +1,29 @@
package com.central.order.service;
/**
* 支付宝小程序订阅消息服务
* <p>
* 对标 WxMiniSubscribeService,封装支付宝模板消息发送能力。
* 支持通过系统 userId + 租户ID 自动查询支付宝 userId 并发送消息。
*
* @author duzhichao
* @date 2026-06-24
*/
public interface AlipayMiniSubscribeService {
/**
* 发送服务进度通知(支付成功/退款中/退款完成/排队通知等)
*
* @param userId 系统用户ID
* @param tenantId 租户ID,用于查询 type=MINI 的支付宝小程序配置
* @param taskName 服务名称(如景区名称)
* @param processDesc 服务阶段描述(如"支付成功,当前排第2位")
* @param orderNo 订单编号
* @param orderTime 下单时间
* @param pageUrl 跳转小程序页面路径
*/
void sendServiceProcessMsg(Long userId, String tenantId,
String taskName, String processDesc,
String orderNo, String orderTime,
String pageUrl);
}
@@ -0,0 +1,219 @@
package com.central.order.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayObject;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.internal.util.AlipaySignature;
import com.central.alipay.config.AlipayClientFactory;
import com.central.alipay.entity.AlipayConfig;
import com.central.common.feign.UserService;
import com.central.order.service.AlipayMiniSubscribeService;
import com.central.order.service.IAlipayConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* 支付宝小程序订阅消息服务实现
* <p>
* 通过 {@link AlipayClient(AlipayRequest, Map)} 直接调用
* alipay.open.app.message.subscription.send 接口,无需依赖特定 SDK 版本的 Request/Response 类。
* <p>
* 验证方式、参数签名等均由 AlipayClient 统一处理。
*
* @author duzhichao
* @date 2026-06-24
*/
@Slf4j
@Service
public class AlipayMiniSubscribeServiceImpl implements AlipayMiniSubscribeService {
/** 支付宝小程序订阅消息发送接口方法名 */
private static final String API_METHOD = "alipay.open.app.message.subscription.send";
@Value("${alipay.mini.template.service-process:}")
private String serviceProcessTemplateId;
@Autowired
private AlipayClientFactory alipayClientFactory;
@Autowired
private IAlipayConfigService alipayConfigService;
@Autowired
private UserService userService;
@Override
public void sendServiceProcessMsg(Long userId, String tenantId,
String taskName, String processDesc,
String orderNo, String orderTime,
String pageUrl) {
try {
// 0. 校验模板ID配置
if (serviceProcessTemplateId == null || serviceProcessTemplateId.isEmpty()) {
log.warn("支付宝小程序订阅消息模板ID未配置(alipay.mini.template.service-process),跳过通知: orderNo={}", orderNo);
return;
}
// 1. 按租户获取支付宝小程序配置(type=MINI)
AlipayConfig config = alipayConfigService.getConfigByTypeAndTenantId("MINI", tenantId);
if (config == null) {
log.warn("支付宝小程序配置不存在(type=MINI),跳过通知: tenantId={}, orderNo={}", tenantId, orderNo);
return;
}
String appId = config.getAppId();
if (appId == null || appId.isEmpty()) {
log.warn("支付宝小程序 appId 为空,跳过通知: tenantId={}, orderNo={}", tenantId, orderNo);
return;
}
// 2. 通过 userId + appId 反查支付宝 userId
String alipayUserId = userService.getAlipayOpenIdByUserId(userId, appId);
if (alipayUserId == null || alipayUserId.isEmpty()) {
log.warn("用户无支付宝 userId,跳过通知: userId={}, appId={}, orderNo={}", userId, appId, orderNo);
return;
}
// 3. 获取支付宝客户端(MINI 类型配置)
AlipayClient client = alipayClientFactory.createAlipayClient(config);
// 4. 构建订阅消息参数(字段名需与支付宝开放平台申请的模板变量一致)
JSONObject data = new JSONObject();
data.put("taskName", new JSONObject().put("value", taskName != null ? taskName : ""));
data.put("processDesc", new JSONObject().put("value", processDesc != null ? processDesc : ""));
data.put("orderNo", new JSONObject().put("value", orderNo != null ? orderNo : ""));
data.put("orderTime", new JSONObject().put("value", orderTime != null ? orderTime : ""));
JSONObject bizContent = new JSONObject();
bizContent.put("to_user_id", alipayUserId);
bizContent.put("template_id", serviceProcessTemplateId);
if (pageUrl != null && !pageUrl.isEmpty()) {
bizContent.put("page", pageUrl);
}
bizContent.put("data", data);
// 5. 使用 AlipayRequest 接口直接调用,无需依赖特定 SDK 版本的 Request 类
Map<String, String> requestParams = new HashMap<>();
requestParams.put("method", API_METHOD);
requestParams.put("biz_content", bizContent.toJSONString());
AlipayRequest<AlipayResponse> request = new SimpleAlipayRequest(requestParams);
// 6. 发送
AlipayResponse response = client.execute(request);
if (response.isSuccess()) {
log.info("支付宝小程序订阅消息发送成功: userId={}, orderNo={}, templateId={}",
userId, orderNo, serviceProcessTemplateId);
} else {
log.error("支付宝小程序订阅消息发送失败: userId={}, orderNo={}, subCode={}, subMsg={}",
userId, orderNo, response.getSubCode(), response.getSubMsg());
}
} catch (Exception e) {
// 支付宝消息发送失败不影响主业务流程
log.error("支付宝小程序订阅消息发送异常: userId={}, orderNo={}", userId, orderNo, e);
}
}
/**
* 简易 AlipayRequest 实现,通过 Map 传参,避免依赖特定 SDK 版本的 Request 类。
* <p>
* 方法签名严格对齐 alipay-sdk-java 4.40.816.ALL 中 AlipayRequest 接口的 19 个抽象方法。
*/
private static class SimpleAlipayRequest implements AlipayRequest<AlipayResponse> {
private final Map<String, String> requestParams;
SimpleAlipayRequest(Map<String, String> requestParams) {
this.requestParams = requestParams;
}
// ---- AlipayRequest 接口 19 个抽象方法(按 javap 反编译顺序) ----
@Override
public String getApiMethodName() {
return requestParams.get("method");
}
@Override
public Map<String, String> getTextParams() {
return requestParams;
}
@Override
public String getApiVersion() {
return "1.0";
}
@Override
public void setApiVersion(String apiVersion) { }
@Override
public String getTerminalType() {
return null;
}
@Override
public void setTerminalType(String terminalType) { }
@Override
public String getTerminalInfo() {
return null;
}
@Override
public void setTerminalInfo(String terminalInfo) { }
@Override
public String getProdCode() {
return null;
}
@Override
public void setProdCode(String prodCode) { }
@Override
public String getNotifyUrl() {
return null;
}
@Override
public void setNotifyUrl(String notifyUrl) { }
@Override
public String getReturnUrl() {
return null;
}
@Override
public void setReturnUrl(String returnUrl) { }
@Override
public Class<AlipayResponse> getResponseClass() {
return AlipayResponse.class;
}
@Override
public boolean isNeedEncrypt() {
return false;
}
@Override
public void setNeedEncrypt(boolean needEncrypt) { }
@Override
public AlipayObject getBizModel() {
return null;
}
@Override
public void setBizModel(AlipayObject bizModel) { }
}
}
@@ -0,0 +1,501 @@
# 支付宝小程序订阅消息通知 — 实现文档
> **作者**: duzhichao
> **日期**: 2026-06-24
> **关联文件**: `OrderStatusChangeListener.java`
---
## 1. 背景与目标
当前 `OrderStatusChangeListener` 中的用户通知仅支持**微信小程序订阅消息**(通过 `WxMiniSubscribeService`)。需要新增**支付宝小程序订阅消息**能力,使得通过支付宝小程序下单的用户也能在订单状态变更时收到消息通知。
### 支付类型枚举(PayTypeEnum)
| payType | 枚举 | 说明 |
|---------|------|------|
| 1 | `WECHAT_PAY` | 微信支付 |
| 2 | `COUPON_PAY` | 优惠券支付 |
| 3 | `FEIPAI_VERIFY` | 第三方渠道核销 |
| 4 | `ALIPAY_PAY` | 支付宝支付 |
### 通知路由策略
> **核心原则:根据订单的 `payType` 决定通知渠道,而非两个平台都发。**
| payType | 通知渠道 | 说明 |
|---------|----------|------|
| 1(微信支付) | 微信小程序订阅消息 | 走 `WxMiniSubscribeService` |
| 4(支付宝支付) | 支付宝小程序订阅消息 | 走 `AlipayMiniSubscribeService` |
| 2/3(优惠券/核销) | 不发送小程序通知 | 无需平台通知 |
### 当前微信通知覆盖的场景
| 场景 | 调用方法 | 调用位置 |
|------|----------|----------|
| 支付成功 | `wxMiniSubscribeService.sendServiceProcessMsg` | `handlePaymentSuccess()` |
| 退款中 | `wxMiniSubscribeService.sendServiceProcessMsg` | `sendMessageForRefunding()` |
| 退款完成 | `wxMiniSubscribeService.sendServiceProcessMsg` | `sendMessageForRefunded()` |
| 素材上传完成 | `wxMiniSubscribeService.sendServiceProcessMsg` | `sendMessageForResouresUploaded()` |
| 通知下一位排队用户 | `wxMiniSubscribeService.sendServiceProcessMsg` | `sendMessageToNextOrderUser()` |
### 设计原则
1. **按 payType 路由**:payType=1 走微信,payType=4 走支付宝,互斥非并行
2. **用户标识隔离**:微信使用 `SysUser.openId`,支付宝通过 `UserService.getAlipayOpenIdByUserId(userId, appId)` 查询
3. **租户维度取配置**:支付宝小程序配置必须按 `order.tenantId + type=MINI` 查询,不能全局取第一条配置
4. **调用语义统一**:`AlipayMiniSubscribeService` 与 `WxMiniSubscribeService` 都封装“服务进度通知”,但入参按平台差异隔离
---
## 2. 现有基础设施分析
项目已具备完整的支付宝集成基础,**无需新增 SDK 依赖**:
| 组件 | 模块 | 说明 |
|------|------|------|
| `AlipayClientFactory` | `zlt-alipay-spring-boot-starter` | 多租户 AlipayClient 缓存工厂 |
| `AlipayConfig` | `zlt-alipay-common-core` | 支付宝配置实体(含 `type=MINI/PAY`) |
| `AlipayAutoConfiguration` | `zlt-alipay-spring-boot-starter` | 自动配置,条件为 `zlt.alipay.enabled=true` |
| `UserService.getAlipayOpenIdByUserId()` | `zlt-common-core` | Feign 接口,通过 userId + appId 反查支付宝用户标识 |
| `SysUserThirdOpenid` | `user-center` | 第三方 openId 映射表(`provider=ALIPAY`) |
| `alipay-sdk-java:4.40.816.ALL` | Maven 依赖 | 已引入;实现前需确认该版本包含目标订阅消息 API 的 Request/Response 类 |
### 用户标识获取方式对比
| 平台 | 存储位置 | 获取方式 |
|------|----------|----------|
| 微信 | `SysUser.openId` | `userCenterService.findUserById(userId).getOpenId()` |
| 支付宝 | `sys_user_third_openid` 表 | 先按 `order.tenantId` 查询 `type=MINI` 配置,再用 `config.appId` 调 `userService.getAlipayOpenIdByUserId(userId, appId)` |
### 参考:WxMiniSubscribeService 接口定义
```java
public interface WxMiniSubscribeService {
void sendPaySuccessMsg(String openId, String orderName, String orderNo, String tip, String amount, String orderTime);
void sendActivityStartMsg(String openId, String place, String activityName, String remark, String activityNo);
void sendVideoEditCompleteMsg(String openId, String taskName, String orderNo, String result);
void sendServiceProcessMsg(String openId, String taskName, String processDesc, String orderNo, String orderTime, String result, String pageUrl);
}
```
---
## 3. 支付宝订阅消息 API
### 3.1 接口选择
支付宝小程序订阅消息应使用**小程序订阅消息专用能力**。服务端接口优先核对支付宝开放平台的 `alipay.open.app.message.subscription.send`(小程序发送订阅消息)及当前 SDK 对应的 Request/Response 类。
> ⚠️ 不建议直接使用 `alipay.open.public.template.message.send` 作为本需求的默认接口。该接口偏生活号/公共模板消息语义,容易与“小程序订阅消息”混淆。实现前必须以支付宝开放平台当前文档和本项目锁定的 `alipay-sdk-java:4.40.816.ALL` 中实际存在的类名为准。
前端需要在支付宝小程序内调用订阅授权 API(如 `my.requestSubscribeMessage`)让用户授权对应模板,服务端只能给已授权的用户发送订阅消息。
### 3.2 SDK 调用示例
```java
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayOpenAppMessageSubscriptionSendRequest;
import com.alipay.api.response.AlipayOpenAppMessageSubscriptionSendResponse;
AlipayClient client = alipayClientFactory.createAlipayClient(config);
AlipayOpenAppMessageSubscriptionSendRequest request =
new AlipayOpenAppMessageSubscriptionSendRequest();
// 构建订阅消息参数,字段名以支付宝开放平台对应接口文档为准
JSONObject bizContent = new JSONObject();
bizContent.put("to_user_id", alipayUserId); // 支付宝 userId
bizContent.put("template_id", templateId); // 订阅消息模板 ID
bizContent.put("page", pageUrl); // 跳转小程序页面(可选)
JSONObject data = new JSONObject();
data.put("taskName", new JSONObject().put("value", tourismName));
data.put("orderNo", new JSONObject().put("value", orderNo));
data.put("processDesc", new JSONObject().put("value", tip));
data.put("orderTime", new JSONObject().put("value", payTime));
bizContent.put("data", data);
request.setBizContent(bizContent.toJSONString());
AlipayOpenAppMessageSubscriptionSendResponse response = client.execute(request);
if (!response.isSuccess()) {
log.error("subCode={}, subMsg={}", response.getSubCode(), response.getSubMsg());
}
```
---
## 4. 详细实现方案
### 4.1 新增接口 `AlipayMiniSubscribeService`
**文件**: `zlt-business/order-center/src/main/java/com/central/order/service/AlipayMiniSubscribeService.java`
```java
package com.central.order.service;
/**
* 支付宝小程序订阅消息服务
* <p>
* 对标 WxMiniSubscribeService,封装支付宝模板消息发送能力。
* 支持通过系统 userId + 租户ID 自动查询支付宝 userId 并发送消息。
*
* @author duzhichao
* @date 2026-06-24
*/
public interface AlipayMiniSubscribeService {
/**
* 发送服务进度通知(支付成功/退款中/退款完成/排队通知等)
*
* @param userId 系统用户ID
* @param tenantId 租户ID,用于查询 type=MINI 的支付宝小程序配置
* @param taskName 服务名称(如景区名称)
* @param processDesc 服务阶段描述(如"支付成功,当前排第2位")
* @param orderNo 订单编号
* @param orderTime 下单时间
* @param pageUrl 跳转小程序页面路径
*/
void sendServiceProcessMsg(Long userId, String tenantId,
String taskName, String processDesc,
String orderNo, String orderTime,
String pageUrl);
}
```
### 4.2 实现类 `AlipayMiniSubscribeServiceImpl`
**文件**: `zlt-business/order-center/src/main/java/com/central/order/service/impl/AlipayMiniSubscribeServiceImpl.java`
```java
package com.central.order.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayOpenAppMessageSubscriptionSendRequest;
import com.alipay.api.response.AlipayOpenAppMessageSubscriptionSendResponse;
import com.central.alipay.config.AlipayClientFactory;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.feign.AlipayConfigService;
import com.central.common.feign.UserService;
import com.central.order.service.AlipayMiniSubscribeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* 支付宝小程序订阅消息服务实现
*
* @author duzhichao
* @date 2026-06-24
*/
@Slf4j
@Service
public class AlipayMiniSubscribeServiceImpl implements AlipayMiniSubscribeService {
@Value("${alipay.mini.template.service-process}")
private String serviceProcessTemplateId;
@Autowired
private AlipayClientFactory alipayClientFactory;
@Autowired
private AlipayConfigService alipayConfigService;
@Autowired
private UserService userService;
@Override
public void sendServiceProcessMsg(Long userId, String tenantId,
String taskName, String processDesc,
String orderNo, String orderTime,
String pageUrl) {
try {
// 1. 按租户获取支付宝小程序配置
AlipayConfig config = alipayConfigService.getConfig("MINI", tenantId);
if (config == null) {
log.warn("支付宝小程序配置不存在,跳过通知: tenantId={}", tenantId);
return;
}
String appId = config.getAppId();
if (appId == null || appId.isEmpty()) {
log.warn("支付宝小程序 appId 为空,跳过通知: tenantId={}", tenantId);
return;
}
// 2. 通过 userId + appId 反查支付宝 userId
String alipayUserId = userService.getAlipayOpenIdByUserId(userId, appId);
if (alipayUserId == null || alipayUserId.isEmpty()) {
log.warn("用户无支付宝 userId,跳过通知: userId={}, appId={}", userId, appId);
return;
}
// 3. 获取支付宝客户端(MINI 类型配置)
AlipayClient client = alipayClientFactory.createAlipayClient(config);
// 4. 构建请求
AlipayOpenAppMessageSubscriptionSendRequest request =
new AlipayOpenAppMessageSubscriptionSendRequest();
// 5. 构建订阅消息参数(字段名需与支付宝开放平台申请的模板变量一致)
JSONObject data = new JSONObject();
data.put("taskName", new JSONObject().put("value", taskName));
data.put("processDesc", new JSONObject().put("value", processDesc));
data.put("orderNo", new JSONObject().put("value", orderNo));
data.put("orderTime", new JSONObject().put("value", orderTime));
JSONObject bizContent = new JSONObject();
bizContent.put("to_user_id", alipayUserId);
bizContent.put("template_id", serviceProcessTemplateId);
bizContent.put("page", pageUrl);
bizContent.put("data", data);
request.setBizContent(bizContent.toJSONString());
// 6. 发送
AlipayOpenAppMessageSubscriptionSendResponse response = client.execute(request);
if (response.isSuccess()) {
log.info("支付宝小程序订阅消息发送成功: userId={}, orderNo={}", userId, orderNo);
} else {
log.error("支付宝小程序订阅消息发送失败: userId={}, orderNo={}, subCode={}, subMsg={}",
userId, orderNo, response.getSubCode(), response.getSubMsg());
}
} catch (Exception e) {
log.error("支付宝小程序订阅消息发送异常: userId={}, orderNo={}", userId, orderNo, e);
}
}
}
```
---
## 5. 配置项
### 5.1 application.yml 新增
```yaml
alipay:
mini:
template:
# 支付宝开放平台 → 小程序订阅消息 → 模板ID
service-process: YOUR_ALIPAY_TEMPLATE_ID
```
### 5.2 AlipayConfig 表数据
确保 `alipay_config` 表中存在 `type=MINI` 的配置记录:
| 字段 | 值 |
|------|-----|
| `tenant_id` | 租户ID |
| `type` | `MINI` |
| `app_id` | 支付宝小程序 AppId |
| `app_private_key` | 应用私钥 |
| `alipay_public_key` | 支付宝公钥 |
| `sign_type` | `RSA2` |
| `status` | `1` |
---
## 6. 改造 OrderStatusChangeListener
### 6.1 新增注入
```java
@Autowired
private AlipayMiniSubscribeService alipayMiniSubscribeService;
```
### 6.2 新增辅助方法
```java
/**
* 根据订单支付类型发送小程序订阅消息
* payType=1 → 微信通知
* payType=4 → 支付宝通知
* 其他 → 不发送
*/
private void sendSubscribeMsgByPayType(Order order, String taskName, String processDesc,
String orderNo, String orderTime, String pageUrl) {
Integer payType = order.getPayType();
if (PayTypeEnum.WECHAT_PAY.getCode().equals(payType)) {
// 微信通知
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser != null && sysUser.getOpenId() != null) {
wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(), taskName, processDesc,
orderNo, orderTime, "", pageUrl);
}
} else if (PayTypeEnum.ALIPAY_PAY.getCode().equals(payType)) {
// 支付宝通知:服务内部按 tenantId 查询 MINI 配置并获取 appId
if (order.getTenantId() != null && !order.getTenantId().isEmpty()) {
alipayMiniSubscribeService.sendServiceProcessMsg(
order.getUserId(), order.getTenantId(), taskName, processDesc,
orderNo, orderTime, pageUrl);
} else {
log.warn("订单 tenantId 为空,跳过支付宝订阅消息: orderNo={}", orderNo);
}
}
// payType=2(优惠券) / 3(核销) 不发送小程序通知
}
```
### 6.3 各场景改造
> 所有场景统一使用 `sendSubscribeMsgByPayType()` 方法,根据 payType 自动路由到对应平台。
#### 支付成功 `handlePaymentSuccess()`
```java
private void handlePaymentSuccess(Order order, Tourism tourism) {
try {
Integer queue = orderService.getOrderRankingByOrderIdAndDevice(order.getId(), order.getDeviceSn());
String orderName = tourism.getTourismName();
String pageUrl = "pages/task/task";
String tip = "支付成功,当前排第" + queue + "位";
String orderTime = DateUtils.sdf.format(order.getPayTime());
// 根据 payType 发送小程序通知(微信 or 支付宝)
sendSubscribeMsgByPayType(order, orderName, tip, order.getOrderNo(), orderTime, pageUrl);
log.info("订单支付成功: orderNo={}, amount={}, tourismName={}",
order.getOrderNo(), order.getOrderAmount(), tourism.getTourismName());
} catch (Exception e) {
log.error("处理支付成功通知失败: orderNo={}", order.getOrderNo(), e);
}
}
```
#### 退款中 `sendMessageForRefunding()`
```java
private void sendMessageForRefunding(Order order, Tourism tourism) {
String orderName = tourism.getTourismName();
String pageUrl = "pages/task/task";
String orderTime = DateUtils.sdf.format(order.getPayTime());
// 根据 payType 发送小程序通知
sendSubscribeMsgByPayType(order, orderName, "您的订单正在退款中",
order.getOrderNo(), orderTime, pageUrl);
}
```
#### 退款完成 `sendMessageForRefunded()`
```java
private void sendMessageForRefunded(Order order, Tourism tourism) {
String orderName = tourism.getTourismName();
String pageUrl = "pages/task/task";
String orderTime = DateUtils.sdf.format(order.getPayTime());
// 根据 payType 发送小程序通知
sendSubscribeMsgByPayType(order, orderName, "您的订单退款已完成",
order.getOrderNo(), orderTime, pageUrl);
}
```
#### 素材上传完成 `sendMessageForResouresUploaded()`
```java
private void sendMessageForResouresUploaded(Order order, Tourism tourism) {
String orderName = tourism.getTourismName();
String pageUrl = "pages/album/album";
String orderTime = DateUtils.sdf.format(order.getPayTime());
// 根据 payType 发送小程序通知
sendSubscribeMsgByPayType(order, orderName, "素材上传完成",
order.getOrderNo(), orderTime, pageUrl);
}
```
#### 通知下一位排队用户 `sendMessageToNextOrderUser()`
```java
private void sendMessageToNextOrderUser(Order order, Tourism tourism) {
Order nextOrder = orderService.getNextQueueOrder(order.getTourismId(), order.getId());
if (nextOrder != null) {
SysUser nextUser = userCenterService.findUserById(nextOrder.getUserId());
if (nextUser != null && tourism != null) {
String activityName = tourism.getTourismName();
String remark = "即将为您进行拍摄服务";
String activityNo = nextOrder.getOrderNo();
String pageUrl = "pages/album/album";
String orderTime = DateUtils.sdf.format(nextOrder.getPayTime());
// 根据下一笔订单的 payType 发送通知(注意:不是当前订单的 payType)
sendSubscribeMsgByPayType(nextOrder, activityName, remark,
activityNo, orderTime, pageUrl);
log.info("已通知下一个排队用户: userId={}, orderNo={}", nextUser.getId(), activityNo);
}
}
}
```
### 6.4 改造前后对比
| 场景 | 改造前 | 改造后 |
|------|--------|--------|
| 支付成功 | 只走微信,手动检查 `openId != null` | `sendSubscribeMsgByPayType()` 按 payType 路由 |
| 退款中 | 只走微信 | `sendSubscribeMsgByPayType()` 按 payType 路由 |
| 退款完成 | 只走微信 | `sendSubscribeMsgByPayType()` 按 payType 路由 |
| 素材上传完成 | 只走微信 | `sendSubscribeMsgByPayType()` 按 payType 路由 |
| 通知下一位排队 | 只走微信 | `sendSubscribeMsgByPayType(nextOrder, ...)` 按**下一笔订单**的 payType 路由 |
---
## 7. 支付宝端前置配置清单
| 步骤 | 操作路径 | 说明 |
|------|----------|------|
| ① 开启能力 | 开放平台 → 应用详情 → 添加能力 → 小程序订阅消息 | 开通小程序订阅消息能力 |
| ② 申请模板 | 小程序订阅消息 → 模板库 | 选择或自定义模板,记录模板ID |
| ③ 配置模板变量 | 模板详情 → 变量定义 | 确保与代码 `data` 中的 key 一致 |
| ④ 用户订阅授权 | 小程序前端调用 `my.requestSubscribeMessage` | 用户需主动授权对应模板后才能收到消息 |
| ⑤ 填写后端配置 | 数据库 `alipay_config` 表 | `type=MINI` 的记录需配置正确的 appId、私钥等 |
### 用户授权流程(前端)
```javascript
// 支付宝小程序端 - 引导用户授权订阅消息
my.requestSubscribeMessage({
entityIds: ['YOUR_ALIPAY_TEMPLATE_ID'],
success(res) {
console.log('订阅消息授权结果', res);
},
fail(err) {
console.error('订阅消息授权失败', err);
}
});
```
---
## 8. 文件变更清单
| 操作 | 文件路径 |
|------|----------|
| **新增** | `zlt-business/order-center/src/main/java/com/central/order/service/AlipayMiniSubscribeService.java` |
| **新增** | `zlt-business/order-center/src/main/java/com/central/order/service/impl/AlipayMiniSubscribeServiceImpl.java` |
| **修改** | `zlt-business/order-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java` |
| **修改** | 对应环境 `application.yml` 新增 `alipay.mini.template.service-process` 配置 |
---
## 9. 风险与注意事项
| 风险点 | 说明 | 应对措施 |
|--------|------|----------|
| 支付宝 userId 获取失败 | 用户未通过支付宝登录或第三方表无映射 | 代码中已做 null 检查,静默跳过 |
| 模板字段不匹配 | 代码中的 key 与平台申请的模板变量不一致 | 上线前严格对照模板变量表 |
| 用户未授权订阅 | 支付宝要求用户主动授权才能发消息 | 前端引导授权;未授权时 API 返回错误码,不影响主流程 |
| 配置缺失 | `alipay_config` 表无当前订单 `tenantId + type=MINI` 记录 | `AlipayMiniSubscribeService` 按租户查询失败时跳过,日志告警 |
| 接口限流 | 支付宝 API 有调用频率限制 | try-catch 不影响主业务流程 |
| 排队通知的 payType | `sendMessageToNextOrderUser` 应使用**下一笔订单**的 payType,而非当前订单 | `sendSubscribeMsgByPayType(nextOrder, ...)` 传入 nextOrder |
@@ -44,10 +44,10 @@ const ResourcesActionCell: React.FC<{ record: OrderItem; onReload?: () => void;
const isThirdPartyPay = record.payType === PAY_TYPE.THIRD_PARTY;
// 判断是否为优惠券支付(携程不支持退款接口)
const isCouponPay = record.payType === PAY_TYPE.COUPON;
// 判断是否为支付宝支付(暂不支持退款)
// 判断是否为支付宝支付(现在支持退款)
const isAlipayPay = record.payType === PAY_TYPE.ALIPAY;
// 是否可以创建退款(任务完成 且 非第三方支付 且 非优惠券支付 且 非支付宝支付)
const canCreateRefund = isTaskComplete && !isThirdPartyPay && !isCouponPay && !isAlipayPay;
// 是否可以创建退款(任务完成 且 非第三方支付 且 非优惠券支付)
const canCreateRefund = isTaskComplete && !isThirdPartyPay && !isCouponPay;
return (
<>
@@ -63,10 +63,6 @@ const ResourcesActionCell: React.FC<{ record: OrderItem; onReload?: () => void;
<Tooltip title="优惠券支付订单不支持退款">
<span style={{ color: '#999', cursor: 'not-allowed' }}>创建退款</span>
</Tooltip>
) : isAlipayPay ? (
<Tooltip title="支付宝支付订单暂不支持退款">
<span style={{ color: '#999', cursor: 'not-allowed' }}>创建退款</span>
</Tooltip>
) : (
<Link onClick={() => setCreateRefundModalVisible(true)}>创建退款</Link>
)