Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
217210c8a7 | ||
|
|
a410e9d4d7 | ||
|
|
fb260df13a | ||
|
|
5aa55aaf6b | ||
|
|
ce1b1da8e6 | ||
|
|
36f21fa340 | ||
|
|
01ad2c3c75 | ||
|
|
04f01cf5a6 | ||
|
|
9087a3c291 | ||
|
|
ca41fe080c | ||
|
|
2babee00b1 | ||
|
|
f88834bdbd | ||
|
|
84146bee17 | ||
|
|
c7bf4639bb | ||
|
|
d12a9026fb | ||
|
|
7550fbed35 | ||
|
|
73d7c819cf | ||
|
|
0ac3bece42 | ||
|
|
815b0e3731 | ||
|
|
7baa083f01 | ||
|
|
15e1edb3fc | ||
|
|
07e53316ec | ||
|
|
b0914aa468 | ||
|
|
3a23adbf7c | ||
|
|
f2663b8181 | ||
|
|
dac9b6468e | ||
|
|
42d34668a1 | ||
|
|
6f7a7f69d9 |
@@ -99,7 +99,20 @@
|
|||||||
"Bash(python -c \"print\\('hello'\\)\")",
|
"Bash(python -c \"print\\('hello'\\)\")",
|
||||||
"Bash(grep -r \"RightPanel\" src/pages/client/index.tsx)",
|
"Bash(grep -r \"RightPanel\" src/pages/client/index.tsx)",
|
||||||
"Bash(grep \"statusBar\\\\|statusDot\" src/pages/client/index.tsx)",
|
"Bash(grep \"statusBar\\\\|statusDot\" src/pages/client/index.tsx)",
|
||||||
"Bash(grep \"routeActions\\\\|routeActionsTitle\" src/pages/client/components/CenterView/index.tsx)"
|
"Bash(grep \"routeActions\\\\|routeActionsTitle\" src/pages/client/components/CenterView/index.tsx)",
|
||||||
|
"Read(//c/Users/10989/.m2/repository/com/alipay/**)",
|
||||||
|
"Bash(\"/e/java/apache-maven-3.9.11-bin/apache-maven-3.9.11/bin/mvn.cmd\" -q -o -pl . compile)",
|
||||||
|
"Bash(\"/e/java/apache-maven-3.9.11-bin/apache-maven-3.9.11/bin/mvn.cmd\" -q -pl zlt-commons/zlt-alipay-spring-boot-starter -am compile -DskipTests)",
|
||||||
|
"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)",
|
||||||
|
"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": [],
|
"deny": [],
|
||||||
"ask": []
|
"ask": []
|
||||||
|
|||||||
@@ -11,8 +11,16 @@ nacos/
|
|||||||
.claude/agents/
|
.claude/agents/
|
||||||
.claude/team-collaboration-matrix.md
|
.claude/team-collaboration-matrix.md
|
||||||
|
|
||||||
|
.reasonix
|
||||||
|
reasonix.toml
|
||||||
|
|
||||||
# Cesium static assets (auto-generated by npm install)
|
# Cesium static assets (auto-generated by npm install)
|
||||||
zlt-web/react-web-next/public/cesium/
|
zlt-web/react-web-next/public/cesium/
|
||||||
|
|
||||||
|
|
||||||
zlt-web/yingyan/public/cesium/
|
zlt-web/yingyan/public/cesium/
|
||||||
|
|
||||||
|
# 忽略 dist.zip 文件
|
||||||
|
zlt-web/react-web-next/dist.zip
|
||||||
|
|
||||||
|
zlt-web/yingyan/dist.zip
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Agent(Explore)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<h2>哪种指点飞行操作流更顺手?</h2>
|
||||||
|
<p class="subtitle">重点比较:从开始飞行到连续改点,需要多少次中断和确认。</p>
|
||||||
|
|
||||||
|
<div class="cards" style="grid-template-columns: repeat(3, minmax(0, 1fr));">
|
||||||
|
<div class="card" data-choice="a" onclick="toggleSelect(this)">
|
||||||
|
<div class="card-image" style="padding:16px;background:#122033;min-height:280px;color:#d9e8f5;">
|
||||||
|
<div style="font-size:12px;color:#7f9bb5;margin-bottom:10px;">现有流程</div>
|
||||||
|
<div style="background:#223754;padding:12px;border-radius:4px;margin:8px 0;">右侧面板<br><b>指点飞行</b></div>
|
||||||
|
<div style="text-align:center;color:#65b8ff;">↓ 确认开始</div>
|
||||||
|
<div style="background:#223754;padding:12px;border-radius:4px;margin:8px 0;">等待升空</div>
|
||||||
|
<div style="text-align:center;color:#65b8ff;">↓ 点击地图</div>
|
||||||
|
<div style="background:#f5f7fb;color:#14253b;padding:12px;border-radius:4px;margin:8px 0;">目标确认弹窗<br><small>高度、速度、确认</small></div>
|
||||||
|
<div style="text-align:center;color:#65b8ff;">↓ 到达后才能再选点</div>
|
||||||
|
<div style="background:#223754;padding:12px;border-radius:4px;margin:8px 0;">重复上述步骤</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body"><h3>A. 分步确认</h3><p>控制感强,但连续指点时被弹窗和状态等待反复打断。</p></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card" data-choice="b" onclick="toggleSelect(this)" style="border-color:#1f8fff;">
|
||||||
|
<div class="card-image" style="padding:16px;background:#10273a;min-height:280px;color:#d9e8f5;position:relative;">
|
||||||
|
<div style="font-size:12px;color:#7fcaef;margin-bottom:10px;">推荐:地图优先</div>
|
||||||
|
<div style="height:140px;border:1px solid #39769b;background:linear-gradient(135deg,#173c55,#1d5870);position:relative;border-radius:3px;">
|
||||||
|
<div style="position:absolute;left:42%;top:38%;font-size:32px;color:#ffcf5c;">✦</div>
|
||||||
|
<div style="position:absolute;right:10px;top:8px;background:#0b1925cc;padding:6px 8px;font-size:12px;">正在指点 · 5 m/s</div>
|
||||||
|
<div style="position:absolute;left:15%;bottom:15%;color:#7ad5ff;font-size:22px;">✈</div>
|
||||||
|
</div>
|
||||||
|
<div style="margin-top:10px;background:#0b1925;padding:10px;border-left:3px solid #1f9fff;display:flex;justify-content:space-between;align-items:center;">
|
||||||
|
<span><b>新目标</b><br><small>113.123456, 23.123456</small></span>
|
||||||
|
<span style="color:#ffcf5c;">发送</span>
|
||||||
|
</div>
|
||||||
|
<div style="font-size:12px;color:#9bb8c9;margin-top:10px;line-height:1.5;">首次进入模式后,地图点击直接更新目标。高度和速度沿用上次值,可在紧凑工具条修改;短暂显示“撤销”而不是每次弹窗。</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body"><h3>B. 地图优先</h3><p>一次启用,连续点击连续改点。危险操作才二次确认,常规改点不打断地图。</p></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card" data-choice="c" onclick="toggleSelect(this)">
|
||||||
|
<div class="card-image" style="padding:16px;background:#17242b;min-height:280px;color:#d9e8f5;">
|
||||||
|
<div style="font-size:12px;color:#a9c4b8;margin-bottom:10px;">精细作业模式</div>
|
||||||
|
<div style="height:92px;border:1px solid #607d70;background:#283b35;border-radius:3px;position:relative;">
|
||||||
|
<span style="position:absolute;left:25%;top:22%;font-size:22px;color:#f2d477;">①</span>
|
||||||
|
<span style="position:absolute;left:58%;top:50%;font-size:22px;color:#f2d477;">②</span>
|
||||||
|
<span style="position:absolute;left:12%;bottom:10%;color:#79c9ee;">✈</span>
|
||||||
|
</div>
|
||||||
|
<div style="margin-top:10px;background:#24332e;padding:10px;border-radius:3px;">
|
||||||
|
<b>下一目标</b><span style="float:right;color:#f2d477;">②</span><br>
|
||||||
|
<small>113.123456, 23.123456 · 120m</small>
|
||||||
|
</div>
|
||||||
|
<div style="display:flex;gap:6px;margin-top:8px;"><span style="background:#31463e;padding:5px 7px;font-size:12px;">添加目标</span><span style="background:#31463e;padding:5px 7px;font-size:12px;">确认发送</span></div>
|
||||||
|
<div style="font-size:12px;color:#a9c4b8;margin-top:10px;line-height:1.5;">地图点击先加入临时队列,用户可以复核、排序或删除后发送。</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body"><h3>C. 目标队列</h3><p>适合测绘和有规划的巡查,但增加了一层操作,与即时指点的感觉相反。</p></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="section" style="margin-top:24px;">
|
||||||
|
<p class="label">选择建议</p>
|
||||||
|
<p>我建议选 <b>B</b>:首次启用和结束返航保留明确确认;飞行期间把地图点击变成主操作,避免“点一下、弹一次、等一次”。</p>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<h2>点击建筑时,目标高度应该怎么计算?</h2>
|
||||||
|
<p class="subtitle">现有代码把“模型命中高度 + 输入高度”直接下发;它不等于界面所说的“相对地面高度”。</p>
|
||||||
|
|
||||||
|
<div class="split">
|
||||||
|
<div class="mockup" data-choice="surface" onclick="toggleSelect(this)">
|
||||||
|
<div class="mockup-header">现有:相对点击表面</div>
|
||||||
|
<div class="mockup-body" style="background:#132633;min-height:300px;position:relative;overflow:hidden;color:#e9f5fa;">
|
||||||
|
<div style="position:absolute;left:12%;bottom:8%;width:78%;height:3px;background:#5e856a;"></div>
|
||||||
|
<div style="position:absolute;left:52%;bottom:9%;width:22%;height:44%;background:#73808b;border:2px solid #aebac0;"><span style="position:absolute;top:8px;left:12px;font-size:12px;">楼</span></div>
|
||||||
|
<div style="position:absolute;left:22%;bottom:12%;font-size:28px;">✈</div>
|
||||||
|
<div style="position:absolute;left:63%;bottom:59%;font-size:26px;color:#ffca60;">✦</div>
|
||||||
|
<div style="position:absolute;left:58%;bottom:72%;border-top:1px dashed #ffca60;width:10%;"></div>
|
||||||
|
<div style="position:absolute;right:8%;top:9%;font-size:12px;background:#202f3b;padding:8px;line-height:1.5;">模型表面 40m<br>输入“120m”<br><b style="color:#ffca60;">目标 = 160m</b></div>
|
||||||
|
<div style="position:absolute;left:7%;top:8%;font-size:12px;color:#ff9c9c;">问题:界面称“相对地面”,实际相对楼顶/立面;路径中的更高障碍也没有检查。</div>
|
||||||
|
</div>
|
||||||
|
<div style="padding:12px;"><b>方案 A:保留现状</b><br><small>实现最少,但语义误导,无法保证航线净空。</small></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mockup" data-choice="safe-corridor" onclick="toggleSelect(this)" style="border-color:#1f8fff;">
|
||||||
|
<div class="mockup-header">推荐:安全航高 + 净空保护</div>
|
||||||
|
<div class="mockup-body" style="background:#132633;min-height:300px;position:relative;overflow:hidden;color:#e9f5fa;">
|
||||||
|
<div style="position:absolute;left:12%;bottom:8%;width:78%;height:3px;background:#5e856a;"></div>
|
||||||
|
<div style="position:absolute;left:52%;bottom:9%;width:22%;height:44%;background:#73808b;border:2px solid #aebac0;"><span style="position:absolute;top:8px;left:12px;font-size:12px;">楼</span></div>
|
||||||
|
<div style="position:absolute;left:22%;bottom:12%;font-size:28px;">✈</div>
|
||||||
|
<div style="position:absolute;left:63%;bottom:77%;font-size:26px;color:#75e5ff;">✦</div>
|
||||||
|
<div style="position:absolute;left:26%;bottom:80%;width:42%;border-top:3px solid #4fc3f7;"></div>
|
||||||
|
<div style="position:absolute;left:25%;bottom:74%;font-size:12px;color:#75e5ff;">安全飞行走廊:障碍物顶部 + 安全净空</div>
|
||||||
|
<div style="position:absolute;right:7%;top:8%;font-size:12px;background:#163c4d;padding:8px;line-height:1.5;">地图点击只取经纬度<br>计划高度 = max:<br>· 当前安全航高<br>· 目标建筑顶部 + 净空<br>· 路径障碍顶部 + 净空</div>
|
||||||
|
<div style="position:absolute;left:7%;top:8%;font-size:12px;color:#b8e8c5;">高度策略明确;无法可靠评估净空时,拒绝下发而不是猜测。</div>
|
||||||
|
</div>
|
||||||
|
<div style="padding:12px;"><b>方案 B:安全走廊(推荐)</b><br><small>点击只决定水平位置;系统决定或校验实际椭球目标高。</small></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="section" style="margin-top:22px;">
|
||||||
|
<p class="label">建议交互</p>
|
||||||
|
<p>把“飞行高度”改成“安全航高(相对起飞点)”,默认继承当前安全高度。点击楼顶时显示“目标位于建筑上方,系统已抬升至安全高度”;若无法验证模型/地形净空,则显示风险并禁止确认飞行。</p>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
|
||||||
|
<p class="subtitle">继续在终端确认安全策略...</p>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
|
||||||
|
<p class="subtitle">正在整理“预览后发送 + 安全航高”的交互方案...</p>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"reason":"idle timeout","timestamp":1784875445807}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
628
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# 指点飞行交互与安全实现计划
|
||||||
|
|
||||||
|
## 目标
|
||||||
|
|
||||||
|
将指点飞行改为“点击产生候选点,明确发送后才改飞”的交互;防止把建筑或模型表面的命中高度直接作为飞行目标高度;记录每一次下发及风险确认。
|
||||||
|
|
||||||
|
## 第一版边界
|
||||||
|
|
||||||
|
- 点击模型表面仅作为目标位置与障碍物候选高度。
|
||||||
|
- 目标椭球高度取当前无人机椭球高度与候选表面高度加净空的较大值。
|
||||||
|
- 第一版不宣称已完成路径三维净空验证;路径未验证时必须由当前账户确认风险后才可发送。
|
||||||
|
- 后端保存首次 `fly_to_point` 与后续 `fly_to_point_update` 的下发记录和风险审计信息。
|
||||||
|
|
||||||
|
## 实施步骤
|
||||||
|
|
||||||
|
1. 先为后端安全命令对象编写单元测试,覆盖“未验证净空必须确认风险”与“已验证净空不要求确认”两种行为。
|
||||||
|
2. 新增安全命令对象、目标下发请求对象和 `mission_fly_to_point` 实体/Mapper;迁移脚本补充审计字段与唯一序号约束。
|
||||||
|
3. 将任务更新接口改为强类型请求,后端从登录上下文取得确认人;对未验证风险但未确认的请求拒绝下发。
|
||||||
|
4. 调整任务服务:根据目标历史决定首次命令或更新命令,设备命令成功后记录历史与最新任务目标;结束时先停止指点会话,再调用真实返航接口。
|
||||||
|
5. 前端 Hook 分离候选目标和已发送目标;候选目标不会改变当前飞行目标,发送成功后才成为已发送目标。
|
||||||
|
6. 前端 Cesium 点选在起飞、等待和飞行中均可用,候选点与已发送点使用不同标识;点选高度只用于净空计算和风险提示。
|
||||||
|
7. 用紧凑浮层替代每次点选的大弹窗,提供发送、丢弃和风险确认;保留起飞、结束飞行的明确确认。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
- 后端:`mvn -pl zlt-business/order-center -am -Dtest=FlyToPointTargetCommandTest -Dsurefire.failIfNoSpecifiedTests=false test`
|
||||||
|
- 前端:`npm run tsc`,随后执行 `npm run build`。
|
||||||
|
- 人工:起飞后点 A 仅预览;发送 A 后飞行;飞往 A 时点 B 仅预览;发送 B 后才改飞;未勾选风险确认不可发送。
|
||||||
+15
@@ -104,5 +104,20 @@ public class CtripDistributorConfig {
|
|||||||
* 沙箱测试-人工出票/退订确认/凭证变更接口icode
|
* 沙箱测试-人工出票/退订确认/凭证变更接口icode
|
||||||
*/
|
*/
|
||||||
private String simulateConfirm;
|
private String simulateConfirm;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 产品列表接口icode
|
||||||
|
*/
|
||||||
|
private String productList;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 位置列表接口icode
|
||||||
|
*/
|
||||||
|
private String locationList;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 产品全量列表接口icode
|
||||||
|
*/
|
||||||
|
private String allProducts;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+165
@@ -4,9 +4,18 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|||||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
|
import com.central.coupon.entity.CtripContact;
|
||||||
import com.central.coupon.entity.CtripDistOrder;
|
import com.central.coupon.entity.CtripDistOrder;
|
||||||
|
import com.central.coupon.entity.CtripOrder;
|
||||||
|
import com.central.coupon.entity.CtripOrderItem;
|
||||||
|
import com.central.coupon.mapper.CtripContactMapper;
|
||||||
import com.central.coupon.mapper.CtripDistOrderMapper;
|
import com.central.coupon.mapper.CtripDistOrderMapper;
|
||||||
|
import com.central.coupon.mapper.CtripOrderItemMapper;
|
||||||
|
import com.central.coupon.mapper.CtripOrderMapper;
|
||||||
|
import com.central.coupon.model.CtripConsumedNoticeResponse;
|
||||||
|
import com.central.coupon.service.CtripConsumedService;
|
||||||
import com.central.coupon.service.ICtripDistOrderService;
|
import com.central.coupon.service.ICtripDistOrderService;
|
||||||
|
import com.central.coupon.service.IOrderDetailService;
|
||||||
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.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
@@ -15,8 +24,13 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RestController
|
@RestController
|
||||||
@@ -30,6 +44,21 @@ public class CtripDistOrderController {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private CtripDistOrderMapper ctripDistOrderMapper;
|
private CtripDistOrderMapper ctripDistOrderMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripContactMapper ctripContactMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripOrderMapper ctripOrderMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripOrderItemMapper ctripOrderItemMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripConsumedService ctripConsumedService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private IOrderDetailService orderDetailService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 分页查询携程分销订单列表
|
* 分页查询携程分销订单列表
|
||||||
*/
|
*/
|
||||||
@@ -97,6 +126,15 @@ public class CtripDistOrderController {
|
|||||||
Long ctripProductId = Long.valueOf(params.get("ctripProductId").toString());
|
Long ctripProductId = Long.valueOf(params.get("ctripProductId").toString());
|
||||||
String tenantId = (String) params.get("tenantId");
|
String tenantId = (String) params.get("tenantId");
|
||||||
String mobile = params.get("mobile") != null ? params.get("mobile").toString() : null;
|
String mobile = params.get("mobile") != null ? params.get("mobile").toString() : null;
|
||||||
|
if (mobile == null || mobile.isEmpty()) {
|
||||||
|
String[] prefixes = {"130","131","132","133","134","135","136","137","138","139",
|
||||||
|
"150","151","152","153","155","156","157","158","159",
|
||||||
|
"170","171","172","173","175","176","177","178",
|
||||||
|
"180","181","182","183","184","185","186","187","188","189",
|
||||||
|
"191","193","195","196","197","198","199"};
|
||||||
|
String prefix = prefixes[ThreadLocalRandom.current().nextInt(prefixes.length)];
|
||||||
|
mobile = prefix + String.format("%08d", ThreadLocalRandom.current().nextInt(100000000));
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ctripDistOrderService.createCtripDistOrder(orderNo, orderAmount, ctripProductId, tenantId, mobile);
|
ctripDistOrderService.createCtripDistOrder(orderNo, orderAmount, ctripProductId, tenantId, mobile);
|
||||||
@@ -125,4 +163,131 @@ public class CtripDistOrderController {
|
|||||||
public Result<CtripDistOrder> getCtripDistOrder(@PathVariable String orderNo) {
|
public Result<CtripDistOrder> getCtripDistOrder(@PathVariable String orderNo) {
|
||||||
return Result.succeed(ctripDistOrderService.getByOrderNo(orderNo));
|
return Result.succeed(ctripDistOrderService.getByOrderNo(orderNo));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手动核销携程分销订单
|
||||||
|
*/
|
||||||
|
@Operation(summary = "手动核销携程分销订单")
|
||||||
|
@PostMapping("/consume/{ctripOrderId}")
|
||||||
|
public Result<String> consumeCtripDistOrder(
|
||||||
|
@Parameter(description = "携程订单ID") @PathVariable Long ctripOrderId) {
|
||||||
|
log.info("手动核销携程分销订单,ctripOrderId: {}", ctripOrderId);
|
||||||
|
try {
|
||||||
|
// 1. 查找CtripDistOrder
|
||||||
|
LambdaQueryWrapper<CtripDistOrder> queryWrapper = new LambdaQueryWrapper<>();
|
||||||
|
queryWrapper.eq(CtripDistOrder::getCtripOrderId, ctripOrderId)
|
||||||
|
.eq(CtripDistOrder::getDeleted, 0);
|
||||||
|
CtripDistOrder distOrder = ctripDistOrderMapper.selectOne(queryWrapper);
|
||||||
|
if (distOrder == null) {
|
||||||
|
return Result.failed("未找到携程分销订单,ctripOrderId: " + ctripOrderId);
|
||||||
|
}
|
||||||
|
if (distOrder.getConsumeStatus() != null && distOrder.getConsumeStatus() == 1) {
|
||||||
|
return Result.failed("该订单已核销,无需重复核销");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 获取手机号,根据手机号通过联系人表查找CtripOrder
|
||||||
|
String mobile = distOrder.getMobile();
|
||||||
|
if (mobile == null || mobile.isEmpty()) {
|
||||||
|
return Result.failed("分销订单手机号为空,无法核销");
|
||||||
|
}
|
||||||
|
|
||||||
|
List<CtripContact> contacts = ctripContactMapper.selectByMobile(mobile);
|
||||||
|
if (contacts == null || contacts.isEmpty()) {
|
||||||
|
distOrder.setConsumeStatus(2);
|
||||||
|
distOrder.setErrorMsg("未找到手机号对应的携程联系人记录");
|
||||||
|
ctripDistOrderMapper.updateById(distOrder);
|
||||||
|
return Result.failed("未找到手机号对应的携程联系人记录");
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Long> orderIds = contacts.stream()
|
||||||
|
.map(CtripContact::getOrderId)
|
||||||
|
.distinct()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
// 筛选状态为PAYMENT_CONFIRMED(13)的订单
|
||||||
|
List<CtripOrder> confirmedOrders = new ArrayList<>();
|
||||||
|
for (Long orderId : orderIds) {
|
||||||
|
CtripOrder ctripOrder = ctripOrderMapper.selectById(orderId);
|
||||||
|
if (ctripOrder != null && Integer.valueOf(13).equals(ctripOrder.getStatus())) {
|
||||||
|
confirmedOrders.add(ctripOrder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (confirmedOrders.isEmpty()) {
|
||||||
|
distOrder.setConsumeStatus(2);
|
||||||
|
distOrder.setErrorMsg("未找到状态为PAYMENT_CONFIRMED的携程订单");
|
||||||
|
ctripDistOrderMapper.updateById(distOrder);
|
||||||
|
return Result.failed("未找到状态为PAYMENT_CONFIRMED的携程订单");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 对每个符合条件的CtripOrder执行核销
|
||||||
|
boolean anySuccess = false;
|
||||||
|
StringBuilder errorMsgs = new StringBuilder();
|
||||||
|
|
||||||
|
for (CtripOrder ctripOrder : confirmedOrders) {
|
||||||
|
try {
|
||||||
|
// 建立订单关联关系
|
||||||
|
if (ctripOrder.getOrderNo() == null || ctripOrder.getOrderNo().trim().isEmpty()) {
|
||||||
|
ctripOrder.setOrderNo(distOrder.getOrderNo());
|
||||||
|
ctripOrderMapper.updateById(ctripOrder);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!orderDetailService.validateOrderForConsume(ctripOrder.getOtaOrderId())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<CtripOrderItem> orderItems = ctripOrderItemMapper.selectByOrderId(ctripOrder.getId());
|
||||||
|
if (orderItems == null || orderItems.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (CtripOrderItem item : orderItems) {
|
||||||
|
if (item.getQuantity() == null || item.getQuantity() <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
CtripConsumedController.CtripConsumeRequest request = new CtripConsumedController.CtripConsumeRequest();
|
||||||
|
request.setOtaOrderId(ctripOrder.getOtaOrderId());
|
||||||
|
request.setSupplierOrderId(ctripOrder.getSupplierOrderId());
|
||||||
|
request.setItemId(item.getItemId());
|
||||||
|
request.setUseQuantity(item.getQuantity());
|
||||||
|
request.setRemark("手动核销分销订单,orderNo: " + distOrder.getOrderNo());
|
||||||
|
|
||||||
|
CtripConsumedNoticeResponse response = ctripConsumedService.consumeOrder(request);
|
||||||
|
boolean success = response != null && "0000".equals(response.getHeader().getResultCode());
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
anySuccess = true;
|
||||||
|
} else {
|
||||||
|
String errMsg = response != null ? response.getHeader().getResultMessage() : "未知错误";
|
||||||
|
errorMsgs.append("otaOrderId=").append(ctripOrder.getOtaOrderId())
|
||||||
|
.append(",itemId=").append(item.getItemId())
|
||||||
|
.append(":").append(errMsg).append("; ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
errorMsgs.append("otaOrderId=").append(ctripOrder.getOtaOrderId())
|
||||||
|
.append(":").append(e.getMessage()).append("; ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 更新CtripDistOrder状态
|
||||||
|
if (anySuccess) {
|
||||||
|
distOrder.setConsumeStatus(1);
|
||||||
|
distOrder.setConsumeTime(LocalDateTime.now());
|
||||||
|
distOrder.setCtripOrderStatus("CONSUMED");
|
||||||
|
distOrder.setErrorMsg(errorMsgs.length() > 0 ? "部分核销异常: " + errorMsgs : null);
|
||||||
|
ctripDistOrderMapper.updateById(distOrder);
|
||||||
|
return Result.succeed("核销成功");
|
||||||
|
} else {
|
||||||
|
distOrder.setConsumeStatus(2);
|
||||||
|
distOrder.setErrorMsg(errorMsgs.length() > 0 ? errorMsgs.toString() : "所有订单核销均失败");
|
||||||
|
ctripDistOrderMapper.updateById(distOrder);
|
||||||
|
return Result.failed("核销失败: " + distOrder.getErrorMsg());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("手动核销携程分销订单异常,ctripOrderId: {}", ctripOrderId, e);
|
||||||
|
return Result.failed("核销异常: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+236
-25
@@ -82,6 +82,7 @@ public class CtripDistTestController {
|
|||||||
icode.put("cancelVerify", ctripDistributorConfig.getIcode().getCancelVerify());
|
icode.put("cancelVerify", ctripDistributorConfig.getIcode().getCancelVerify());
|
||||||
icode.put("cancel", ctripDistributorConfig.getIcode().getCancel());
|
icode.put("cancel", ctripDistributorConfig.getIcode().getCancel());
|
||||||
icode.put("bookingDetail", ctripDistributorConfig.getIcode().getBookingDetail());
|
icode.put("bookingDetail", ctripDistributorConfig.getIcode().getBookingDetail());
|
||||||
|
icode.put("allProducts",ctripDistributorConfig.getIcode().getAllProducts());
|
||||||
data.put("icode", icode);
|
data.put("icode", icode);
|
||||||
} else {
|
} else {
|
||||||
data.put("icode", "null - icode未配置!");
|
data.put("icode", "null - icode未配置!");
|
||||||
@@ -131,7 +132,7 @@ public class CtripDistTestController {
|
|||||||
try {
|
try {
|
||||||
Map<String, Object> result = ctripDistApiService.getProductDetail(productId);
|
Map<String, Object> result = ctripDistApiService.getProductDetail(productId);
|
||||||
log.info("产品详情返回: {}", result);
|
log.info("产品详情返回: {}", result);
|
||||||
return Result.succeed(result, "获取产���详情成功");
|
return Result.succeed(result, "获取产品详情成功");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("获取产品详情失败,productId: {}", productId, e);
|
log.error("获取产品详情失败,productId: {}", productId, e);
|
||||||
return Result.failed("获取产品详情失败: " + e.getMessage());
|
return Result.failed("获取产品详情失败: " + e.getMessage());
|
||||||
@@ -204,7 +205,7 @@ public class CtripDistTestController {
|
|||||||
*
|
*
|
||||||
* 调用示例:POST /ctrip/dist/test/check-availability
|
* 调用示例:POST /ctrip/dist/test/check-availability
|
||||||
*
|
*
|
||||||
* 产品2示例(中文姓名+身份证,2出行人):
|
* 产品2示例(如果模板里是 P_NAME,最终会按 P_CNAME 下发,2出行人):
|
||||||
* {
|
* {
|
||||||
* "productId": xxx,
|
* "productId": xxx,
|
||||||
* "packageId": xxx,
|
* "packageId": xxx,
|
||||||
@@ -217,7 +218,7 @@ public class CtripDistTestController {
|
|||||||
* ]
|
* ]
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* 产品3示例(英文姓名,quantity=2但只需1个出行人):
|
* 产品3示例(姓名字段会优先匹配中文姓名题;若模板为 P_NAME,也会改成 P_CNAME):
|
||||||
* {
|
* {
|
||||||
* "productId": 39098283,
|
* "productId": 39098283,
|
||||||
* "packageId": xxx,
|
* "packageId": xxx,
|
||||||
@@ -225,7 +226,7 @@ public class CtripDistTestController {
|
|||||||
* "price": 68.00,
|
* "price": 68.00,
|
||||||
* "quantity": 2,
|
* "quantity": 2,
|
||||||
* "passengers": [
|
* "passengers": [
|
||||||
* {"P_FIRSTCNAME": "Chao", "P_LASTCNAME": "Du"}
|
* {"name": "张三"}
|
||||||
* ]
|
* ]
|
||||||
* }
|
* }
|
||||||
*/
|
*/
|
||||||
@@ -536,6 +537,145 @@ public class CtripDistTestController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 9. 获取位置列表 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取位置列表
|
||||||
|
* 用途:查询可用城市/地区列表,获取locationID和locationType供产品列表接口使用
|
||||||
|
* locale固定为zh-CN
|
||||||
|
*
|
||||||
|
* 调用示例:GET /ctrip/dist/test/location-list?pageIndex=1&pageSize=20
|
||||||
|
*/
|
||||||
|
@GetMapping("/location-list")
|
||||||
|
@Operation(summary = "9.获取位置列表")
|
||||||
|
public Result<Map<String, Object>> testLocationList(
|
||||||
|
@RequestParam(defaultValue = "1") int pageIndex,
|
||||||
|
@RequestParam(defaultValue = "20") int pageSize) {
|
||||||
|
log.info("===== 获取位置列表,pageIndex: {}, pageSize: {} =====", pageIndex, pageSize);
|
||||||
|
try {
|
||||||
|
Map<String, Object> result = ctripDistApiService.getLocationList(pageIndex, pageSize);
|
||||||
|
log.info("位置列表返回: {}", result);
|
||||||
|
return Result.succeed(result, "获取位置列表成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取位置列表失败", e);
|
||||||
|
return Result.failed("获取位置列表失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 10. 获取产品列表 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取产品列表
|
||||||
|
* 用途:查询产品列表,site和destination的locationID/locationType自动从位置列表接口获取
|
||||||
|
* 可通过locationIndex指定使用位置列表中的第几个位置(0-based,默认0)
|
||||||
|
*
|
||||||
|
* 调用示例:POST /ctrip/dist/test/product-list
|
||||||
|
* Body:
|
||||||
|
* {
|
||||||
|
* "locale": "zh-HK",
|
||||||
|
* "currency": "HKD",
|
||||||
|
* "categoryIDList": [1, 2],
|
||||||
|
* "sortOrder": "ID_A",
|
||||||
|
* "pageIndex": 1,
|
||||||
|
* "pageSize": 10,
|
||||||
|
* "imageSize": "500_280",
|
||||||
|
* "poiIDList": [],
|
||||||
|
* "keyWord": "",
|
||||||
|
* "lastUpdateProductID": 0,
|
||||||
|
* "business": "ACTIVITY",
|
||||||
|
* "locationIndex": 0
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
@PostMapping("/product-list")
|
||||||
|
@Operation(summary = "10.获取产品列表(自动填充位置)")
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public Result<Map<String, Object>> testProductList(@RequestBody Map<String, Object> params) {
|
||||||
|
log.info("===== 获取产品列表,params: {} =====", params);
|
||||||
|
try {
|
||||||
|
// 提取locationIndex并从请求体中移除(不传给产品列表接口)
|
||||||
|
int locationIndex = params.containsKey("locationIndex")
|
||||||
|
? Integer.parseInt(params.get("locationIndex").toString()) : 0;
|
||||||
|
Map<String, Object> productListRequest = new java.util.LinkedHashMap<>(params);
|
||||||
|
productListRequest.remove("locationIndex");
|
||||||
|
|
||||||
|
// 第一步:调用位置列表接口获取locationID和locationType
|
||||||
|
log.info("第一步:调用位置列表接口,locale=zh-CN,取第{}个位置", locationIndex);
|
||||||
|
Map<String, Object> locationResult = ctripDistApiService.getLocationList(1, 20);
|
||||||
|
Object locationData = locationResult.get("data");
|
||||||
|
if (locationData == null) {
|
||||||
|
return Result.failed("位置列表接口返回data为空,无法获取locationID");
|
||||||
|
}
|
||||||
|
List<Map<String, Object>> locationList =
|
||||||
|
(List<Map<String, Object>>) ((Map<String, Object>) locationData).get("locationList");
|
||||||
|
if (locationList == null || locationList.isEmpty()) {
|
||||||
|
return Result.failed("位置列表为空,无法获取locationID");
|
||||||
|
}
|
||||||
|
if (locationIndex >= locationList.size()) {
|
||||||
|
return Result.failed("locationIndex=" + locationIndex + " 超出位置列表范围(共" + locationList.size() + "个位置)");
|
||||||
|
}
|
||||||
|
Map<String, Object> location = locationList.get(locationIndex);
|
||||||
|
Object locationID = location.get("locationID");
|
||||||
|
Object locationType = location.get("type");
|
||||||
|
log.info("获取到位置:locationID={}, type={}, name={}", locationID, locationType, location.get("name"));
|
||||||
|
|
||||||
|
// 第二步:用获取到的locationID和locationType填充site和destination
|
||||||
|
Map<String, Object> siteMap = new java.util.LinkedHashMap<>();
|
||||||
|
siteMap.put("locationID", locationID);
|
||||||
|
siteMap.put("locationType", locationType);
|
||||||
|
Map<String, Object> destinationMap = new java.util.LinkedHashMap<>();
|
||||||
|
destinationMap.put("locationID", locationID);
|
||||||
|
destinationMap.put("locationType", locationType);
|
||||||
|
productListRequest.put("site", siteMap);
|
||||||
|
productListRequest.put("destination", destinationMap);
|
||||||
|
|
||||||
|
log.info("第二步:调用产品列表接口,site/destination locationID={}, locationType={}", locationID, locationType);
|
||||||
|
|
||||||
|
// 第三步:调用产品列表接口
|
||||||
|
Map<String, Object> result = ctripDistApiService.getProductList(productListRequest);
|
||||||
|
log.info("产品列表返回: {}", result);
|
||||||
|
|
||||||
|
// 在返回结果中附加使用的位置信息,方便调试
|
||||||
|
Map<String, Object> response = new java.util.LinkedHashMap<>();
|
||||||
|
response.put("usedLocation", location);
|
||||||
|
response.put("productListResult", result);
|
||||||
|
return Result.succeed(response, "获取产品列表成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取产品列表失败", e);
|
||||||
|
return Result.failed("获取产品列表失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 11. 获取产品全量列表 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取产品全量列表
|
||||||
|
* 用途:分批拉取指定业务类型下的全量产品ID及销售状态
|
||||||
|
* 首次调用 lastMaxId 传 "0",后续将上次返回的 maxId 作为 lastMaxId 继续翻页,
|
||||||
|
* 直到返回的 productList 为空或数量小于 limit 为止
|
||||||
|
*
|
||||||
|
* 调用示例:GET /ctrip/dist/test/all-products?business=ACTIVITY&lastMaxId=0&limit=50
|
||||||
|
*/
|
||||||
|
@GetMapping("/all-products")
|
||||||
|
@Operation(summary = "11.获取产品全量列表")
|
||||||
|
public Result<Map<String, Object>> testAllProducts(
|
||||||
|
@RequestParam(defaultValue = "ACTIVITY") String business,
|
||||||
|
@RequestParam(defaultValue = "0") String lastMaxId,
|
||||||
|
@RequestParam(defaultValue = "50") int limit) {
|
||||||
|
log.info("===== 获取产品全量列表,business: {}, lastMaxId: {}, limit: {} =====",
|
||||||
|
business, lastMaxId, limit);
|
||||||
|
try {
|
||||||
|
Map<String, Object> result = ctripDistApiService.getAllProducts(business, lastMaxId, limit);
|
||||||
|
log.info("产品全量列表返回: success={}, maxId={}, productList size={}",
|
||||||
|
result.get("success"), result.get("maxId"),
|
||||||
|
result.get("productList") instanceof java.util.List
|
||||||
|
? ((java.util.List<?>) result.get("productList")).size() : 0);
|
||||||
|
return Result.succeed(result, "获取产品全量列表成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取产品全量列表失败", e);
|
||||||
|
return Result.failed("获取产品全量列表失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ==================== 辅助方法 ====================
|
// ==================== 辅助方法 ====================
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -572,8 +712,8 @@ public class CtripDistTestController {
|
|||||||
/**
|
/**
|
||||||
* 解析出行人问卷答案
|
* 解析出行人问卷答案
|
||||||
*
|
*
|
||||||
* passengers中每个出行人是一个Map,key为questionCode,value为答案值
|
* passengers中每个出行人是一个Map,key可以直接传questionCode,也可以传通用姓名字段
|
||||||
* 示例: {"P_FIRSTCNAME": "Chao", "P_LASTCNAME": "Du"}
|
* 示例: {"name": "张三"} 或 {"P_NAME": "张三"}
|
||||||
*
|
*
|
||||||
* 系统自动从缓存的问卷模板中匹配questionID和questionTitle
|
* 系统自动从缓存的问卷模板中匹配questionID和questionTitle
|
||||||
*
|
*
|
||||||
@@ -594,35 +734,28 @@ public class CtripDistTestController {
|
|||||||
List<Map<String, Object>> passengers = (List<Map<String, Object>>) passengersObj;
|
List<Map<String, Object>> passengers = (List<Map<String, Object>>) passengersObj;
|
||||||
// 构建 questionCode → 模板 的映射
|
// 构建 questionCode → 模板 的映射
|
||||||
// 携程返回的字段名是 "code"(不是 "questionCode")
|
// 携程返回的字段名是 "code"(不是 "questionCode")
|
||||||
Map<String, Map<String, Object>> templateMap = new LinkedHashMap<>();
|
Map<String, Map<String, Object>> templateMap = buildQuestionTemplateMap(questionTemplate);
|
||||||
for (Map<String, Object> q : questionTemplate) {
|
|
||||||
String code = getFieldValue(q, "code", "questionCode");
|
|
||||||
if (code != null) {
|
|
||||||
templateMap.put(code, q);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (Map<String, Object> passengerMap : passengers) {
|
for (Map<String, Object> passengerMap : passengers) {
|
||||||
List<CtripDistBookRequest.QuestionAnswer> answers = new ArrayList<>();
|
Map<String, CtripDistBookRequest.QuestionAnswer> answersByCode = new LinkedHashMap<>();
|
||||||
for (Map.Entry<String, Object> entry : passengerMap.entrySet()) {
|
for (Map.Entry<String, Object> entry : passengerMap.entrySet()) {
|
||||||
String questionCode = entry.getKey();
|
String inputKey = entry.getKey();
|
||||||
String answerValue = entry.getValue() != null ? entry.getValue().toString() : "";
|
String answerValue = entry.getValue() != null ? entry.getValue().toString() : "";
|
||||||
|
|
||||||
// 从模板匹配 questionID 和 questionTitle
|
// 从模板匹配 questionID 和 questionTitle
|
||||||
Map<String, Object> template = templateMap.get(questionCode);
|
Map<String, Object> template = resolveQuestionTemplate(inputKey, questionTemplate, templateMap);
|
||||||
if (template != null) {
|
if (template != null) {
|
||||||
CtripDistBookRequest.QuestionAnswer answer = new CtripDistBookRequest.QuestionAnswer();
|
CtripDistBookRequest.QuestionAnswer answer = buildQuestionAnswer(template, answerValue);
|
||||||
answer.setQuestionID(Long.valueOf(template.get("questionID").toString()));
|
if (answer.getQuestionCode() == null || answer.getQuestionCode().isEmpty()) {
|
||||||
answer.setQuestionCode(questionCode);
|
log.warn("questionCode={} 未能从问卷模板解析出实际 code,跳过", inputKey);
|
||||||
String title = getFieldValue(template, "title", "questionTitle");
|
|
||||||
answer.setQuestionTitle(title != null ? title : "");
|
|
||||||
answer.setAnswerList(Collections.singletonList(answerValue));
|
|
||||||
answers.add(answer);
|
|
||||||
} else {
|
} else {
|
||||||
log.warn("questionCode={} 在问卷模板中未找到,跳过", questionCode);
|
answersByCode.put(answer.getQuestionCode(), answer);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.warn("questionCode={} 在问卷模板中未找到,跳过", inputKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
result.add(answers);
|
result.add(new ArrayList<>(answersByCode.values()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -633,6 +766,84 @@ public class CtripDistTestController {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Map<String, Map<String, Object>> buildQuestionTemplateMap(List<Map<String, Object>> questionTemplate) {
|
||||||
|
Map<String, Map<String, Object>> templateMap = new LinkedHashMap<>();
|
||||||
|
for (Map<String, Object> template : questionTemplate) {
|
||||||
|
String code = getFieldValue(template, "code", "questionCode");
|
||||||
|
if (code != null && !code.isEmpty()) {
|
||||||
|
templateMap.put(code, template);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return templateMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> resolveQuestionTemplate(String inputKey,
|
||||||
|
List<Map<String, Object>> questionTemplate,
|
||||||
|
Map<String, Map<String, Object>> templateMap) {
|
||||||
|
Map<String, Object> directTemplate = templateMap.get(inputKey);
|
||||||
|
if (directTemplate != null) {
|
||||||
|
return directTemplate;
|
||||||
|
}
|
||||||
|
if (isPassengerNameKey(inputKey)) {
|
||||||
|
return findPreferredChineseNameTemplate(questionTemplate, templateMap);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> findPreferredChineseNameTemplate(List<Map<String, Object>> questionTemplate,
|
||||||
|
Map<String, Map<String, Object>> templateMap) {
|
||||||
|
return findQuestionTemplateByCodes(questionTemplate, templateMap, "P_CNAME", "P_NAME");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> findQuestionTemplateByCodes(List<Map<String, Object>> questionTemplate,
|
||||||
|
Map<String, Map<String, Object>> templateMap,
|
||||||
|
String... preferredCodes) {
|
||||||
|
for (String preferredCode : preferredCodes) {
|
||||||
|
Map<String, Object> template = templateMap.get(preferredCode);
|
||||||
|
if (template != null) {
|
||||||
|
return template;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (Map<String, Object> template : questionTemplate) {
|
||||||
|
String code = getFieldValue(template, "code", "questionCode");
|
||||||
|
for (String preferredCode : preferredCodes) {
|
||||||
|
if (preferredCode.equalsIgnoreCase(code)) {
|
||||||
|
return template;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isPassengerNameKey(String inputKey) {
|
||||||
|
if (inputKey == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return Arrays.asList("name", "passengerName", "passengerCname", "cname", "P_NAME", "P_CNAME")
|
||||||
|
.contains(inputKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private CtripDistBookRequest.QuestionAnswer buildQuestionAnswer(Map<String, Object> template, String answerValue) {
|
||||||
|
CtripDistBookRequest.QuestionAnswer answer = new CtripDistBookRequest.QuestionAnswer();
|
||||||
|
String questionId = getFieldValue(template, "questionID", "id");
|
||||||
|
if (questionId != null && !questionId.isEmpty()) {
|
||||||
|
answer.setQuestionID(Long.valueOf(questionId));
|
||||||
|
}
|
||||||
|
String questionCode = getFieldValue(template, "code", "questionCode");
|
||||||
|
answer.setQuestionCode(normalizeQuestionCode(questionCode));
|
||||||
|
String title = getFieldValue(template, "title", "questionTitle");
|
||||||
|
answer.setQuestionTitle(title != null ? title : "");
|
||||||
|
answer.setAnswerList(Collections.singletonList(answerValue));
|
||||||
|
return answer;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeQuestionCode(String questionCode) {
|
||||||
|
if ("P_NAME".equalsIgnoreCase(questionCode)) {
|
||||||
|
return "P_CNAME";
|
||||||
|
}
|
||||||
|
return questionCode != null ? questionCode : "";
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建测试下单请求(通用版)
|
* 构建测试下单请求(通用版)
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -39,6 +39,9 @@ public class CtripDistOrder {
|
|||||||
@TableField("distributor_order_id")
|
@TableField("distributor_order_id")
|
||||||
private String distributorOrderId;
|
private String distributorOrderId;
|
||||||
|
|
||||||
|
@TableField("mobile")
|
||||||
|
private String mobile;
|
||||||
|
|
||||||
@TableField("order_amount")
|
@TableField("order_amount")
|
||||||
private BigDecimal orderAmount;
|
private BigDecimal orderAmount;
|
||||||
|
|
||||||
|
|||||||
+27
@@ -98,4 +98,31 @@ public interface ICtripDistApiService {
|
|||||||
* @return 响应
|
* @return 响应
|
||||||
*/
|
*/
|
||||||
Map<String, Object> simulateConfirm(Map<String, Object> requestBody);
|
Map<String, Object> simulateConfirm(Map<String, Object> requestBody);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取位置列表
|
||||||
|
*
|
||||||
|
* @param pageIndex 页码
|
||||||
|
* @param pageSize 每页数量
|
||||||
|
* @return 位置列表
|
||||||
|
*/
|
||||||
|
Map<String, Object> getLocationList(int pageIndex, int pageSize);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取产品列表
|
||||||
|
*
|
||||||
|
* @param request 请求参数
|
||||||
|
* @return 产品列表
|
||||||
|
*/
|
||||||
|
Map<String, Object> getProductList(Map<String, Object> request);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取产品全量列表
|
||||||
|
*
|
||||||
|
* @param business 业务类型(如 ACTIVITY)
|
||||||
|
* @param lastMaxId 上次返回的maxId,首次传"0"
|
||||||
|
* @param limit 每页条数
|
||||||
|
* @return 产品全量列表
|
||||||
|
*/
|
||||||
|
Map<String, Object> getAllProducts(String business, String lastMaxId, int limit);
|
||||||
}
|
}
|
||||||
|
|||||||
+24
-1
@@ -117,12 +117,35 @@ public class CtripDistApiServiceImpl implements ICtripDistApiService {
|
|||||||
return callApi(config.getIcode().getSimulateConfirm(), requestBody, Map.class);
|
return callApi(config.getIcode().getSimulateConfirm(), requestBody, Map.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> getLocationList(int pageIndex, int pageSize) {
|
||||||
|
Map<String, Object> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("locale", "zh-CN");
|
||||||
|
requestBody.put("pageIndex", pageIndex);
|
||||||
|
requestBody.put("pageSize", pageSize);
|
||||||
|
return callApi(config.getIcode().getLocationList(), requestBody, Map.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> getProductList(Map<String, Object> request) {
|
||||||
|
return callApi(config.getIcode().getProductList(), request, Map.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> getAllProducts(String business, String lastMaxId, int limit) {
|
||||||
|
Map<String, Object> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("business", business);
|
||||||
|
requestBody.put("lastMaxId", lastMaxId);
|
||||||
|
requestBody.put("limit", limit);
|
||||||
|
return callApi(config.getIcode().getAllProducts(), requestBody, Map.class);
|
||||||
|
}
|
||||||
|
|
||||||
private <T> T callApi(String icode, Object requestBody, Class<T> responseType) {
|
private <T> T callApi(String icode, Object requestBody, Class<T> responseType) {
|
||||||
String token = tokenService.getAccessToken();
|
String token = tokenService.getAccessToken();
|
||||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||||
String url = String.format("%s?aid=%s&sid=%s&icode=%s&uuid=%s&token=%s",
|
String url = String.format("%s?aid=%s&sid=%s&icode=%s&uuid=%s&token=%s",
|
||||||
config.getApiUrl(), config.getAid(), config.getSid(), icode, uuid, token);
|
config.getApiUrl(), config.getAid(), config.getSid(), icode, uuid, token);
|
||||||
|
log.info("请求地址是:{}",url);
|
||||||
String requestJson;
|
String requestJson;
|
||||||
try {
|
try {
|
||||||
requestJson = objectMapper.writeValueAsString(requestBody);
|
requestJson = objectMapper.writeValueAsString(requestBody);
|
||||||
|
|||||||
+107
-10
@@ -16,8 +16,10 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
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.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -56,20 +58,24 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
|||||||
Map<String, Object> bookInfo = ctripDistApiService.getBookInfo(ctripProductId, packageId, resourceId);
|
Map<String, Object> bookInfo = ctripDistApiService.getBookInfo(ctripProductId, packageId, resourceId);
|
||||||
log.info("携程分销商下单填写信息,orderNo: {}, bookInfo: {}", orderNo, bookInfo);
|
log.info("携程分销商下单填写信息,orderNo: {}, bookInfo: {}", orderNo, bookInfo);
|
||||||
|
|
||||||
// 校验产品是否要求额外乘客问卷(如身份证等),如果要求则无法自动下单
|
// 校验问卷是否属于当前支持自动填充的范围
|
||||||
validateBookInfo(bookInfo, orderNo);
|
validateBookInfo(bookInfo, orderNo);
|
||||||
|
|
||||||
String distributorOrderId = orderNo;
|
String distributorOrderId = orderNo;
|
||||||
BigDecimal amountYuan = new BigDecimal(orderAmount).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
|
BigDecimal amountYuan = new BigDecimal(orderAmount).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
|
||||||
CtripDistBookRequest request = buildBookRequest(distributorOrderId, ctripProductId, packageId, resourceId, amountYuan, mobile);
|
CtripDistBookRequest checkRequest = buildBookRequest(
|
||||||
|
distributorOrderId, ctripProductId, packageId, resourceId, amountYuan, mobile, bookInfo, false);
|
||||||
|
|
||||||
// 可订检查:下单前确认资源可预订
|
// 可订检查:下单前确认资源可预订
|
||||||
boolean available = ctripDistApiService.checkAvailability(request);
|
boolean available = ctripDistApiService.checkAvailability(checkRequest);
|
||||||
if (!available) {
|
if (!available) {
|
||||||
throw new RuntimeException("携程可订检查失败,资源不可预订,orderNo: " + orderNo);
|
throw new RuntimeException("携程可订检查失败,资源不可预订,orderNo: " + orderNo);
|
||||||
}
|
}
|
||||||
log.info("携程可订检查通过,orderNo: {}", orderNo);
|
log.info("携程可订检查通过,orderNo: {}", orderNo);
|
||||||
|
|
||||||
|
CtripDistBookRequest createRequest = buildBookRequest(
|
||||||
|
distributorOrderId, ctripProductId, packageId, resourceId, amountYuan, mobile, bookInfo, true);
|
||||||
|
|
||||||
CtripDistOrder order = new CtripDistOrder();
|
CtripDistOrder order = new CtripDistOrder();
|
||||||
order.setTenantId(tenantId);
|
order.setTenantId(tenantId);
|
||||||
order.setOrderNo(orderNo);
|
order.setOrderNo(orderNo);
|
||||||
@@ -77,6 +83,7 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
|||||||
order.setCtripPackageId(packageId);
|
order.setCtripPackageId(packageId);
|
||||||
order.setCtripResourceId(resourceId);
|
order.setCtripResourceId(resourceId);
|
||||||
order.setDistributorOrderId(distributorOrderId);
|
order.setDistributorOrderId(distributorOrderId);
|
||||||
|
order.setMobile(mobile);
|
||||||
order.setOrderAmount(amountYuan);
|
order.setOrderAmount(amountYuan);
|
||||||
order.setCurrency(config.getCurrency());
|
order.setCurrency(config.getCurrency());
|
||||||
order.setCtripOrderStatus("CREATING");
|
order.setCtripOrderStatus("CREATING");
|
||||||
@@ -87,7 +94,7 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
|||||||
ctripDistOrderMapper.insert(order);
|
ctripDistOrderMapper.insert(order);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
CtripDistBookResponse response = ctripDistApiService.createOrder(request);
|
CtripDistBookResponse response = ctripDistApiService.createOrder(createRequest);
|
||||||
if (response != null && response.isSuccess() && response.getData() != null && response.getData().getOrderId() != null) {
|
if (response != null && response.isSuccess() && response.getData() != null && response.getData().getOrderId() != null) {
|
||||||
order.setCtripOrderId(response.getData().getOrderId());
|
order.setCtripOrderId(response.getData().getOrderId());
|
||||||
order.setCtripOrderStatus("CONFIRMED");
|
order.setCtripOrderStatus("CONFIRMED");
|
||||||
@@ -164,7 +171,8 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
|||||||
private static final String DEFAULT_CONTACT_EMAIL = "1098974448@qq.com";
|
private static final String DEFAULT_CONTACT_EMAIL = "1098974448@qq.com";
|
||||||
|
|
||||||
private CtripDistBookRequest buildBookRequest(String distributorOrderId, Long productId, Long packageId,
|
private CtripDistBookRequest buildBookRequest(String distributorOrderId, Long productId, Long packageId,
|
||||||
Long resourceId, BigDecimal amountYuan, String userMobile) {
|
Long resourceId, BigDecimal amountYuan, String userMobile,
|
||||||
|
Map<String, Object> bookInfo, boolean includeAreaCode) {
|
||||||
CtripDistBookRequest request = new CtripDistBookRequest();
|
CtripDistBookRequest request = new CtripDistBookRequest();
|
||||||
request.setLocale(config.getLocale());
|
request.setLocale(config.getLocale());
|
||||||
request.setCurrency(config.getCurrency());
|
request.setCurrency(config.getCurrency());
|
||||||
@@ -184,7 +192,7 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
|||||||
CtripDistBookRequest.Passenger passenger = new CtripDistBookRequest.Passenger();
|
CtripDistBookRequest.Passenger passenger = new CtripDistBookRequest.Passenger();
|
||||||
passenger.setPackageID(packageId);
|
passenger.setPackageID(packageId);
|
||||||
passenger.setResourceID(resourceId);
|
passenger.setResourceID(resourceId);
|
||||||
passenger.setQuestionAnswerList(new ArrayList<>());
|
passenger.setQuestionAnswerList(buildPassengerQuestionAnswers(bookInfo, contactMobile, includeAreaCode));
|
||||||
request.setPassengerList(Collections.singletonList(passenger));
|
request.setPassengerList(Collections.singletonList(passenger));
|
||||||
|
|
||||||
CtripDistBookRequest.OrderResource orderResource = new CtripDistBookRequest.OrderResource();
|
CtripDistBookRequest.OrderResource orderResource = new CtripDistBookRequest.OrderResource();
|
||||||
@@ -202,6 +210,33 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
|||||||
return request;
|
return request;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private List<CtripDistBookRequest.QuestionAnswer> buildPassengerQuestionAnswers(Map<String, Object> bookInfo,
|
||||||
|
String contactMobile,
|
||||||
|
boolean includeAreaCode) {
|
||||||
|
List<CtripDistBookRequest.QuestionAnswer> answers = new ArrayList<>();
|
||||||
|
if (bookInfo == null || bookInfo.get("data") == null) {
|
||||||
|
return answers;
|
||||||
|
}
|
||||||
|
Map<String, Object> data = (Map<String, Object>) bookInfo.get("data");
|
||||||
|
Object questionList = data.get("passengerQuestionList");
|
||||||
|
if (!(questionList instanceof List)) {
|
||||||
|
return answers;
|
||||||
|
}
|
||||||
|
for (Object item : (List<?>) questionList) {
|
||||||
|
if (!(item instanceof Map)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Map<String, Object> question = (Map<String, Object>) item;
|
||||||
|
String answerValue = resolvePassengerAnswerValue(question, contactMobile, includeAreaCode);
|
||||||
|
if (answerValue == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
answers.add(buildQuestionAnswer(question, answerValue));
|
||||||
|
}
|
||||||
|
return answers;
|
||||||
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private Long extractPackageId(Map<String, Object> productDetail) {
|
private Long extractPackageId(Map<String, Object> productDetail) {
|
||||||
Map<String, Object> data = (Map<String, Object>) productDetail.get("data");
|
Map<String, Object> data = (Map<String, Object>) productDetail.get("data");
|
||||||
@@ -226,7 +261,7 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 校验下单填写信息
|
* 校验下单填写信息
|
||||||
* 如果产品要求额外乘客问卷(如身份证等),当前平台无法提供,拒绝自动下单
|
* 当前仅支持自动填充姓名、手机号和手机号区号
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private void validateBookInfo(Map<String, Object> bookInfo, String orderNo) {
|
private void validateBookInfo(Map<String, Object> bookInfo, String orderNo) {
|
||||||
@@ -237,10 +272,72 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
|||||||
Map<String, Object> data = (Map<String, Object>) bookInfo.get("data");
|
Map<String, Object> data = (Map<String, Object>) bookInfo.get("data");
|
||||||
Object questionList = data.get("passengerQuestionList");
|
Object questionList = data.get("passengerQuestionList");
|
||||||
if (questionList instanceof List) {
|
if (questionList instanceof List) {
|
||||||
List<?> questions = (List<?>) questionList;
|
Set<String> unsupportedCodes = new LinkedHashSet<>();
|
||||||
if (!questions.isEmpty()) {
|
for (Object item : (List<?>) questionList) {
|
||||||
throw new RuntimeException("该携程产品要求填写额外乘客信息(如身份证等),无法自动下单,orderNo: " + orderNo);
|
if (!(item instanceof Map)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Map<String, Object> question = (Map<String, Object>) item;
|
||||||
|
String questionCode = normalizeQuestionCode(getFieldValue(question, "code", "questionCode"));
|
||||||
|
if (!isSupportedPassengerQuestion(questionCode)) {
|
||||||
|
unsupportedCodes.add(questionCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!unsupportedCodes.isEmpty()) {
|
||||||
|
throw new RuntimeException("该携程产品包含暂不支持自动填写的乘客信息,questionCode="
|
||||||
|
+ unsupportedCodes + ",orderNo: " + orderNo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean isSupportedPassengerQuestion(String questionCode) {
|
||||||
|
return "P_CNAME".equalsIgnoreCase(questionCode)
|
||||||
|
|| "P_TELPHONE".equalsIgnoreCase(questionCode)
|
||||||
|
|| "P_TELPHONE_AREA_CODE".equalsIgnoreCase(questionCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolvePassengerAnswerValue(Map<String, Object> question, String contactMobile,
|
||||||
|
boolean includeAreaCode) {
|
||||||
|
String questionCode = normalizeQuestionCode(getFieldValue(question, "code", "questionCode"));
|
||||||
|
if ("P_CNAME".equalsIgnoreCase(questionCode)) {
|
||||||
|
return DEFAULT_CONTACT_NAME;
|
||||||
|
}
|
||||||
|
if ("P_TELPHONE".equalsIgnoreCase(questionCode)) {
|
||||||
|
return contactMobile;
|
||||||
|
}
|
||||||
|
if ("P_TELPHONE_AREA_CODE".equalsIgnoreCase(questionCode)) {
|
||||||
|
return includeAreaCode ? "+86" : null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CtripDistBookRequest.QuestionAnswer buildQuestionAnswer(Map<String, Object> question, String answerValue) {
|
||||||
|
CtripDistBookRequest.QuestionAnswer answer = new CtripDistBookRequest.QuestionAnswer();
|
||||||
|
String questionId = getFieldValue(question, "questionID", "id");
|
||||||
|
if (questionId != null && !questionId.isEmpty()) {
|
||||||
|
answer.setQuestionID(Long.valueOf(questionId));
|
||||||
|
}
|
||||||
|
answer.setQuestionCode(normalizeQuestionCode(getFieldValue(question, "code", "questionCode")));
|
||||||
|
String title = getFieldValue(question, "title", "questionTitle");
|
||||||
|
answer.setQuestionTitle(title != null ? title : "");
|
||||||
|
answer.setAnswerList(Collections.singletonList(answerValue));
|
||||||
|
return answer;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeQuestionCode(String questionCode) {
|
||||||
|
if ("P_NAME".equalsIgnoreCase(questionCode)) {
|
||||||
|
return "P_CNAME";
|
||||||
|
}
|
||||||
|
return questionCode != null ? questionCode : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getFieldValue(Map<String, Object> map, String... keys) {
|
||||||
|
for (String key : keys) {
|
||||||
|
Object value = map.get(key);
|
||||||
|
if (value != null) {
|
||||||
|
return value.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+143
-42
@@ -1,16 +1,26 @@
|
|||||||
package com.central.coupon.task;
|
package com.central.coupon.task;
|
||||||
|
|
||||||
|
import com.central.coupon.controller.CtripConsumedController;
|
||||||
|
import com.central.coupon.entity.CtripContact;
|
||||||
import com.central.coupon.entity.CtripDistOrder;
|
import com.central.coupon.entity.CtripDistOrder;
|
||||||
|
import com.central.coupon.entity.CtripOrder;
|
||||||
|
import com.central.coupon.entity.CtripOrderItem;
|
||||||
|
import com.central.coupon.mapper.CtripContactMapper;
|
||||||
import com.central.coupon.mapper.CtripDistOrderMapper;
|
import com.central.coupon.mapper.CtripDistOrderMapper;
|
||||||
import com.central.coupon.model.CtripDistBookingDetailResponse;
|
import com.central.coupon.mapper.CtripOrderItemMapper;
|
||||||
import com.central.coupon.service.ICtripDistApiService;
|
import com.central.coupon.mapper.CtripOrderMapper;
|
||||||
|
import com.central.coupon.model.CtripConsumedNoticeResponse;
|
||||||
|
import com.central.coupon.service.CtripConsumedService;
|
||||||
|
import com.central.coupon.service.IOrderDetailService;
|
||||||
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.scheduling.annotation.Scheduled;
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
@@ -20,7 +30,19 @@ public class CtripDistConsumeTask {
|
|||||||
private CtripDistOrderMapper ctripDistOrderMapper;
|
private CtripDistOrderMapper ctripDistOrderMapper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ICtripDistApiService ctripDistApiService;
|
private CtripContactMapper ctripContactMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripOrderMapper ctripOrderMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripOrderItemMapper ctripOrderItemMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripConsumedService ctripConsumedService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private IOrderDetailService orderDetailService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 每天凌晨3点执行:核销2天前创建且未核销的携程分销订单
|
* 每天凌晨3点执行:核销2天前创建且未核销的携程分销订单
|
||||||
@@ -29,17 +51,18 @@ public class CtripDistConsumeTask {
|
|||||||
public void autoConsumeCtripDistOrders() {
|
public void autoConsumeCtripDistOrders() {
|
||||||
log.info("开始自动核销携程分销订单");
|
log.info("开始自动核销携程分销订单");
|
||||||
try {
|
try {
|
||||||
List<CtripDistOrder> pendingOrders = ctripDistOrderMapper.selectPendingConsumeOrders(2);
|
// 1. 查询2天前创建且未核销的CtripDistOrder
|
||||||
|
List<CtripDistOrder> pendingOrders = ctripDistOrderMapper.selectPendingConsumeOrders(3);
|
||||||
log.info("待核销的携程分销订单数量: {}", pendingOrders.size());
|
log.info("待核销的携程分销订单数量: {}", pendingOrders.size());
|
||||||
|
|
||||||
for (CtripDistOrder order : pendingOrders) {
|
for (CtripDistOrder distOrder : pendingOrders) {
|
||||||
try {
|
try {
|
||||||
consumeOrder(order);
|
consumeOrder(distOrder);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("核销携程分销订单失败,orderNo: {}", order.getOrderNo(), e);
|
log.error("核销携程分销订单失败,orderNo: {}", distOrder.getOrderNo(), e);
|
||||||
order.setConsumeStatus(2);
|
distOrder.setConsumeStatus(2);
|
||||||
order.setErrorMsg("核销失败: " + e.getMessage());
|
distOrder.setErrorMsg("核销失败: " + e.getMessage());
|
||||||
ctripDistOrderMapper.updateById(order);
|
ctripDistOrderMapper.updateById(distOrder);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.info("携程分销订单自动核销完成");
|
log.info("携程分销订单自动核销完成");
|
||||||
@@ -48,43 +71,121 @@ public class CtripDistConsumeTask {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private void consumeOrder(CtripDistOrder distOrder) {
|
||||||
* 核销单个订单
|
String mobile = distOrder.getMobile();
|
||||||
* 先查询携程订单状态确认为CONFIRMED,然后标记为已核销
|
log.info("开始核销携程分销订单,orderNo: {}, mobile: {}", distOrder.getOrderNo(), mobile);
|
||||||
*/
|
|
||||||
private void consumeOrder(CtripDistOrder order) {
|
|
||||||
log.info("开始核销携程分销订单,orderNo: {}, ctripOrderId: {}",
|
|
||||||
order.getOrderNo(), order.getCtripOrderId());
|
|
||||||
|
|
||||||
// 查询携程订单当前状态
|
if (mobile == null || mobile.isEmpty()) {
|
||||||
CtripDistBookingDetailResponse detail = ctripDistApiService.getOrderDetail(order.getCtripOrderId());
|
distOrder.setConsumeStatus(2);
|
||||||
if (detail != null && detail.isSuccess() && detail.getData() != null
|
distOrder.setErrorMsg("分销订单手机号为空,无法核销");
|
||||||
&& detail.getData().getOrder() != null) {
|
ctripDistOrderMapper.updateById(distOrder);
|
||||||
String ctripStatus = detail.getData().getOrder().getOrderStatus();
|
log.warn("分销订单手机号为空,跳过核销,orderNo: {}", distOrder.getOrderNo());
|
||||||
log.info("携程订单当前状态: {}, orderNo: {}", ctripStatus, order.getOrderNo());
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if ("CONFIRMED".equals(ctripStatus)) {
|
// 2. 根据手机号通过联系人表查找CtripOrder
|
||||||
// 订单状态正常,执行核销
|
List<CtripContact> contacts = ctripContactMapper.selectByMobile(mobile);
|
||||||
order.setConsumeStatus(1);
|
if (contacts == null || contacts.isEmpty()) {
|
||||||
order.setConsumeTime(LocalDateTime.now());
|
distOrder.setConsumeStatus(2);
|
||||||
order.setCtripOrderStatus("CONSUMED");
|
distOrder.setErrorMsg("未找到手机号对应的携程联系人记录");
|
||||||
ctripDistOrderMapper.updateById(order);
|
ctripDistOrderMapper.updateById(distOrder);
|
||||||
log.info("携程分销订单核销成功,orderNo: {}", order.getOrderNo());
|
log.warn("未找到手机号 {} 对应的联系人记录,orderNo: {}", mobile, distOrder.getOrderNo());
|
||||||
} else if ("CANCELLED".equals(ctripStatus) || "CANCELLED_RESERVATION".equals(ctripStatus)) {
|
return;
|
||||||
// 订单已被取消,更新状态
|
}
|
||||||
order.setCtripOrderStatus(ctripStatus);
|
|
||||||
order.setConsumeStatus(2);
|
List<Long> orderIds = contacts.stream()
|
||||||
order.setErrorMsg("携程订单已被取消,无法核销");
|
.map(CtripContact::getOrderId)
|
||||||
ctripDistOrderMapper.updateById(order);
|
.distinct()
|
||||||
log.warn("携程订单已取消,跳过核销,orderNo: {}", order.getOrderNo());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
// 筛选状态为PAYMENT_CONFIRMED(13)的订单
|
||||||
|
List<CtripOrder> confirmedOrders = new ArrayList<>();
|
||||||
|
for (Long orderId : orderIds) {
|
||||||
|
CtripOrder ctripOrder = ctripOrderMapper.selectById(orderId);
|
||||||
|
if (ctripOrder != null && Integer.valueOf(13).equals(ctripOrder.getStatus())) {
|
||||||
|
confirmedOrders.add(ctripOrder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (confirmedOrders.isEmpty()) {
|
||||||
|
distOrder.setConsumeStatus(2);
|
||||||
|
distOrder.setErrorMsg("未找到状态为PAYMENT_CONFIRMED的携程订单");
|
||||||
|
ctripDistOrderMapper.updateById(distOrder);
|
||||||
|
log.warn("手机号 {} 无PAYMENT_CONFIRMED状态的订单,orderNo: {}", mobile, distOrder.getOrderNo());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 对每个符合条件的CtripOrder执行核销
|
||||||
|
boolean anySuccess = false;
|
||||||
|
StringBuilder errorMsgs = new StringBuilder();
|
||||||
|
|
||||||
|
for (CtripOrder ctripOrder : confirmedOrders) {
|
||||||
|
try {
|
||||||
|
// 建立订单关联关系
|
||||||
|
if (ctripOrder.getOrderNo() == null || ctripOrder.getOrderNo().trim().isEmpty()) {
|
||||||
|
ctripOrder.setOrderNo(distOrder.getOrderNo());
|
||||||
|
ctripOrderMapper.updateById(ctripOrder);
|
||||||
|
log.info("建立订单关联关系,otaOrderId: {}, orderNo: {}", ctripOrder.getOtaOrderId(), distOrder.getOrderNo());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证订单是否可核销
|
||||||
|
if (!orderDetailService.validateOrderForConsume(ctripOrder.getOtaOrderId())) {
|
||||||
|
log.warn("订单不可核销,otaOrderId: {}", ctripOrder.getOtaOrderId());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询订单项,逐项核销
|
||||||
|
List<CtripOrderItem> orderItems = ctripOrderItemMapper.selectByOrderId(ctripOrder.getId());
|
||||||
|
if (orderItems == null || orderItems.isEmpty()) {
|
||||||
|
log.warn("订单无订单项,otaOrderId: {}", ctripOrder.getOtaOrderId());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (CtripOrderItem item : orderItems) {
|
||||||
|
if (item.getQuantity() == null || item.getQuantity() <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
CtripConsumedController.CtripConsumeRequest request = new CtripConsumedController.CtripConsumeRequest();
|
||||||
|
request.setOtaOrderId(ctripOrder.getOtaOrderId());
|
||||||
|
request.setSupplierOrderId(ctripOrder.getSupplierOrderId());
|
||||||
|
request.setItemId(item.getItemId());
|
||||||
|
request.setUseQuantity(item.getQuantity());
|
||||||
|
request.setRemark("分销订单自动核销,orderNo: " + distOrder.getOrderNo());
|
||||||
|
|
||||||
|
CtripConsumedNoticeResponse response = ctripConsumedService.consumeOrder(request);
|
||||||
|
boolean success = response != null && "0000".equals(response.getHeader().getResultCode());
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
log.info("核销成功,otaOrderId: {}, itemId: {}", ctripOrder.getOtaOrderId(), item.getItemId());
|
||||||
|
anySuccess = true;
|
||||||
} else {
|
} else {
|
||||||
log.warn("携程订单状态不适合核销: {},orderNo: {}", ctripStatus, order.getOrderNo());
|
String errMsg = response != null ? response.getHeader().getResultMessage() : "未知错误";
|
||||||
|
log.error("核销失败,otaOrderId: {}, itemId: {}, error: {}", ctripOrder.getOtaOrderId(), item.getItemId(), errMsg);
|
||||||
|
errorMsgs.append("otaOrderId=").append(ctripOrder.getOtaOrderId())
|
||||||
|
.append(",itemId=").append(item.getItemId())
|
||||||
|
.append(":").append(errMsg).append("; ");
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("核销携程订单异常,otaOrderId: {}", ctripOrder.getOtaOrderId(), e);
|
||||||
|
errorMsgs.append("otaOrderId=").append(ctripOrder.getOtaOrderId())
|
||||||
|
.append(":").append(e.getMessage()).append("; ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 更新CtripDistOrder状态
|
||||||
|
if (anySuccess) {
|
||||||
|
distOrder.setConsumeStatus(1);
|
||||||
|
distOrder.setConsumeTime(LocalDateTime.now());
|
||||||
|
distOrder.setCtripOrderStatus("CONSUMED");
|
||||||
|
distOrder.setErrorMsg(errorMsgs.length() > 0 ? "部分核销异常: " + errorMsgs : null);
|
||||||
|
log.info("携程分销订单核销成功,orderNo: {}", distOrder.getOrderNo());
|
||||||
} else {
|
} else {
|
||||||
log.error("查询携程订单详情失败,orderNo: {}", order.getOrderNo());
|
distOrder.setConsumeStatus(2);
|
||||||
order.setConsumeStatus(2);
|
distOrder.setErrorMsg(errorMsgs.length() > 0 ? errorMsgs.toString() : "所有订单核销均失败");
|
||||||
order.setErrorMsg("查询携程订单详情失败");
|
log.warn("携程分销订单核销失败,orderNo: {}", distOrder.getOrderNo());
|
||||||
ctripDistOrderMapper.updateById(order);
|
|
||||||
}
|
}
|
||||||
|
ctripDistOrderMapper.updateById(distOrder);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+170
@@ -28,6 +28,7 @@ import org.springframework.beans.factory.annotation.Value;
|
|||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -275,6 +276,87 @@ public class DeviceCommandController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行 - 首次飞向目标点
|
||||||
|
* 创建 fly_to_point 会话,flyToId = missionCode
|
||||||
|
*/
|
||||||
|
@Operation(summary = "无人机指点飞行 - 飞向目标")
|
||||||
|
@PostMapping("/flyToPoint")
|
||||||
|
public Result<String> flyToPoint(@RequestBody FlyToPointRequest request) {
|
||||||
|
log.info("收到指点飞行(首次)命令: device={}, flyToId={}, target=({}, {}, {})",
|
||||||
|
request.getDeviceSn(), request.getFlyToId(),
|
||||||
|
request.getLatitude(), request.getLongitude(), request.getHeight());
|
||||||
|
|
||||||
|
try {
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("fly_to_id", request.getFlyToId());
|
||||||
|
params.put("latitude", request.getLatitude());
|
||||||
|
params.put("longitude", request.getLongitude());
|
||||||
|
params.put("height", request.getHeight() != null ? request.getHeight() : 100f);
|
||||||
|
params.put("max_speed", request.getMaxSpeed() != null ? request.getMaxSpeed() : 12f);
|
||||||
|
|
||||||
|
String commandId = commandManager.sendCommand(
|
||||||
|
request.getDeviceSn(),
|
||||||
|
"fly_to_point",
|
||||||
|
params
|
||||||
|
);
|
||||||
|
return Result.succeed(commandId, "指点飞行命令已发送");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("发送指点飞行命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
|
||||||
|
return Result.failed("命令发送失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行 - 更新目标点(连续指点)
|
||||||
|
* 打断当前飞行,立即转向新目标;设备协议不含 fly_to_id,仅传 max_speed + points
|
||||||
|
*/
|
||||||
|
@Operation(summary = "无人机指点飞行 - 更新目标点")
|
||||||
|
@PostMapping("/flyToPointUpdate")
|
||||||
|
public Result<String> flyToPointUpdate(@RequestBody FlyToPointUpdateRequest request) {
|
||||||
|
log.info("收到指点飞行(更新)命令: device={}, target=({}, {}, {})",
|
||||||
|
request.getDeviceSn(), request.getLatitude(), request.getLongitude(), request.getHeight());
|
||||||
|
|
||||||
|
try {
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("latitude", request.getLatitude());
|
||||||
|
params.put("longitude", request.getLongitude());
|
||||||
|
params.put("height", request.getHeight() != null ? request.getHeight() : 100f);
|
||||||
|
params.put("max_speed", request.getMaxSpeed() != null ? request.getMaxSpeed() : 12f);
|
||||||
|
|
||||||
|
String commandId = commandManager.sendCommand(
|
||||||
|
request.getDeviceSn(),
|
||||||
|
"fly_to_point_update",
|
||||||
|
params
|
||||||
|
);
|
||||||
|
return Result.succeed(commandId, "目标更新命令已发送");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("发送目标更新命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
|
||||||
|
return Result.failed("命令发送失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行 - 停止指点飞行
|
||||||
|
*/
|
||||||
|
@Operation(summary = "无人机指点飞行 - 停止")
|
||||||
|
@PostMapping("/flyToPointStop")
|
||||||
|
public Result<String> flyToPointStop(@RequestParam String deviceSn) {
|
||||||
|
log.info("收到停止指点飞行命令: device={}", deviceSn);
|
||||||
|
|
||||||
|
try {
|
||||||
|
String commandId = commandManager.sendCommand(
|
||||||
|
deviceSn,
|
||||||
|
"fly_to_point_stop",
|
||||||
|
new JSONObject()
|
||||||
|
);
|
||||||
|
return Result.succeed(commandId, "停止指点飞行命令已发送");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("发送停止指点飞行命令失败: device={}, error={}", deviceSn, e.getMessage());
|
||||||
|
return Result.failed("命令发送失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 开始录像
|
* 开始录像
|
||||||
*/
|
*/
|
||||||
@@ -425,6 +507,57 @@ public class DeviceCommandController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 切换直播镜头(如切换到变焦镜头)
|
||||||
|
*/
|
||||||
|
@Operation(summary = "切换直播镜头")
|
||||||
|
@PostMapping("/liveLensChange")
|
||||||
|
public Result<String> liveLensChange(@RequestBody Map<String, Object> request) {
|
||||||
|
String deviceSn = (String) request.get("deviceSn");
|
||||||
|
String videoType = (String) request.get("videoType");
|
||||||
|
|
||||||
|
log.info("切换直播镜头: device={}, videoType={}", deviceSn, videoType);
|
||||||
|
|
||||||
|
try {
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("video_type", videoType != null ? videoType : "zoom");
|
||||||
|
|
||||||
|
String commandId = commandManager.sendCommand(deviceSn, "live_lens_change", params);
|
||||||
|
return Result.succeed(commandId, "镜头切换命令已发送");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("切换镜头失败: device={}, error={}", deviceSn, e.getMessage());
|
||||||
|
return Result.failed("命令发送失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置变焦倍数
|
||||||
|
*/
|
||||||
|
@Operation(summary = "设置变焦倍数")
|
||||||
|
@PostMapping("/cameraFocalLengthSet")
|
||||||
|
public Result<String> cameraFocalLengthSet(@RequestBody Map<String, Object> request) {
|
||||||
|
String deviceSn = (String) request.get("deviceSn");
|
||||||
|
Double zoomFactor = request.get("zoomFactor") != null ?
|
||||||
|
Double.parseDouble(request.get("zoomFactor").toString()) : 2.0;
|
||||||
|
|
||||||
|
// 范围限制 2~200
|
||||||
|
zoomFactor = Math.max(2, Math.min(200, zoomFactor));
|
||||||
|
|
||||||
|
log.info("设置变焦: device={}, zoomFactor={}", deviceSn, zoomFactor);
|
||||||
|
|
||||||
|
try {
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("camera_type", "zoom");
|
||||||
|
params.put("zoom_factor", zoomFactor);
|
||||||
|
|
||||||
|
String commandId = commandManager.sendCommand(deviceSn, "camera_focal_length_set", params);
|
||||||
|
return Result.succeed(commandId, "变焦命令已发送");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("设置变焦失败: device={}, error={}", deviceSn, e.getMessage());
|
||||||
|
return Result.failed("命令发送失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 执行航线任务
|
* 执行航线任务
|
||||||
* 参考writeProperties逻辑,用于航线任务执行(不包含订单业务逻辑和幂等性检查)
|
* 参考writeProperties逻辑,用于航线任务执行(不包含订单业务逻辑和幂等性检查)
|
||||||
@@ -646,6 +779,43 @@ public class DeviceCommandController {
|
|||||||
private Boolean locked;
|
private Boolean locked;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行(首次飞向目标)请求参数
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public static class FlyToPointRequest {
|
||||||
|
/** 设备SN */
|
||||||
|
private String deviceSn;
|
||||||
|
/** 飞行会话ID(= missionCode) */
|
||||||
|
private String flyToId;
|
||||||
|
/** 目标纬度 */
|
||||||
|
private Double latitude;
|
||||||
|
/** 目标经度 */
|
||||||
|
private Double longitude;
|
||||||
|
/** 目标椭球高(前端计算:Cartographic.height + 用户飞行高度) */
|
||||||
|
private Float height;
|
||||||
|
/** 最大飞行速度(m/s),默认 12 */
|
||||||
|
private Float maxSpeed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行更新目标(连续指点)请求参数
|
||||||
|
* 注意:设备协议不含 fly_to_id,仅传 max_speed + points
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public static class FlyToPointUpdateRequest {
|
||||||
|
/** 设备SN */
|
||||||
|
private String deviceSn;
|
||||||
|
/** 目标纬度 */
|
||||||
|
private Double latitude;
|
||||||
|
/** 目标经度 */
|
||||||
|
private Double longitude;
|
||||||
|
/** 目标椭球高 */
|
||||||
|
private Float height;
|
||||||
|
/** 最大飞行速度(m/s),默认 12 */
|
||||||
|
private Float maxSpeed;
|
||||||
|
}
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public static class CommandStatusDTO {
|
public static class CommandStatusDTO {
|
||||||
private String commandId;
|
private String commandId;
|
||||||
|
|||||||
+1
-1
@@ -10,7 +10,7 @@ public enum ControlEnum {
|
|||||||
TAKEOFF_TO_POINT("takeoff_to_point"),
|
TAKEOFF_TO_POINT("takeoff_to_point"),
|
||||||
FLY_TO_POINT("fly_to_point"),
|
FLY_TO_POINT("fly_to_point"),
|
||||||
FLY_TO_POINT_STOP("fly_to_point_stop"),
|
FLY_TO_POINT_STOP("fly_to_point_stop"),
|
||||||
FLY_TO_POINT_UPDATE("fly_to_point_stop"),
|
FLY_TO_POINT_UPDATE("fly_to_point_update"),
|
||||||
FLIGHTTASK_PAUSE("flighttask_pause"),
|
FLIGHTTASK_PAUSE("flighttask_pause"),
|
||||||
FLIGHTTASK_PREPARE ("flighttask_prepare"),
|
FLIGHTTASK_PREPARE ("flighttask_prepare"),
|
||||||
FLIGHTTASK_RECOVERY("flighttask_recovery"),
|
FLIGHTTASK_RECOVERY("flighttask_recovery"),
|
||||||
|
|||||||
+15
@@ -88,5 +88,20 @@ public class ControlMessageConstant {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public final static String LIVE_LENS_CHANGE = "{\n" +
|
||||||
|
"\t\"data\": {\n" +
|
||||||
|
"\t\t\"video_type\": video_type\n" +
|
||||||
|
"\t},\n" +
|
||||||
|
"\t\"method\": \"live_lens_change\"\n" +
|
||||||
|
"}";
|
||||||
|
|
||||||
|
public final static String CAMERA_FOCAL_LENGTH_SET = "{\n" +
|
||||||
|
"\t\"data\": {\n" +
|
||||||
|
"\t\t\"camera_type\": camera_type,\n" +
|
||||||
|
"\t\t\"zoom_factor\": zoom_factor\n" +
|
||||||
|
"\t},\n" +
|
||||||
|
"\t\"method\": \"camera_focal_length_set\"\n" +
|
||||||
|
"}";
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+167
-3
@@ -147,7 +147,8 @@ public class DeviceCommandManager {
|
|||||||
parameter.put("properties", properties);
|
parameter.put("properties", properties);
|
||||||
|
|
||||||
JSONObject headers = new JSONObject();
|
JSONObject headers = new JSONObject();
|
||||||
headers.put("async", false);
|
// 指点飞行的下发、更新和停止均由设备异步执行,其余命令维持原有同步应答语义。
|
||||||
|
headers.put("async", requiresAsyncHeader(command.getCommandType()));
|
||||||
parameter.put("headers", headers);
|
parameter.put("headers", headers);
|
||||||
|
|
||||||
// 构造完整消息
|
// 构造完整消息
|
||||||
@@ -267,6 +268,43 @@ public class DeviceCommandManager {
|
|||||||
data.put("locked", params.getBooleanValue("locked"));
|
data.put("locked", params.getBooleanValue("locked"));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case "live_lens_change":
|
||||||
|
// 切换直播镜头
|
||||||
|
data.put("video_type", params.getString("video_type"));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "camera_focal_length_set":
|
||||||
|
// 设置变焦倍数
|
||||||
|
data.put("camera_type", params.getString("camera_type"));
|
||||||
|
data.put("zoom_factor", params.getDoubleValue("zoom_factor"));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "fly_to_point":
|
||||||
|
// 首次飞向目标点(生成 fly_to_id 会话)
|
||||||
|
data.put("fly_to_id", params.getString("fly_to_id"));
|
||||||
|
data.put("max_speed", params.getFloatValue("max_speed"));
|
||||||
|
// points 数组
|
||||||
|
JSONObject pointFirst = new JSONObject();
|
||||||
|
pointFirst.put("height", params.getFloatValue("height"));
|
||||||
|
pointFirst.put("latitude", params.getDoubleValue("latitude"));
|
||||||
|
pointFirst.put("longitude", params.getDoubleValue("longitude"));
|
||||||
|
data.put("points", new JSONObject[]{pointFirst});
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "fly_to_point_update":
|
||||||
|
// 更新目标点(设备协议无 fly_to_id,仅 max_speed + points)
|
||||||
|
data.put("max_speed", params.getFloatValue("max_speed"));
|
||||||
|
JSONObject pointUpdate = new JSONObject();
|
||||||
|
pointUpdate.put("height", params.getFloatValue("height"));
|
||||||
|
pointUpdate.put("latitude", params.getDoubleValue("latitude"));
|
||||||
|
pointUpdate.put("longitude", params.getDoubleValue("longitude"));
|
||||||
|
data.put("points", new JSONObject[]{pointUpdate});
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "fly_to_point_stop":
|
||||||
|
// 停止指点飞行 - 无参数
|
||||||
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
// 其他命令,直接使用 params 作为 data
|
// 其他命令,直接使用 params 作为 data
|
||||||
data = params;
|
data = params;
|
||||||
@@ -275,8 +313,8 @@ public class DeviceCommandManager {
|
|||||||
|
|
||||||
properties.put("method", method);
|
properties.put("method", method);
|
||||||
|
|
||||||
// 一键起飞命令需要 data.data 的嵌套结构,其他命令直接使用 data
|
// 设备协议要求任务型飞行命令使用 data.data 嵌套结构。
|
||||||
if ("takeoff_to_point".equals(method)) {
|
if (requiresNestedDataWrapper(method)) {
|
||||||
JSONObject dataWrapper = new JSONObject();
|
JSONObject dataWrapper = new JSONObject();
|
||||||
dataWrapper.put("data", data);
|
dataWrapper.put("data", data);
|
||||||
properties.put("data", dataWrapper);
|
properties.put("data", dataWrapper);
|
||||||
@@ -287,6 +325,18 @@ public class DeviceCommandManager {
|
|||||||
return properties;
|
return properties;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean requiresNestedDataWrapper(String method) {
|
||||||
|
return "takeoff_to_point".equals(method)
|
||||||
|
|| "fly_to_point".equals(method)
|
||||||
|
|| "fly_to_point_update".equals(method);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean requiresAsyncHeader(String method) {
|
||||||
|
return "fly_to_point".equals(method)
|
||||||
|
|| "fly_to_point_update".equals(method)
|
||||||
|
|| "fly_to_point_stop".equals(method);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 加入队列
|
* 加入队列
|
||||||
*/
|
*/
|
||||||
@@ -399,11 +449,120 @@ public class DeviceCommandManager {
|
|||||||
}, delay, TimeUnit.MILLISECONDS);
|
}, delay, TimeUnit.MILLISECONDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步等待的命令 Future 缓存: commandId -> CompletableFuture
|
||||||
|
*/
|
||||||
|
private final ConcurrentHashMap<String, CompletableFuture<CommandResult>> syncFutures = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送命令并同步等待设备响应
|
||||||
|
* 实现要点:先生成 commandId → 注册 Future → 再发送命令(避免设备快速响应时 Future 未注册的竞态)
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
* @param commandType 命令类型
|
||||||
|
* @param params 命令参数
|
||||||
|
* @param timeoutMs 超时时间(毫秒)
|
||||||
|
* @return 命令结果
|
||||||
|
*/
|
||||||
|
public CommandResult sendCommandSync(String deviceSn, String commandType, JSONObject params, long timeoutMs) {
|
||||||
|
// 1. 先生成 commandId
|
||||||
|
String commandId = UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
// 2. 创建 Future 并注册(必须在发送命令之前)
|
||||||
|
CompletableFuture<CommandResult> future = new CompletableFuture<>();
|
||||||
|
syncFutures.put(commandId, future);
|
||||||
|
|
||||||
|
// 3. 创建命令对象并发送
|
||||||
|
DeviceCommand command = DeviceCommand.builder()
|
||||||
|
.commandId(commandId)
|
||||||
|
.deviceSn(deviceSn)
|
||||||
|
.commandType(commandType)
|
||||||
|
.params(params != null ? params : new JSONObject())
|
||||||
|
.status(CommandStatus.PENDING)
|
||||||
|
.createTime(System.currentTimeMillis())
|
||||||
|
.sendTime(0)
|
||||||
|
.expireTime(System.currentTimeMillis() + timeoutMs)
|
||||||
|
.retryCount(0)
|
||||||
|
.maxRetry(0)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
log.info("创建同步命令: commandId={}, device={}, type={}, timeout={}ms",
|
||||||
|
commandId, deviceSn, commandType, timeoutMs);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 4. 检查并发送
|
||||||
|
if (!jetLinksWebSocketClient.isConnected()) {
|
||||||
|
jetLinksWebSocketClient.connect();
|
||||||
|
int waitCount = 0;
|
||||||
|
while (!jetLinksWebSocketClient.isConnected() && waitCount < 50) {
|
||||||
|
Thread.sleep(100);
|
||||||
|
waitCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (jetLinksWebSocketClient.isConnected()) {
|
||||||
|
sendCommandImmediately(command);
|
||||||
|
} else {
|
||||||
|
syncFutures.remove(commandId);
|
||||||
|
return CommandResult.failed("WebSocket 未连接");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 阻塞等待结果
|
||||||
|
CommandResult result = future.get(timeoutMs, TimeUnit.MILLISECONDS);
|
||||||
|
log.info("同步命令完成: commandId={}, success={}", commandId, result.isSuccess());
|
||||||
|
return result;
|
||||||
|
|
||||||
|
} catch (TimeoutException e) {
|
||||||
|
log.error("同步命令超时: commandId={}, device={}, type={}, timeout={}ms",
|
||||||
|
commandId, deviceSn, commandType, timeoutMs);
|
||||||
|
syncFutures.remove(commandId);
|
||||||
|
return CommandResult.timeout("命令执行超时");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("同步命令异常: commandId={}, error={}", commandId, e.getMessage());
|
||||||
|
syncFutures.remove(commandId);
|
||||||
|
return CommandResult.failed("命令执行异常: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 命令结果 DTO
|
||||||
|
*/
|
||||||
|
@lombok.Data
|
||||||
|
@lombok.AllArgsConstructor
|
||||||
|
public static class CommandResult {
|
||||||
|
private boolean success;
|
||||||
|
private String message;
|
||||||
|
private String commandId;
|
||||||
|
|
||||||
|
public static CommandResult success(String commandId) {
|
||||||
|
return new CommandResult(true, "执行成功", commandId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandResult failed(String message) {
|
||||||
|
return new CommandResult(false, message, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandResult timeout(String message) {
|
||||||
|
return new CommandResult(false, message, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 接收设备命令响应
|
* 接收设备命令响应
|
||||||
*/
|
*/
|
||||||
public void handleCommandResponse(String commandId, boolean success, String message) {
|
public void handleCommandResponse(String commandId, boolean success, String message) {
|
||||||
DeviceCommand command = pendingCommands.remove(commandId);
|
DeviceCommand command = pendingCommands.remove(commandId);
|
||||||
|
|
||||||
|
// 同步等待的 Future 回调
|
||||||
|
CompletableFuture<CommandResult> syncFuture = syncFutures.remove(commandId);
|
||||||
|
if (syncFuture != null) {
|
||||||
|
if (success) {
|
||||||
|
syncFuture.complete(CommandResult.success(commandId));
|
||||||
|
} else {
|
||||||
|
syncFuture.complete(CommandResult.failed(message != null ? message : "设备执行失败"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (command == null) {
|
if (command == null) {
|
||||||
log.warn("收到未知命令响应: commandId={}", commandId);
|
log.warn("收到未知命令响应: commandId={}", commandId);
|
||||||
return;
|
return;
|
||||||
@@ -453,6 +612,11 @@ public class DeviceCommandManager {
|
|||||||
command.setStatus(CommandStatus.TIMEOUT);
|
command.setStatus(CommandStatus.TIMEOUT);
|
||||||
log.warn("命令响应超时: commandId={}, device={}",
|
log.warn("命令响应超时: commandId={}, device={}",
|
||||||
command.getCommandId(), command.getDeviceSn());
|
command.getCommandId(), command.getDeviceSn());
|
||||||
|
// 同步 Future 超时回调
|
||||||
|
CompletableFuture<CommandResult> syncFuture = syncFutures.remove(command.getCommandId());
|
||||||
|
if (syncFuture != null) {
|
||||||
|
syncFuture.complete(CommandResult.timeout("命令响应超时"));
|
||||||
|
}
|
||||||
pendingTimeoutCount.incrementAndGet();
|
pendingTimeoutCount.incrementAndGet();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,770 @@
|
|||||||
|
# JetLinks WebSocket 对接方案 — 迁移指南
|
||||||
|
|
||||||
|
> 目标读者:把这套 JetLinks 平台对接方案迁移到新 Spring Boot 项目的开发者。
|
||||||
|
> 覆盖范围:WebSocket 长连接 + 主题订阅 + 命令下发 + 分布式引用计数 + 消息解析全流程。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、方案能力
|
||||||
|
|
||||||
|
- **单节点单连接**:全局共享一条 WebSocket,所有设备走主题订阅模式。
|
||||||
|
- **懒加载**:项目启动不连接,首次订阅或首次发命令时才建立连接;全部取消后自动断开。
|
||||||
|
- **分布式安全**:多实例通过 Redis 引用计数决定首/末订阅者,跨实例互不干扰。
|
||||||
|
- **自动重连 + Token 自刷新**:指数退避重连;`authError` 触发 Token 刷新后再重连;重连后基于 Redis 状态挑选真实需要的主题。
|
||||||
|
- **命令队列**:断线时命令进队列,重连后按顺序重发;支持指数退避重试、超时清理、异步 response 回调。
|
||||||
|
- **多产品线兼容**:默认适配大疆机场(AutoDock3),改主题模板即可支持其他产品。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、整体架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌────────────────────────────────────────────────────────┐
|
||||||
|
│ 业务入口(SSE / REST / MQ 消费者 …) │
|
||||||
|
└────────────────────────┬───────────────────────────────┘
|
||||||
|
↓
|
||||||
|
┌────────────────────────────────────────────────────────┐
|
||||||
|
│ SubscriptionPoolService(Redis 引用计数,分布式共享) │
|
||||||
|
│ device:sub:{sn}:{topicType} → Set<sessionId> │
|
||||||
|
│ device:sub:session:{sessionId} → Set<sn:topicType> │
|
||||||
|
└────────────────────────┬───────────────────────────────┘
|
||||||
|
首/末订阅者触发或取消
|
||||||
|
↓
|
||||||
|
┌────────────────────────────────────────────────────────┐
|
||||||
|
│ DeviceSubscriptionManager(业务侧订阅编排) │
|
||||||
|
└────────────────────────┬───────────────────────────────┘
|
||||||
|
↓
|
||||||
|
┌────────────────────────────────────────────────────────┐
|
||||||
|
│ JetLinksWebSocketClient(全局单例长连接) │
|
||||||
|
│ - subscribedTopics / topicSubscriptionIds │
|
||||||
|
│ - deviceSubscriptionCounts │
|
||||||
|
│ - 心跳 / 重连 / 认证过期 → 刷新Token │
|
||||||
|
└────────┬──────────────────────────────┬────────────────┘
|
||||||
|
↓ ↓
|
||||||
|
┌──────────────────┐ ┌──────────────────────┐
|
||||||
|
│ TokenManager │ │ DeviceMessageHandler │
|
||||||
|
│ OAuth2 + 缓存 │ │ 解析 / 缓存 / 推送 │
|
||||||
|
└──────────────────┘ └──────────┬───────────┘
|
||||||
|
↓
|
||||||
|
┌──────────────────────┐
|
||||||
|
│ DeviceCommandManager │
|
||||||
|
│ 命令队列 / 重试 / 超时 │
|
||||||
|
└──────────────────────┘
|
||||||
|
|
||||||
|
可选:IsolatedWebSocketClient —— 一次性抓取场景独立短连接
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、依赖与配置
|
||||||
|
|
||||||
|
### 3.1 Maven 依赖
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<!-- Spring 基础 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-websocket</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- OAuth2 Token 获取 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.okhttp3</groupId>
|
||||||
|
<artifactId>okhttp</artifactId>
|
||||||
|
<version>4.12.0</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- JSON 处理 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba</groupId>
|
||||||
|
<artifactId>fastjson</artifactId>
|
||||||
|
<version>2.0.53</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Lombok -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<optional>true</optional>
|
||||||
|
</dependency>
|
||||||
|
```
|
||||||
|
|
||||||
|
Spring Boot 3.x 使用 `jakarta.annotation.*`;Spring Boot 2.x 需改为 `javax.annotation.*`。
|
||||||
|
|
||||||
|
### 3.2 application.yml
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
device:
|
||||||
|
websocket:
|
||||||
|
oauth2:
|
||||||
|
token-url: http://<jetlinks-host>:8848/oauth2/token
|
||||||
|
client-id: <your-client-id>
|
||||||
|
client-secret: <your-client-secret>
|
||||||
|
connection:
|
||||||
|
base-url: ws://<jetlinks-host>:8848/device
|
||||||
|
connect-timeout: 10000
|
||||||
|
read-timeout: 60000
|
||||||
|
heartbeat:
|
||||||
|
enabled: true
|
||||||
|
interval: 30000
|
||||||
|
reconnect:
|
||||||
|
enabled: true
|
||||||
|
max-attempts: 10
|
||||||
|
initial-delay: 2000
|
||||||
|
max-delay: 60000
|
||||||
|
multiplier: 2
|
||||||
|
subscribe:
|
||||||
|
batch-size: 50
|
||||||
|
batch-interval: 500
|
||||||
|
on-demand: true
|
||||||
|
timeout:
|
||||||
|
offline-threshold: 60000
|
||||||
|
check-interval: 10000
|
||||||
|
command:
|
||||||
|
default-timeout: 60000
|
||||||
|
max-retry: 3
|
||||||
|
retry-delay-base: 1000
|
||||||
|
queue-max-size: 100
|
||||||
|
cleanup-interval: 10000
|
||||||
|
|
||||||
|
spring:
|
||||||
|
redis:
|
||||||
|
host: <redis-host>
|
||||||
|
port: 6379
|
||||||
|
password: <optional>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 启动类
|
||||||
|
|
||||||
|
```java
|
||||||
|
@SpringBootApplication
|
||||||
|
@EnableScheduling // 命令过期清理需要
|
||||||
|
public class YourApp { ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、文件清单(14 个 Java 文件)
|
||||||
|
|
||||||
|
放到你的项目里,保留同名包结构;`com.central.device.websocket` 可整体改成你项目的包名。
|
||||||
|
|
||||||
|
```
|
||||||
|
websocket/
|
||||||
|
├── config/
|
||||||
|
│ └── WebSocketProperties.java
|
||||||
|
├── client/
|
||||||
|
│ ├── JetLinksWebSocketClient.java ★ 核心
|
||||||
|
│ └── IsolatedWebSocketClient.java (可选)
|
||||||
|
├── manager/
|
||||||
|
│ ├── TokenManager.java
|
||||||
|
│ ├── SubscriptionPoolService.java
|
||||||
|
│ ├── DeviceSubscriptionManager.java ★ 需按新项目改造
|
||||||
|
│ └── DeviceCommandManager.java
|
||||||
|
├── handler/
|
||||||
|
│ └── DeviceMessageHandler.java ★ 需按新项目改造
|
||||||
|
└── model/
|
||||||
|
├── SubscriptionTopic.java ★ 需按产品线改
|
||||||
|
├── SubscriptionMessage.java
|
||||||
|
├── DeviceCommand.java
|
||||||
|
├── CommandStatus.java
|
||||||
|
├── DeviceRealtimeData.java
|
||||||
|
├── DroneRealtimeData.java
|
||||||
|
├── GpsData.java
|
||||||
|
└── message/
|
||||||
|
├── PropertyReportMessage.java
|
||||||
|
├── DeviceStateEventMessage.java
|
||||||
|
└── MsgAlarmEventMessage.java
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、协议参考(JetLinks 侧)
|
||||||
|
|
||||||
|
### 5.1 主题订阅报文
|
||||||
|
|
||||||
|
```json
|
||||||
|
// 订阅
|
||||||
|
{"type":"sub","topic":"/device/AutoDock3/{sn}/message/event/fire_alarm","parameter":{},"id":"sub-xxx"}
|
||||||
|
|
||||||
|
// 取消订阅 (id 必须与订阅时相同)
|
||||||
|
{"type":"unsub","topic":"/device/AutoDock3/{sn}/message/event/fire_alarm","parameter":{},"id":"sub-xxx"}
|
||||||
|
|
||||||
|
// 心跳
|
||||||
|
{"type":"ping","timestamp":1700000000000}
|
||||||
|
// 服务端回复
|
||||||
|
{"type":"pong"}
|
||||||
|
|
||||||
|
// 认证过期
|
||||||
|
{"type":"authError","message":"..."}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 命令下发报文
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device-message-sender/AutoDock3/{sn}",
|
||||||
|
"parameter": {
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"properties": {
|
||||||
|
"method": "takeoff_to_point",
|
||||||
|
"data": { "data": { /* 指令参数 */ } }
|
||||||
|
},
|
||||||
|
"headers": { "async": false }
|
||||||
|
},
|
||||||
|
"id": "request-id-xxx"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 主题列表(大疆机场默认)
|
||||||
|
|
||||||
|
| 主题模板 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| `/device/AutoDock3/{sn}/online` | 设备上线 |
|
||||||
|
| `/device/AutoDock3/{sn}/offline` | 设备离线 |
|
||||||
|
| `/device/AutoDock3/{sn}/message/property/report` | 属性上报 |
|
||||||
|
| `/device/AutoDock3/{sn}/message/event/fire_alarm` | **设备状态事件**(非火警,是机库/无人机综合状态) |
|
||||||
|
| `/device/AutoDock3/{sn}/message/event/msg_alarm` | 无人机遥测数据 |
|
||||||
|
| `/device-message-sender/AutoDock3/{sn}` | 命令下发 / 命令响应 |
|
||||||
|
|
||||||
|
新项目若接不同产品线,改 `SubscriptionTopic` 里的模板段(例如 `D-Dock2`、`ship`)或用 `subscribeRawTopic()` 传入完整 topic。
|
||||||
|
|
||||||
|
### 5.4 大疆 DRC 指令集
|
||||||
|
|
||||||
|
按 `method` 分类,`DeviceCommandManager.buildCommandProperties()` 已按指令组装好参数:
|
||||||
|
|
||||||
|
| method | 参数 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| `takeoff_to_point` | 经纬度、目标高度、返航高度等 | 一键起飞(注意 `data.data` 嵌套) |
|
||||||
|
| `return_home` / `return_home_cancel` | 无 | 一键返航 / 取消返航 |
|
||||||
|
| `flighttask_pause` / `flighttask_recovery` | 无 | 航线暂停 / 恢复 |
|
||||||
|
| `drc_mode_enter` | 无 | 进入指令飞行模式 |
|
||||||
|
| `stick_control` | roll/pitch/throttle/yaw (624~1424) | DRC 杆量控制,5-10Hz 下发 |
|
||||||
|
| `camera_screen_drag` | pitch_speed / yaw_speed / locked | 云台拖动 |
|
||||||
|
| `camera_mode_switch` | camera_mode (0拍照/1录像/2低光/3全景) | 切相机模式 |
|
||||||
|
| `camera_photo_take` | 无 | 拍照 |
|
||||||
|
| `camera_recording_start` / `camera_recording_stop` | 无 | 录像开始 / 结束 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、关键设计要点(迁移时必须理解)
|
||||||
|
|
||||||
|
### 6.1 懒加载 + 自动断开
|
||||||
|
|
||||||
|
```java
|
||||||
|
// JetLinksWebSocketClient.subscribeDevice()
|
||||||
|
if (!isConnected()) {
|
||||||
|
connect(); // 首次触发连接
|
||||||
|
// 最多等 5 秒
|
||||||
|
while (!isConnected() && waitCount < 50) { Thread.sleep(100); waitCount++; }
|
||||||
|
}
|
||||||
|
// ...
|
||||||
|
|
||||||
|
// unsubscribeDevice() 末尾
|
||||||
|
if (subscribedTopics.isEmpty()) {
|
||||||
|
deviceSubscriptionCounts.clear();
|
||||||
|
closeConnection(); // 全部取消 → 主动断开
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`closeConnection()` 会置 `isAutoClose=true`,`afterConnectionClosed()` 里跳过重连。
|
||||||
|
|
||||||
|
### 6.2 订阅 ID 一致性(重要)
|
||||||
|
|
||||||
|
订阅和取消订阅必须携带同一个 `id`,否则 JetLinks 无法定位该订阅。用 `topicSubscriptionIds` 保存 `topic → id` 的映射:
|
||||||
|
|
||||||
|
```java
|
||||||
|
String subscriptionId = "sub-" + deviceSn + "-" + topic + "-" + UUID.randomUUID().toString().substring(0, 8);
|
||||||
|
topicSubscriptionIds.put(topic, subscriptionId);
|
||||||
|
// 发订阅报文...
|
||||||
|
// 取消时:
|
||||||
|
String subscriptionId = topicSubscriptionIds.remove(topic);
|
||||||
|
// 发取消订阅报文,携带相同 id
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.3 Redis 双向索引 + 引用计数
|
||||||
|
|
||||||
|
```
|
||||||
|
device:sub:{sn}:{topicType} → Set<sessionId> # 按设备主题反查订阅者
|
||||||
|
device:sub:session:{sessionId} → Set<sn:topicType> # 按 session 快速清理
|
||||||
|
```
|
||||||
|
|
||||||
|
- `addSubscription()` → SADD 到两个 Set,返回是否是**首次订阅者**(`isFirst`),只有 true 才向 WebSocket 发订阅报文。
|
||||||
|
- `removeSubscription()` → SREM,返回是否是**最后一个订阅者**(`isLast`),只有 true 才发取消订阅报文。
|
||||||
|
- 24h TTL 兜底 + 60s 一次孤儿清理(活跃 sessionId 集合 vs Redis 中的 session)。
|
||||||
|
|
||||||
|
**分布式必备**。单机也建议用同一套代码,切换到嵌入式 Redis 或删掉分布式逻辑都可以。
|
||||||
|
|
||||||
|
### 6.4 消息路由
|
||||||
|
|
||||||
|
```
|
||||||
|
handleTextMessage()
|
||||||
|
├── type=pong → 忽略
|
||||||
|
├── type=authError → 刷 Token + 重连
|
||||||
|
├── topic 含 /device-message-sender/ → 命令响应 → DeviceCommandManager
|
||||||
|
└── 其他 → handleSubscriptionResult()
|
||||||
|
├── /online → markDeviceOnline
|
||||||
|
├── /offline → markDeviceOffline
|
||||||
|
├── /message/property/report → handlePropertyReport
|
||||||
|
├── /message/event/fire_alarm → handleDeviceStateEvent
|
||||||
|
└── /message/event/msg_alarm → handleMsgAlarmEvent
|
||||||
|
```
|
||||||
|
|
||||||
|
从 topic 提取 deviceSn 的规则:`/device/{productType}/{sn}/...` 或 `/device-message-sender/{productType}/{sn}` 的第 4 段。
|
||||||
|
|
||||||
|
### 6.5 fire_alarm 三段合并(大疆机场特性)
|
||||||
|
|
||||||
|
`fire_alarm` 会循环推送三种结构的数据:
|
||||||
|
|
||||||
|
| 类型 | 识别字段 | 内容 |
|
||||||
|
|-----|---------|------|
|
||||||
|
| 0 - 飞行任务 | `wireless_link` / `sdr` / `tilt_angle` / `flighttask_step_code` | 图传状态 |
|
||||||
|
| 1 - 机库综合 | `drone_charge_state` / `sub_device` / `environment_temperature` | 环境+子设备 |
|
||||||
|
| 2 - 机库状态 | `drone_battery_maintenance_info` / `electric_supply_voltage` | 供电+电池 |
|
||||||
|
|
||||||
|
`DeviceMessageHandler.deviceDataCache[sn] = JSONObject[3]`,按 `identifyDataType()` 归位;**三种齐全**才 `deepMerge()` 并向下游推送,避免半截数据。
|
||||||
|
|
||||||
|
### 6.6 心跳 & 重连
|
||||||
|
|
||||||
|
- 心跳:默认 30s,发 `{"type":"ping","timestamp":...}`。
|
||||||
|
- 重连:指数退避,`delay = min(initialDelay × multiplier^attempts, maxDelay)`。
|
||||||
|
- 重连成功后 `resubscribeAll()`:**基于 Redis 池状态**决定订阅哪些主题(避免恢复已取消的死订阅):
|
||||||
|
|
||||||
|
```java
|
||||||
|
if (subscriptionPoolService.hasSubscribers(sn, TopicType.FIRE_ALARM)) topics.add(EVENT_FIRE_ALARM);
|
||||||
|
if (subscriptionPoolService.hasSubscribers(sn, TopicType.MSG_ALARM)) topics.add(EVENT_MSG_ALARM);
|
||||||
|
if (hasFireAlarm || hasMsgAlarm || hasOnline) topics.add(ONLINE);
|
||||||
|
if (hasFireAlarm || hasMsgAlarm || hasOffline) topics.add(OFFLINE);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.7 Token 生命周期
|
||||||
|
|
||||||
|
- OAuth2 `client_credentials` 模式,`expires_in - 60s` 判过期。
|
||||||
|
- 3 次重试;重试全部失败时,如果旧 token 距离真实过期还有 60s 缓冲,允许降级返回旧 token。
|
||||||
|
- 收到 `authError` 时刷新 Token → 关连接 → 触发重连。
|
||||||
|
|
||||||
|
### 6.8 命令下发流程
|
||||||
|
|
||||||
|
```
|
||||||
|
sendCommand(sn, method, params)
|
||||||
|
↓
|
||||||
|
未连接?→ connect() + 最多等 5s
|
||||||
|
↓
|
||||||
|
连接成功 → sendCommandImmediately()
|
||||||
|
↓ (放入 pendingCommands 等待响应)
|
||||||
|
连接失败 → addToQueue()(每设备独立队列,上限 100)
|
||||||
|
↓
|
||||||
|
【收到响应】/device-message-sender/... → handleCommandResponse(commandId, success, msg)
|
||||||
|
【WS 重连】 → onWebSocketReconnected() → 按队列顺序重发(每条间隔 100ms)
|
||||||
|
【超时】@Scheduled 每 10s 扫描 → 队列过期 EXPIRED / pendingCommands 超时 TIMEOUT
|
||||||
|
【发送异常】retryCommand() 指数退避重试 (delay = 2^retryCount × base)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.9 抑制无效日志
|
||||||
|
|
||||||
|
- `subscribedTopics.contains(topic)` 过滤已取消订阅但延迟到达的消息。
|
||||||
|
- `recentlyUnsubscribedDevices` 5s 宽限期,避免 unsubscribe 瞬间刷 warn。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、迁移改造清单
|
||||||
|
|
||||||
|
### 7.1 必须适配的 4 处
|
||||||
|
|
||||||
|
**1. 产品类型(`SubscriptionTopic.java`)**
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 默认全是 AutoDock3,改成你的产品:
|
||||||
|
ONLINE("/device/AutoDock3/{deviceSn}/online"),
|
||||||
|
// →
|
||||||
|
ONLINE("/device/YourProduct/{deviceSn}/online"),
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. 命令 topic 前缀(`DeviceCommandManager.sendCommandImmediately`)**
|
||||||
|
|
||||||
|
```java
|
||||||
|
message.put("topic", "/device-message-sender/AutoDock3/" + command.getDeviceSn());
|
||||||
|
// → 改成你的产品
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. 业务耦合点(`DeviceSubscriptionManager`)**
|
||||||
|
|
||||||
|
原代码依赖 `IAgeDeviceService`(景区设备表)和 `DeviceMessageHandler.addDevice(sn, scenicId, tenantId)`。迁移时二选一:
|
||||||
|
|
||||||
|
- 保留景区级订阅:用你项目的设备 Service 替换 `IAgeDeviceService`。
|
||||||
|
- 只要单设备订阅:删掉 `subscribeForScenic` / `unsubscribeForScenic` / 景区缓存,只保留下面这个方法:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public void subscribeDevice(String deviceSn, String tenantId) {
|
||||||
|
messageHandler.addDevice(deviceSn, 0L, tenantId);
|
||||||
|
jetLinksWebSocketClient.subscribeDevice(deviceSn,
|
||||||
|
SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE, SubscriptionTopic.EVENT_FIRE_ALARM);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unsubscribeDevice(String deviceSn) {
|
||||||
|
// ⚠️ 不要取消 EVENT_MSG_ALARM,那是操控台单独管理的
|
||||||
|
jetLinksWebSocketClient.unsubscribeDevice(deviceSn,
|
||||||
|
SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE, SubscriptionTopic.EVENT_FIRE_ALARM);
|
||||||
|
messageHandler.removeDevice(deviceSn);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**4. 下游推送(`DeviceMessageHandler.pushDeviceDataUpdate`)**
|
||||||
|
|
||||||
|
原代码通过反射调用 `sseEmitterManager.sendDeviceDataUpdate(sn, data)` / `sendDroneDataUpdate(sn, data)`。新项目:
|
||||||
|
|
||||||
|
- 若继续用 SSE:实现同名方法,或直接把反射调用改成强类型调用。
|
||||||
|
- 换成 WebFlux Sink / MQ / 直接落库:改 `pushDeviceDataUpdate()` 和 `handleMsgAlarmEvent()` 里对应位置。
|
||||||
|
|
||||||
|
`DeviceAlarmDataService` 是把 fire_alarm / msg_alarm 快照写 Redis 的服务,可选实现。
|
||||||
|
|
||||||
|
### 7.2 依赖注入接线(有循环依赖)
|
||||||
|
|
||||||
|
`JetLinksWebSocketClient` ↔ `DeviceCommandManager` ↔ `SubscriptionPoolService` 三者有环,用 setter 打破。**必须**在启动后完成以下接线,否则重连时无法基于 Redis 状态恢复订阅、命令响应无法回调:
|
||||||
|
|
||||||
|
```java
|
||||||
|
// DeviceCommandManager 的 @PostConstruct 里已做:
|
||||||
|
jetLinksWebSocketClient.setCommandManager(this);
|
||||||
|
|
||||||
|
// 你需要显式做:
|
||||||
|
@Component
|
||||||
|
class WebSocketWiring {
|
||||||
|
@Autowired JetLinksWebSocketClient client;
|
||||||
|
@Autowired SubscriptionPoolService pool;
|
||||||
|
@Autowired DeviceMessageHandler handler;
|
||||||
|
@Autowired(required = false) YourSseManager sse;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
void wire() {
|
||||||
|
client.setSubscriptionPoolService(pool);
|
||||||
|
if (sse != null) handler.setSseEmitterManager(sse);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.3 已知问题(迁移前顺手修)
|
||||||
|
|
||||||
|
原项目审计报告发现的 P0 问题(详见 `WebSocket订阅机制审计报告.md`),新项目建议直接按修复版写:
|
||||||
|
|
||||||
|
**问题 A:机库 SSE 断开时按主题分别判断 `isLast`,不要 `&&` 合并**
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 错误写法:
|
||||||
|
if (isLastFireAlarm && isLastOnline && isLastOffline) {
|
||||||
|
deviceSubscriptionManager.unsubscribeDevice(deviceSn); // 混合场景永远进不来
|
||||||
|
}
|
||||||
|
|
||||||
|
// 正确写法:
|
||||||
|
if (isLastFireAlarm) {
|
||||||
|
jetLinksWebSocketClient.unsubscribeDevice(sn, SubscriptionTopic.EVENT_FIRE_ALARM);
|
||||||
|
}
|
||||||
|
if (isLastOnline && isLastOffline
|
||||||
|
&& !subscriptionPoolService.hasSubscribers(sn, TopicType.MSG_ALARM)) {
|
||||||
|
jetLinksWebSocketClient.unsubscribeDevice(sn, SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**问题 B:`unsubscribeDevice()` 不要连 `EVENT_MSG_ALARM` 一起取消**
|
||||||
|
|
||||||
|
`msg_alarm` 属于操控台生命周期,应由 `unsubscribeDroneTelemetry()` 单独管理。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、上手示例
|
||||||
|
|
||||||
|
### 8.1 基础订阅 / 取消订阅(业务代码)
|
||||||
|
|
||||||
|
```java
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/device")
|
||||||
|
public class DeviceController {
|
||||||
|
|
||||||
|
@Autowired JetLinksWebSocketClient wsClient;
|
||||||
|
@Autowired SubscriptionPoolService pool;
|
||||||
|
@Autowired DeviceSubscriptionManager subMgr;
|
||||||
|
|
||||||
|
@PostMapping("/monitor/{sn}")
|
||||||
|
public Result<?> startMonitor(@PathVariable String sn,
|
||||||
|
@RequestParam String sessionId,
|
||||||
|
@RequestParam String tenantId) {
|
||||||
|
// 引用计数:只有首次订阅者才真正下发订阅报文
|
||||||
|
boolean isFirst = pool.addSubscription(sessionId, sn, TopicType.FIRE_ALARM)
|
||||||
|
| pool.addSubscription(sessionId, sn, TopicType.ONLINE)
|
||||||
|
| pool.addSubscription(sessionId, sn, TopicType.OFFLINE);
|
||||||
|
if (isFirst) subMgr.subscribeDevice(sn, tenantId);
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/monitor/{sn}")
|
||||||
|
public Result<?> stopMonitor(@PathVariable String sn,
|
||||||
|
@RequestParam String sessionId) {
|
||||||
|
boolean isLastFireAlarm = pool.removeSubscription(sessionId, sn, TopicType.FIRE_ALARM);
|
||||||
|
boolean isLastOnline = pool.removeSubscription(sessionId, sn, TopicType.ONLINE);
|
||||||
|
boolean isLastOffline = pool.removeSubscription(sessionId, sn, TopicType.OFFLINE);
|
||||||
|
|
||||||
|
if (isLastFireAlarm) {
|
||||||
|
wsClient.unsubscribeDevice(sn, SubscriptionTopic.EVENT_FIRE_ALARM);
|
||||||
|
}
|
||||||
|
if (isLastOnline && isLastOffline
|
||||||
|
&& !pool.hasSubscribers(sn, TopicType.MSG_ALARM)) {
|
||||||
|
wsClient.unsubscribeDevice(sn, SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE);
|
||||||
|
}
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 下发命令
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Autowired DeviceCommandManager cmdMgr;
|
||||||
|
|
||||||
|
// 一键起飞
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("target_latitude", 31.2120679);
|
||||||
|
params.put("target_longitude", 110.86967);
|
||||||
|
params.put("target_height", 322.63797);
|
||||||
|
params.put("security_takeoff_height", 50);
|
||||||
|
params.put("rth_mode", 1);
|
||||||
|
params.put("rth_altitude", 50);
|
||||||
|
params.put("rc_lost_action", 2);
|
||||||
|
params.put("commander_mode_lost_action", 1);
|
||||||
|
params.put("commander_flight_mode", 1);
|
||||||
|
params.put("commander_flight_height", 50);
|
||||||
|
params.put("flight_id", UUID.randomUUID().toString());
|
||||||
|
params.put("max_speed", 5);
|
||||||
|
params.put("flight_safety_advance_check", 0);
|
||||||
|
String commandId = cmdMgr.sendCommand(deviceSn, "takeoff_to_point", params);
|
||||||
|
|
||||||
|
// 拍照
|
||||||
|
cmdMgr.sendCommand(deviceSn, "camera_photo_take", new JSONObject());
|
||||||
|
|
||||||
|
// 查询状态
|
||||||
|
CommandStatus status = cmdMgr.getCommandStatus(commandId);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.3 SSE + 断开清理
|
||||||
|
|
||||||
|
前端刷新/关闭页面时用 `navigator.sendBeacon()` 触发后端清理;后端定时(60s)扫描活跃 session 列表,用 `SubscriptionPoolService.cleanupOrphanSessions(activeIds)` 清理孤儿。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八点五、两种命令下发方式(WebSocket vs REST)
|
||||||
|
|
||||||
|
命令下发有两条路径可选,可以按场景混用:
|
||||||
|
|
||||||
|
| 维度 | WebSocket 通道(本方案) | JetLinks REST API |
|
||||||
|
|------|-----------------------|-------------------|
|
||||||
|
| 实现类 | `DeviceCommandManager` | 直接 HTTP 调用 JetLinks |
|
||||||
|
| 触发点 | 长连接已建立时最快 | 无需长连接,任何时候都能发 |
|
||||||
|
| 响应机制 | 异步,通过 `/device-message-sender/...` 主题回调 `handleCommandResponse()` | 同步,HTTP 返回体即结果 |
|
||||||
|
| 断线容错 | 有队列 + 重连后重发 | 请求当场失败,需业务方重试 |
|
||||||
|
| 状态查询 | `commandManager.getCommandStatus(commandId)` | 无状态跟踪,靠 HTTP 响应 |
|
||||||
|
| 高频指令(DRC 杆量 5-10Hz) | ✅ 更合适 | ❌ 每次都建 HTTP 连接,太重 |
|
||||||
|
| 一次性长任务(航线下发) | ⚪ 可用 | ✅ 更合适,直接拿结果 |
|
||||||
|
|
||||||
|
### 8.5.1 WebSocket 通道 — HTTP 接口封装
|
||||||
|
|
||||||
|
`DeviceCommandController` 是 `DeviceCommandManager` 的 HTTP 门面,前端/其他服务直接调 REST 即可,无需感知 WebSocket 存在。搬到新项目改一下包和 `Result` 类型就能用:
|
||||||
|
|
||||||
|
**通用发送 / 状态查询:**
|
||||||
|
```
|
||||||
|
POST /device/command/send
|
||||||
|
Body: { "deviceSn": "SN123", "commandType": "takeoff_to_point", "params": {...} }
|
||||||
|
Resp: { "code": 0, "data": "<commandId>" }
|
||||||
|
|
||||||
|
GET /device/command/status/{commandId}
|
||||||
|
Resp: { "commandId":"...", "status":"SENT", "statusDesc":"已发送,等待设备响应",
|
||||||
|
"deviceSn":"SN123", "commandType":"takeoff_to_point",
|
||||||
|
"createTime":..., "sendTime":..., "retryCount":0, "errorMsg":null }
|
||||||
|
```
|
||||||
|
|
||||||
|
**语义化端点(对前端更友好):**
|
||||||
|
|
||||||
|
| 接口 | 方法 | 参数 | 说明 |
|
||||||
|
|------|------|------|------|
|
||||||
|
| `POST /device/command/takeoff` | body: `TakeoffRequest` | 一键起飞(自带默认值填充) |
|
||||||
|
| `POST /device/command/return?deviceSn=` | query | 一键返航 |
|
||||||
|
| `POST /device/command/return/cancel?deviceSn=` | query | 取消返航 |
|
||||||
|
| `POST /device/command/pause?deviceSn=` | query | 航线暂停 / 紧急悬停 |
|
||||||
|
| `POST /device/command/resume?deviceSn=` | query | 航线恢复 |
|
||||||
|
| `POST /device/command/photo?deviceSn=` | query | 拍照 |
|
||||||
|
| `POST /device/command/recording/start?deviceSn=` | query | 开始录像 |
|
||||||
|
| `POST /device/command/recording/stop?deviceSn=` | query | 停止录像 |
|
||||||
|
| `POST /device/command/camera/mode?deviceSn=&cameraMode=` | query | 切换相机模式 |
|
||||||
|
| `POST /device/command/drc/enter?deviceSn=` | query | 进入 DRC 模式 |
|
||||||
|
| `POST /device/command/drc/stick` | body: `StickControlRequest` | DRC 杆量控制 |
|
||||||
|
| `POST /device/command/gimbal` | body: `GimbalControlRequest` | 云台拖动控制 |
|
||||||
|
|
||||||
|
**调用示例(curl):**
|
||||||
|
```bash
|
||||||
|
# 拍照
|
||||||
|
curl -X POST 'http://<host>/device/command/photo?deviceSn=SN123'
|
||||||
|
|
||||||
|
# 一键起飞
|
||||||
|
curl -X POST 'http://<host>/device/command/takeoff' \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{
|
||||||
|
"deviceSn": "SN123",
|
||||||
|
"targetLatitude": 31.2120679,
|
||||||
|
"targetLongitude": 110.86967,
|
||||||
|
"targetHeight": 322.6,
|
||||||
|
"commanderFlightHeight": 50,
|
||||||
|
"maxSpeed": 5
|
||||||
|
}'
|
||||||
|
|
||||||
|
# 查询命令执行状态
|
||||||
|
curl 'http://<host>/device/command/status/<commandId>'
|
||||||
|
```
|
||||||
|
|
||||||
|
**迁移改造清单:**
|
||||||
|
- `Result` / `@Tag` / `@Operation` 换成新项目对应的返回体和文档注解。
|
||||||
|
- `getStreamUrls(deviceSn)` 依赖本项目的设备表(推流地址),删掉或改成你项目的 Service。
|
||||||
|
- 起飞接口里 `flight_id` 默认取 UUID,业务上要联动订单号的话在这里改。
|
||||||
|
|
||||||
|
### 8.5.2 REST API 通道 — 直接调 JetLinks
|
||||||
|
|
||||||
|
JetLinks 平台自带一套设备属性下发 REST API,不需要 WebSocket 长连接。项目里"执行航线任务"就是走这条:
|
||||||
|
|
||||||
|
```
|
||||||
|
POST http://<jetlinks-host>:8848/device/instance/{deviceSn}/property
|
||||||
|
Header: Authorization: Bearer <token>
|
||||||
|
Body: { "method": "flighttask_prepare", "data": {...} }
|
||||||
|
|
||||||
|
Response: { "status": 200, "message": "success", "result": {...} }
|
||||||
|
错误码: 500 + "Device is offline" → 设备离线
|
||||||
|
```
|
||||||
|
|
||||||
|
**核心代码位置:** `DeviceCommandController.executeWayline()` 及其 `buildWaylineControlMessage()`。搬迁时需要一起带走的辅助类:
|
||||||
|
|
||||||
|
| 类 | 职责 |
|
||||||
|
|----|------|
|
||||||
|
| `RequestUtils` | 封装 `getPostRequestResult` 之类的 HTTP 调用(带鉴权头) |
|
||||||
|
| `IotRequestResult` | 解析 JetLinks 响应体 `{status, message, result}` |
|
||||||
|
| `ControlMessageConstant` | 保存指令模板 JSON(`flighttask_prepare`、`stick_control` 等) |
|
||||||
|
|
||||||
|
**REST 通道适用场景:**
|
||||||
|
- **航线任务下发**:payload 较大,一次性完成,需要立即知道结果。
|
||||||
|
- **属性读写**:与 `SubscriptionTopic.PROPERTY_READ / PROPERTY_WRITE` 等价,但同步返回。
|
||||||
|
- **无长连接的边缘节点/脚本**:只发一两条命令就退出,没必要建 WebSocket。
|
||||||
|
- **平台管理接口**:设备产品配置、日志查询、固件下发等 JetLinks 提供的 REST 能力。
|
||||||
|
|
||||||
|
**通用调用骨架(新项目可以直接抄):**
|
||||||
|
|
||||||
|
```java
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/device/rest-command")
|
||||||
|
public class DeviceRestCommandController {
|
||||||
|
|
||||||
|
@Value("${jetlinks.server.baseUrl}")
|
||||||
|
private String jetlinksBaseUrl;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private RequestUtils requestUtils; // 带 token 的 HTTP 调用工具
|
||||||
|
|
||||||
|
@PostMapping("/property/{deviceSn}")
|
||||||
|
public Result<String> sendProperty(@PathVariable String deviceSn,
|
||||||
|
@RequestBody JSONObject body) {
|
||||||
|
String url = jetlinksBaseUrl + "/device/instance/" + deviceSn + "/property";
|
||||||
|
Map<String, String> resp = requestUtils.getPostRequestResultMap(url, body.toJSONString());
|
||||||
|
JSONObject json = JSON.parseObject(resp.get(""));
|
||||||
|
IotRequestResult r = IotRequestResult.getInstance(json);
|
||||||
|
return r.getStatus() == 200
|
||||||
|
? Result.succeed(r.getMessage())
|
||||||
|
: Result.failed(r.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`RequestUtils` 里需要注入 `TokenManager.getValidToken()` 作为 `Authorization: Bearer <token>` 头,Token 复用 WebSocket 通道那套 OAuth2 客户端凭证。
|
||||||
|
|
||||||
|
### 8.5.3 组合使用建议
|
||||||
|
|
||||||
|
| 场景 | 推荐通道 |
|
||||||
|
|------|---------|
|
||||||
|
| 前端页面持续订阅设备状态 | WebSocket |
|
||||||
|
| 高频控制指令(DRC 杆量、云台拖动) | WebSocket |
|
||||||
|
| 一次性拍照 / 录像开关 | 都可以,WebSocket 更省资源 |
|
||||||
|
| 航线下发、属性读写 | REST |
|
||||||
|
| 后台服务批量下发命令 | REST(无需维护长连接) |
|
||||||
|
| 无人值守脚本 / 定时任务 | REST |
|
||||||
|
|
||||||
|
**混合部署时的一致性:** 两条通道最终都到 JetLinks 平台,设备侧不区分来源。业务侧要注意命令幂等和状态跟踪 —— REST 通道没有 `commandId` 概念,需要业务方自己带任务号(如 `missionCode`)关联结果。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 九、启动流程时序
|
||||||
|
|
||||||
|
```
|
||||||
|
1. Bean 装配
|
||||||
|
├── WebSocketProperties @ConfigurationProperties 装载
|
||||||
|
├── TokenManager 就绪(不请求 token)
|
||||||
|
├── JetLinksWebSocketClient.init() 只创建重连线程池
|
||||||
|
├── DeviceCommandManager.init() 回填 commandManager 引用
|
||||||
|
├── SubscriptionPoolService 就绪
|
||||||
|
└── WebSocketWiring.wire() setSubscriptionPoolService / setSseEmitterManager
|
||||||
|
|
||||||
|
2. 首次业务调用
|
||||||
|
├── 前端建立 SSE / 调 REST
|
||||||
|
├── SubscriptionPoolService.addSubscription() → isFirst=true
|
||||||
|
├── DeviceSubscriptionManager.subscribeDevice()
|
||||||
|
├── JetLinksWebSocketClient.subscribeDevice()
|
||||||
|
│ └── isConnected? → 否 → connect() → 等待 5s → afterConnectionEstablished()
|
||||||
|
│ ↓
|
||||||
|
│ startHeartbeat() + resubscribeAll()
|
||||||
|
└── 发订阅报文
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十、监控与排障
|
||||||
|
|
||||||
|
**关键日志前缀:**
|
||||||
|
- `订阅设备:` / `取消订阅设备:` — 业务层订阅动作
|
||||||
|
- `发送订阅消息:` / `取消订阅主题:` — WebSocket 层实际报文
|
||||||
|
- `WebSocket连接成功` / `WebSocket连接关闭` — 连接状态
|
||||||
|
- `Token刷新成功` / `Token刷新失败` — Token 生命周期
|
||||||
|
- `命令发送成功` / `命令响应解析结果` — 命令流转
|
||||||
|
- `设备 X 数据未齐全` — fire_alarm 三段合并等待
|
||||||
|
|
||||||
|
**排障 checklist:**
|
||||||
|
- 收不到数据 → 确认 `subscribedTopics` 含目标 topic,`isConnected() == true`。
|
||||||
|
- 命令没响应 → 检查 topic 前缀(产品类型);检查 `pendingCommands` 是否有该 commandId。
|
||||||
|
- 重连后订阅错乱 → 确认 `setSubscriptionPoolService()` 已调用;查 `resubscribeAll()` 日志。
|
||||||
|
- Redis 池残留 → 手动跑 `SubscriptionPoolService.printSubscriptionStatus()` / `clearAllSubscriptions()`。
|
||||||
|
- 收到 `topic=null` warn → 通常是 `handleSubscriptionResult` 里的非设备消息(如订阅确认回执),不影响业务。
|
||||||
|
|
||||||
|
**订阅一致性巡检(推荐):**
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Scheduled(fixedDelay = 300_000)
|
||||||
|
public void checkConsistency() {
|
||||||
|
for (String sn : wsClient.getActiveDevices()) {
|
||||||
|
int wsCount = wsClient.getDeviceSubscriptionCount(sn);
|
||||||
|
boolean redisHas = pool.hasSubscribers(sn, TopicType.FIRE_ALARM)
|
||||||
|
|| pool.hasSubscribers(sn, TopicType.MSG_ALARM)
|
||||||
|
|| pool.hasSubscribers(sn, TopicType.ONLINE);
|
||||||
|
if (wsCount > 0 && !redisHas) {
|
||||||
|
log.warn("检测到订阅残留: sn={}, wsCount={}", sn, wsCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十一、参考文档
|
||||||
|
|
||||||
|
同目录下的原始文档保留了更细节的部分,作为补充参考:
|
||||||
|
- `WebSocket懒加载使用说明.md` — 懒加载语义 + API 快速参考
|
||||||
|
- `WebSocket消息处理说明.md` — 消息 POJO 结构 + 处理逻辑
|
||||||
|
- `WebSocket订阅机制审计报告.md` — 已知问题 + 修复方案 + 场景推演
|
||||||
|
- `指令飞行.md` — 大疆 DRC 指令集完整参数字典
|
||||||
+92
@@ -0,0 +1,92 @@
|
|||||||
|
package com.central.device.websocket.manager;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSONArray;
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.central.device.websocket.model.CommandStatus;
|
||||||
|
import com.central.device.websocket.model.DeviceCommand;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
|
public class DeviceCommandManagerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void flyToPointUsesNestedDataWrapper() throws Exception {
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("fly_to_id", "FP20260724164503");
|
||||||
|
params.put("max_speed", 12.0f);
|
||||||
|
params.put("height", 55.327644f);
|
||||||
|
params.put("latitude", 30.61043916027994d);
|
||||||
|
params.put("longitude", 114.39342878294764d);
|
||||||
|
|
||||||
|
JSONObject properties = buildProperties("fly_to_point", params);
|
||||||
|
|
||||||
|
Assert.assertEquals("fly_to_point", properties.getString("method"));
|
||||||
|
JSONObject outerData = properties.getJSONObject("data");
|
||||||
|
Assert.assertNotNull("指点飞行外层 data 下必须继续包含 data", outerData.getJSONObject("data"));
|
||||||
|
JSONObject commandData = outerData.getJSONObject("data");
|
||||||
|
Assert.assertEquals("FP20260724164503", commandData.getString("fly_to_id"));
|
||||||
|
Assert.assertEquals(12.0f, commandData.getFloatValue("max_speed"), 0.001f);
|
||||||
|
JSONArray points = commandData.getJSONArray("points");
|
||||||
|
Assert.assertEquals(1, points.size());
|
||||||
|
Assert.assertEquals(55.327644f, points.getJSONObject(0).getFloatValue("height"), 0.001f);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void flyToPointUpdateUsesNestedDataWrapper() throws Exception {
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("max_speed", 10.0f);
|
||||||
|
params.put("height", 60.0f);
|
||||||
|
params.put("latitude", 30.61043916027994d);
|
||||||
|
params.put("longitude", 114.39342878294764d);
|
||||||
|
|
||||||
|
JSONObject properties = buildProperties("fly_to_point_update", params);
|
||||||
|
|
||||||
|
JSONObject commandData = properties.getJSONObject("data").getJSONObject("data");
|
||||||
|
Assert.assertNotNull("连续指点更新也必须使用 data.data 包装", commandData);
|
||||||
|
Assert.assertEquals(10.0f, commandData.getFloatValue("max_speed"), 0.001f);
|
||||||
|
Assert.assertEquals(60.0f, commandData.getJSONArray("points").getJSONObject(0).getFloatValue("height"), 0.001f);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void returnHomeKeepsFlatEmptyData() throws Exception {
|
||||||
|
JSONObject properties = buildProperties("return_home", new JSONObject());
|
||||||
|
|
||||||
|
Assert.assertEquals("return_home", properties.getString("method"));
|
||||||
|
JSONObject data = properties.getJSONObject("data");
|
||||||
|
Assert.assertNotNull(data);
|
||||||
|
Assert.assertFalse("返航命令不能新增 data.data 包装", data.containsKey("data"));
|
||||||
|
Assert.assertTrue(data.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void flyToPointCommandsUseAsyncHeader() throws Exception {
|
||||||
|
Assert.assertTrue(requiresAsyncHeader("fly_to_point"));
|
||||||
|
Assert.assertTrue(requiresAsyncHeader("fly_to_point_update"));
|
||||||
|
Assert.assertTrue(requiresAsyncHeader("fly_to_point_stop"));
|
||||||
|
Assert.assertFalse(requiresAsyncHeader("return_home"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private JSONObject buildProperties(String commandType, JSONObject params) throws Exception {
|
||||||
|
DeviceCommand command = DeviceCommand.builder()
|
||||||
|
.commandId("cmd-test")
|
||||||
|
.deviceSn("device-test")
|
||||||
|
.commandType(commandType)
|
||||||
|
.params(params)
|
||||||
|
.status(CommandStatus.PENDING)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
DeviceCommandManager manager = new DeviceCommandManager();
|
||||||
|
Method method = DeviceCommandManager.class.getDeclaredMethod("buildCommandProperties", DeviceCommand.class);
|
||||||
|
method.setAccessible(true);
|
||||||
|
return (JSONObject) method.invoke(manager, command);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean requiresAsyncHeader(String commandType) throws Exception {
|
||||||
|
DeviceCommandManager manager = new DeviceCommandManager();
|
||||||
|
Method method = DeviceCommandManager.class.getDeclaredMethod("requiresAsyncHeader", String.class);
|
||||||
|
method.setAccessible(true);
|
||||||
|
return (boolean) method.invoke(manager, commandType);
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
@@ -63,6 +63,12 @@ public class FileController {
|
|||||||
@Value("${zlt.security.tencent.getwxacodeUrl}")
|
@Value("${zlt.security.tencent.getwxacodeUrl}")
|
||||||
private String getwxacodeUrl;
|
private String getwxacodeUrl;
|
||||||
|
|
||||||
|
@Value("${cdn.s3.domain:minicdn.goflytec.com}")
|
||||||
|
private String s3CdnDomain;
|
||||||
|
|
||||||
|
@Value("${cdn.s3.enabled:true}")
|
||||||
|
private boolean s3CdnEnabled;
|
||||||
|
|
||||||
private final RestTemplate restTemplate = new RestTemplate();
|
private final RestTemplate restTemplate = new RestTemplate();
|
||||||
|
|
||||||
@Value("${zlt.security.tencent.pagePath}")
|
@Value("${zlt.security.tencent.pagePath}")
|
||||||
@@ -201,6 +207,46 @@ public class FileController {
|
|||||||
return Result.succeed(map);
|
return Result.succeed(map);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 拉取外部图片 URL 字节并强制入 S3(不进 OSS / 不进智能路由)
|
||||||
|
* 用于支付宝小程序二维码:alipay.open.app.qrcode.create 返回临时 qr_code_url,需立刻拉回入 S3
|
||||||
|
*/
|
||||||
|
@GetMapping("/qrcode/s3/by-url")
|
||||||
|
public Result<Map> uploadQrCodeToS3ByUrl(@RequestParam("codeId") String codeId,
|
||||||
|
@RequestParam("qrUrl") String qrUrl,
|
||||||
|
@RequestParam(value = "suffix", required = false, defaultValue = "png") String suffix) throws Exception {
|
||||||
|
if (codeId == null || codeId.isEmpty() || qrUrl == null || qrUrl.isEmpty()) {
|
||||||
|
return Result.failed("codeId 和 qrUrl 不能为空");
|
||||||
|
}
|
||||||
|
ResponseEntity<byte[]> resp = restTemplate.exchange(qrUrl, HttpMethod.GET, HttpEntity.EMPTY, byte[].class);
|
||||||
|
if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null || resp.getBody().length == 0) {
|
||||||
|
return Result.failed("拉取二维码图片失败: " + resp.getStatusCode());
|
||||||
|
}
|
||||||
|
String fileName = codeId + "." + suffix;
|
||||||
|
FileInfo fileInfo = fileService.uploadForS3(fileName, new ByteArrayInputStream(resp.getBody()));
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("codeId", codeId);
|
||||||
|
map.put("fileId", fileInfo.getId());
|
||||||
|
map.put("filePath", fileInfo.getPath());
|
||||||
|
return Result.succeed(map);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 直接 S3 无过期访问地址(绕过 TimeWindowStorageService 智能路由)
|
||||||
|
* 用于支付宝小程序二维码:与 AbstractIFileService.uploadForS3 上传时设置的 fileInfo.url 完全一致 ——
|
||||||
|
* 直接拼 https://<s3CdnDomain>/<objectPath>,不签名、不带过期、可被 CDN 缓存。
|
||||||
|
*/
|
||||||
|
@GetMapping("/files/s3/path")
|
||||||
|
public String getS3ViewUrlByPath(@RequestParam("path") String path) {
|
||||||
|
if (path == null || path.isEmpty()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (s3CdnEnabled && s3CdnDomain != null && !s3CdnDomain.isEmpty()) {
|
||||||
|
return "https://" + s3CdnDomain + "/" + path;
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
@PostMapping("/path")
|
@PostMapping("/path")
|
||||||
public FileInfo creatFileInfo(@RequestBody String path) {
|
public FileInfo creatFileInfo(@RequestBody String path) {
|
||||||
return fileService.createFile(path);
|
return fileService.createFile(path);
|
||||||
|
|||||||
@@ -20,6 +20,11 @@ public interface IFileService extends IService<FileInfo> {
|
|||||||
|
|
||||||
FileInfo uploadForS3(MultipartFile file ) throws Exception;
|
FileInfo uploadForS3(MultipartFile file ) throws Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 强制以 S3 方式上传字节流(用于支付宝小程序二维码等需绕开 OSS 的场景)
|
||||||
|
*/
|
||||||
|
FileInfo uploadForS3(String name, InputStream inputStream) throws Exception;
|
||||||
|
|
||||||
FileInfo upload(String name, InputStream inputStream) throws Exception;
|
FileInfo upload(String name, InputStream inputStream) throws Exception;
|
||||||
|
|
||||||
PageResult<FileInfo> findList(Map<String, Object> params);
|
PageResult<FileInfo> findList(Map<String, Object> params);
|
||||||
|
|||||||
+20
@@ -79,6 +79,26 @@ public abstract class AbstractIFileService extends ServiceImpl<FileMapper, FileI
|
|||||||
return fileInfo;
|
return fileInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileInfo uploadForS3(String name, InputStream inputStream) {
|
||||||
|
if (s3Template == null) {
|
||||||
|
throw new RuntimeException("S3服务未配置,无法使用S3上传");
|
||||||
|
}
|
||||||
|
FileInfo fileInfo = FileUtil.getFileInfo(name, inputStream);
|
||||||
|
if (!fileInfo.getName().contains(FILE_SPLIT)) {
|
||||||
|
throw new IllegalArgumentException("缺少后缀名");
|
||||||
|
}
|
||||||
|
ObjectInfo objectInfo = s3Template.upload(name, inputStream);
|
||||||
|
if (objectInfo == null) {
|
||||||
|
throw new RuntimeException("S3上传失败: " + name);
|
||||||
|
}
|
||||||
|
fileInfo.setPath(objectInfo.getObjectPath());
|
||||||
|
fileInfo.setUrl(buildCdnUrl(objectInfo.getObjectPath()));
|
||||||
|
fileInfo.setSource("s3");
|
||||||
|
baseMapper.insert(fileInfo);
|
||||||
|
return fileInfo;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建CDN URL
|
* 构建CDN URL
|
||||||
* @param objectPath 对象路径 (格式: bucket/objectKey)
|
* @param objectPath 对象路径 (格式: bucket/objectKey)
|
||||||
|
|||||||
+19
-1
@@ -6,6 +6,7 @@ import com.aliyuncs.cdn.model.v20180510.*;
|
|||||||
import com.aliyuncs.profile.DefaultProfile;
|
import com.aliyuncs.profile.DefaultProfile;
|
||||||
import com.central.file.config.CdnConfig;
|
import com.central.file.config.CdnConfig;
|
||||||
import com.central.file.service.ICdnService;
|
import com.central.file.service.ICdnService;
|
||||||
|
import com.central.file.utils.CdnUtils;
|
||||||
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.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -14,6 +15,7 @@ import org.springframework.util.CollectionUtils;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CDN服务实现类
|
* CDN服务实现类
|
||||||
@@ -94,9 +96,25 @@ public class CdnServiceImpl implements ICdnService {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 过滤掉视频文件:视频体积大且点播命中率低,预热会造成大量CDN回源流量
|
||||||
|
List<String> nonVideoUrls = urls.stream()
|
||||||
|
.filter(url -> {
|
||||||
|
if (CdnUtils.isVideoFile(url)) {
|
||||||
|
log.info("跳过视频文件预热: {}", url);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
if (nonVideoUrls.isEmpty()) {
|
||||||
|
log.info("过滤后无需要预热的文件(均为视频),跳过预热");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
PushObjectCacheRequest request = new PushObjectCacheRequest();
|
PushObjectCacheRequest request = new PushObjectCacheRequest();
|
||||||
request.setObjectPath(String.join("\n", urls));
|
request.setObjectPath(String.join("\n", nonVideoUrls));
|
||||||
if (area != null && !area.isEmpty()) {
|
if (area != null && !area.isEmpty()) {
|
||||||
request.setArea(area);
|
request.setArea(area);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -90,12 +90,6 @@
|
|||||||
<artifactId>hibernate-validator</artifactId>
|
<artifactId>hibernate-validator</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>javax.servlet</groupId>
|
|
||||||
<artifactId>javax.servlet-api</artifactId>
|
|
||||||
<version>4.0.1</version>
|
|
||||||
<scope>compile</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-webflux</artifactId>
|
<artifactId>spring-webflux</artifactId>
|
||||||
@@ -121,6 +115,16 @@
|
|||||||
<artifactId>zlt-wechat-spring-boot-starter</artifactId>
|
<artifactId>zlt-wechat-spring-boot-starter</artifactId>
|
||||||
<version>${project.version}</version>
|
<version>${project.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.zlt</groupId>
|
||||||
|
<artifactId>zlt-alipay-common-core</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.zlt</groupId>
|
||||||
|
<artifactId>zlt-alipay-spring-boot-starter</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|||||||
+10
@@ -18,6 +18,16 @@ public class PayTypeConstants {
|
|||||||
*/
|
*/
|
||||||
public static final Integer COUPON_PAY = 2;
|
public static final Integer COUPON_PAY = 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 第三方聚到核销
|
||||||
|
*/
|
||||||
|
public static final Integer FEIPAI_VERIFY = 3;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝支付
|
||||||
|
*/
|
||||||
|
public static final Integer ALIPAY_PAY = 4;
|
||||||
|
|
||||||
private PayTypeConstants() {
|
private PayTypeConstants() {
|
||||||
// 私有构造函数,防止实例化
|
// 私有构造函数,防止实例化
|
||||||
}
|
}
|
||||||
|
|||||||
+392
@@ -0,0 +1,392 @@
|
|||||||
|
package com.central.order.controller;
|
||||||
|
|
||||||
|
import com.alipay.api.response.AlipayTradeCreateResponse;
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import com.central.alipay.notify.AlipayNotifyVerifier;
|
||||||
|
import com.central.alipay.service.AlipayPayService;
|
||||||
|
import com.central.alipay.service.AlipayRefundService;
|
||||||
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
|
import com.central.common.context.TenantContextHolder;
|
||||||
|
import com.central.common.feign.UserService;
|
||||||
|
import com.central.common.model.LoginAppUser;
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.common.model.SysUser;
|
||||||
|
import com.central.common.utils.SecurityTenantUtils;
|
||||||
|
import com.central.order.enums.OrderStatus;
|
||||||
|
import com.central.order.enums.PayTypeEnum;
|
||||||
|
import com.central.order.enums.RefundState;
|
||||||
|
import com.central.order.model.Order;
|
||||||
|
import com.central.order.model.QrCode;
|
||||||
|
import com.central.order.service.ICtripDistOrderService;
|
||||||
|
import com.central.order.service.IOrderService;
|
||||||
|
import com.central.order.service.IQrCodeService;
|
||||||
|
import com.central.order.service.IRefundService;
|
||||||
|
import com.central.order.service.IAlipayConfigService;
|
||||||
|
import com.central.order.util.StringUtils;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jodd.util.StringUtil;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝支付控制器(对标 WxPayController)
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@Tag(name = "支付宝支付管理", description = "支付宝小程序下单、支付/退款异步回调")
|
||||||
|
@RequestMapping("/alipay")
|
||||||
|
public class AliPayController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private IOrderService orderService;
|
||||||
|
@Autowired
|
||||||
|
private IRefundService refundService;
|
||||||
|
@Autowired
|
||||||
|
private IQrCodeService qrCodeService;
|
||||||
|
@Autowired
|
||||||
|
private IAlipayConfigService alipayConfigService;
|
||||||
|
@Autowired
|
||||||
|
private AlipayPayService alipayPayService;
|
||||||
|
@Autowired
|
||||||
|
private AlipayRefundService alipayRefundService;
|
||||||
|
@Autowired
|
||||||
|
private AlipayNotifyVerifier alipayNotifyVerifier;
|
||||||
|
@Autowired
|
||||||
|
private ICtripDistOrderService ctripDistOrderService;
|
||||||
|
@Autowired
|
||||||
|
private UserService userService;
|
||||||
|
|
||||||
|
// ==================== 小程序下单 ====================
|
||||||
|
|
||||||
|
@Operation(summary = "支付宝小程序下单",
|
||||||
|
description = "调用 alipay.trade.create 获取 tradeNo,前端用 my.tradePay({tradeNo}) 拉起支付。"
|
||||||
|
+ "请求需携带 Authorization: Bearer <access_token>。"
|
||||||
|
+ "入参 JSON:orderId(必填)+buyerId(可选)。出参成功返回 { tradeNo, outTradeNo }")
|
||||||
|
@io.swagger.v3.oas.annotations.parameters.RequestBody(
|
||||||
|
description = "{\"orderId\": 订单ID(必填), \"buyerId\": 支付宝userId(可选)}",
|
||||||
|
required = true,
|
||||||
|
content = @Content(schema = @Schema(example = "{\"orderId\": 1001, \"buyerId\": \"2088xxxxxxxxxxxx\"}")))
|
||||||
|
@PostMapping("/order/pay")
|
||||||
|
public Result<AlipayTradeCreateResponse> payOrder(@RequestBody Map<String, Object> body) {
|
||||||
|
Object rawOrderId = body.get("orderId");
|
||||||
|
Assert.notNull(rawOrderId, "orderId 不能为空");
|
||||||
|
Long orderId = Long.valueOf(rawOrderId.toString());
|
||||||
|
Order order = orderService.getById(orderId);
|
||||||
|
Assert.notNull(order, "订单不存在: " + orderId);
|
||||||
|
|
||||||
|
// 校验当前登录用户拥有该订单(防止替他人订单发起支付)
|
||||||
|
LoginAppUser currentUser = LoginUserContextHolder.getUser();
|
||||||
|
Assert.notNull(currentUser, "未登录或登录已过期");
|
||||||
|
if (order.getUserId() == null || !order.getUserId().equals(currentUser.getId())) {
|
||||||
|
throw new IllegalStateException("无权操作他人订单, orderId: " + orderId);
|
||||||
|
}
|
||||||
|
// 租户边界校验:订单租户必须与当前用户当前租户一致
|
||||||
|
String currentTenantId = SecurityTenantUtils.getCurrentTenantId();
|
||||||
|
if (currentTenantId != null && order.getTenantId() != null
|
||||||
|
&& !currentTenantId.equals(order.getTenantId())
|
||||||
|
&& !SecurityTenantUtils.isSuperAdmin()) {
|
||||||
|
throw new IllegalStateException("订单与当前租户不一致, orderId: " + orderId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 业务校验:订单必须为待支付状态,避免重复下单
|
||||||
|
if (!OrderStatus.UNPAID.getId().equals(order.getOrderStatus())) {
|
||||||
|
throw new IllegalStateException("订单状态不允许支付,orderId: " + orderId
|
||||||
|
+ ", status: " + order.getOrderStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
AlipayConfig config = alipayConfigService.getConfigByTypeAndTenantId("PAY", order.getTenantId());
|
||||||
|
Assert.notNull(config, "支付宝支付配置不存在,tenantId: " + order.getTenantId());
|
||||||
|
|
||||||
|
// buyerId 不信任前端传入:以服务端 sys_user_third_openid 映射为准
|
||||||
|
String buyerId = order.getUserId() != null
|
||||||
|
? userService.getAlipayOpenIdByUserId(order.getUserId(), config.getAppId())
|
||||||
|
: null;
|
||||||
|
Object rawBuyerId = body.get("buyerId");
|
||||||
|
if (rawBuyerId != null && !rawBuyerId.toString().isEmpty()) {
|
||||||
|
// 客户端传入 buyerId 时必须与服务端映射结果一致
|
||||||
|
if (buyerId == null || !buyerId.equals(rawBuyerId.toString())) {
|
||||||
|
throw new IllegalStateException("buyerId 与当前登录用户不匹配");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
|
||||||
|
String subject = qrCode != null && qrCode.getName() != null
|
||||||
|
? qrCode.getName() : "景区订单-" + order.getOrderNo();
|
||||||
|
|
||||||
|
AlipayPayService.AlipayPayRequest req = new AlipayPayService.AlipayPayRequest();
|
||||||
|
req.setOutTradeNo(order.getOrderNo());
|
||||||
|
if (order.getOrderAmount() == null) {
|
||||||
|
throw new IllegalArgumentException("订单金额不能为空, orderId: " + orderId);
|
||||||
|
}
|
||||||
|
// Order.orderAmount 以"分"存储,支付宝 SDK total_amount 需要"元"
|
||||||
|
req.setTotalAmount(StringUtils.fenToYuanAmount(order.getOrderAmount()));
|
||||||
|
req.setSubject(subject);
|
||||||
|
req.setBuyerId(buyerId);
|
||||||
|
if (Boolean.TRUE.equals(config.getIsServiceMode()) && config.getSubMerchantId() != null) {
|
||||||
|
req.setSubMerchantId(config.getSubMerchantId());
|
||||||
|
}
|
||||||
|
|
||||||
|
AlipayTradeCreateResponse response = alipayPayService.create(config, req);
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
return Result.succeed(response,order.getOrderNo());
|
||||||
|
} else {
|
||||||
|
return Result.failed(response.getMsg());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 支付异步回调 ====================
|
||||||
|
|
||||||
|
@Operation(summary = "支付宝支付异步通知(支付宝服务器回调)",
|
||||||
|
description = "Content-Type: application/x-www-form-urlencoded。"
|
||||||
|
+ "支付宝以 POST form 方式回调,验签后更新订单状态为已支付。"
|
||||||
|
+ "关键入参:app_id、out_trade_no、trade_no、trade_status、total_amount、sign。"
|
||||||
|
+ "出参:纯文本 success 或 failure")
|
||||||
|
@PostMapping("/pay/notify")
|
||||||
|
public String handleAlipayPayNotify(HttpServletRequest request) {
|
||||||
|
Map<String, String> params = toMap(request);
|
||||||
|
log.info("------收到支付宝支付回调通知------, summary: {}", summarizeNotify(params));
|
||||||
|
|
||||||
|
try {
|
||||||
|
String appId = params.get("app_id");
|
||||||
|
// ISV(服务商)模式下应优先使用 auth_app_id 定位商家应用
|
||||||
|
String authAppId = params.get("auth_app_id");
|
||||||
|
String lookupAppId = (authAppId != null && !authAppId.isEmpty()) ? authAppId : appId;
|
||||||
|
AlipayConfig config = alipayConfigService.getConfigByAppIdAndType(lookupAppId, "PAY");
|
||||||
|
if (config == null) {
|
||||||
|
log.error("支付宝支付配置不存在,appId: {}, authAppId: {}", appId, authAppId);
|
||||||
|
return "failure";
|
||||||
|
}
|
||||||
|
TenantContextHolder.setTenant(config.getTenantId());
|
||||||
|
|
||||||
|
if (!alipayNotifyVerifier.verify(params, config)) {
|
||||||
|
log.warn("支付宝回调验签失败, summary:{}", summarizeNotify(params));
|
||||||
|
return "failure";
|
||||||
|
}
|
||||||
|
|
||||||
|
String tradeStatus = params.get("trade_status");
|
||||||
|
if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
|
||||||
|
handleAlipayPaymentResult(params, config);
|
||||||
|
} else {
|
||||||
|
log.info("支付宝支付回调忽略非成功状态: {}", tradeStatus);
|
||||||
|
}
|
||||||
|
return "success";
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 关键步骤异常时返回 failure,触发支付宝重试(最多重试 8 次,间隔 2m/10m/10m/1h/2h/6h/15h)
|
||||||
|
log.error("处理支付宝支付回调失败,将由支付宝重试", e);
|
||||||
|
return "failure";
|
||||||
|
} finally {
|
||||||
|
TenantContextHolder.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleAlipayPaymentResult(Map<String, String> params, AlipayConfig config) {
|
||||||
|
String outTradeNo = params.get("out_trade_no");
|
||||||
|
String tradeNo = params.get("trade_no");
|
||||||
|
|
||||||
|
log.info("处理支付宝支付结果, 交易号:{}, 商户订单号:{}", tradeNo, outTradeNo);
|
||||||
|
|
||||||
|
Order order = orderService.getOrderByNumberWithFallback(outTradeNo, config.getTenantId());
|
||||||
|
if (order == null) {
|
||||||
|
// 订单不存在通常是数据落库延迟或脏数据,记录后让外层返回 failure 触发支付宝重试
|
||||||
|
log.error("支付宝回调订单不存在: {}, tenantId:{}", outTradeNo, config.getTenantId());
|
||||||
|
throw new IllegalStateException("订单不存在: " + outTradeNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (OrderStatus.PAID.getId().equals(order.getOrderStatus())) {
|
||||||
|
log.info("订单已支付,跳过: {}", outTradeNo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 业务验真:避免回调被重放/金额不一致 =====
|
||||||
|
// 注意:租户一致性校验已移除,因为回调配置可能由 webApp 降级提供,
|
||||||
|
// 订单租户(如 hbzhapp)与配置租户(webApp)不一致属于正常场景。
|
||||||
|
// 安全性由以下校验保证:app_id 匹配 + 金额匹配 + seller_id 匹配
|
||||||
|
|
||||||
|
// 1) 金额一致:DB 以"分"存储,支付宝回调 total_amount 为"元"
|
||||||
|
String expectedYuan = StringUtils.fenToYuanAmount(order.getOrderAmount());
|
||||||
|
String notifyTotal = params.get("total_amount");
|
||||||
|
if (expectedYuan == null || notifyTotal == null
|
||||||
|
|| !expectedYuan.equals(notifyTotal.trim())) {
|
||||||
|
log.error("支付宝回调金额不一致, expected:{}, notify:{}, outTradeNo:{}",
|
||||||
|
expectedYuan, notifyTotal, outTradeNo);
|
||||||
|
throw new IllegalStateException("回调金额与订单金额不一致");
|
||||||
|
}
|
||||||
|
// 3) 应用身份一致:优先校验 auth_app_id(ISV),否则校验 app_id
|
||||||
|
String notifyAuthAppId = params.get("auth_app_id");
|
||||||
|
String notifyAppId = params.get("app_id");
|
||||||
|
String expectedAppId = config.getAppId();
|
||||||
|
if (notifyAuthAppId != null && !notifyAuthAppId.isEmpty()) {
|
||||||
|
if (!notifyAuthAppId.equals(expectedAppId)) {
|
||||||
|
log.error("支付宝回调 auth_app_id 不匹配配置, notify:{}, config:{}",
|
||||||
|
notifyAuthAppId, expectedAppId);
|
||||||
|
throw new IllegalStateException("回调应用身份不匹配");
|
||||||
|
}
|
||||||
|
} else if (notifyAppId == null || !notifyAppId.equals(expectedAppId)) {
|
||||||
|
log.error("支付宝回调 app_id 不匹配配置, notify:{}, config:{}", notifyAppId, expectedAppId);
|
||||||
|
throw new IllegalStateException("回调应用身份不匹配");
|
||||||
|
}
|
||||||
|
// 4) 商家身份(卖家)一致:ISV 模式下 seller_id 应等于配置的 PID;直连模式下 seller_id 等于配置 PID 也成立
|
||||||
|
String notifySellerId = params.get("seller_id");
|
||||||
|
if (config.getPid() != null && !config.getPid().isEmpty()
|
||||||
|
&& notifySellerId != null && !notifySellerId.isEmpty()
|
||||||
|
&& !config.getPid().equals(notifySellerId)) {
|
||||||
|
log.error("支付宝回调 seller_id 与配置 pid 不一致, notify:{}, configPid:{}",
|
||||||
|
notifySellerId, config.getPid());
|
||||||
|
throw new IllegalStateException("回调商家身份不匹配");
|
||||||
|
}
|
||||||
|
|
||||||
|
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
|
||||||
|
|
||||||
|
order.setOrderStatus(OrderStatus.PAID.getId());
|
||||||
|
order.setPayType(PayTypeEnum.ALIPAY_PAY.getCode());
|
||||||
|
order.setPayTime(new Date());
|
||||||
|
orderService.updateOrder(order);
|
||||||
|
|
||||||
|
// 携程分销订单为旁路异步任务,失败不影响本地订单完成
|
||||||
|
if (qrCode != null && Integer.valueOf(1).equals(qrCode.getEnableCtripOrder())) {
|
||||||
|
log.info("二维码已开启携程分销,异步创建携程订单,orderNo: {}", order.getOrderNo());
|
||||||
|
try {
|
||||||
|
String mobile = null;
|
||||||
|
if (Objects.nonNull(order.getUserId())) {
|
||||||
|
SysUser sysUser = userService.findUserById(order.getUserId());
|
||||||
|
if (Objects.nonNull(sysUser) && StringUtil.isNotEmpty(sysUser.getMobile())) {
|
||||||
|
mobile = sysUser.getMobile();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctripDistOrderService.createCtripDistOrder(
|
||||||
|
order.getOrderNo(), order.getOrderAmount(),
|
||||||
|
qrCode.getCtripProductId(), order.getTenantId(), mobile);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("异步创建携程分销订单失败,orderNo: {},不影响本地订单", order.getOrderNo(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 退款异步回调 ====================
|
||||||
|
|
||||||
|
@Operation(summary = "支付宝退款异步通知(支付宝服务器回调)",
|
||||||
|
description = "Content-Type: application/x-www-form-urlencoded。"
|
||||||
|
+ "支付宝 POST form 方式回调退款结果,验签后更新退款单和订单状态。"
|
||||||
|
+ "关键入参:app_id、out_trade_no、out_biz_no、refund_fee、sign。"
|
||||||
|
+ "出参:纯文本 success 或 failure")
|
||||||
|
@PostMapping("/refund/notify")
|
||||||
|
public String handleAlipayRefundNotify(HttpServletRequest request) {
|
||||||
|
Map<String, String> params = toMap(request);
|
||||||
|
log.info("------收到支付宝退款回调通知------, summary: {}", summarizeNotify(params));
|
||||||
|
|
||||||
|
try {
|
||||||
|
String appId = params.get("app_id");
|
||||||
|
// ISV 模式下应使用 auth_app_id 定位商家应用
|
||||||
|
String authAppId = params.get("auth_app_id");
|
||||||
|
String lookupAppId = (authAppId != null && !authAppId.isEmpty()) ? authAppId : appId;
|
||||||
|
AlipayConfig config = alipayConfigService.getConfigByAppIdAndType(lookupAppId, "PAY");
|
||||||
|
if (config == null) {
|
||||||
|
log.error("支付宝支付配置不存在,appId: {}, authAppId: {}", appId, authAppId);
|
||||||
|
return "failure";
|
||||||
|
}
|
||||||
|
TenantContextHolder.setTenant(config.getTenantId());
|
||||||
|
|
||||||
|
if (!alipayNotifyVerifier.verify(params, config)) {
|
||||||
|
log.warn("支付宝退款回调验签失败");
|
||||||
|
return "failure";
|
||||||
|
}
|
||||||
|
|
||||||
|
handleAlipayRefundResult(params, config);
|
||||||
|
return "success";
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("处理支付宝退款回调失败,将由支付宝重试", e);
|
||||||
|
return "failure";
|
||||||
|
} finally {
|
||||||
|
TenantContextHolder.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleAlipayRefundResult(Map<String, String> params, AlipayConfig config) {
|
||||||
|
String outRefundNo = params.get("out_biz_no");
|
||||||
|
String outTradeNo = params.get("out_trade_no");
|
||||||
|
|
||||||
|
log.info("处理支付宝退款结果, 退款单号:{}, 商户订单号:{}", outRefundNo, outTradeNo);
|
||||||
|
|
||||||
|
com.central.order.model.Refund refund = refundService.getRefundByNo(outRefundNo);
|
||||||
|
if (refund == null) {
|
||||||
|
log.error("退款订单不存在: {}", outRefundNo);
|
||||||
|
throw new IllegalStateException("退款订单不存在: " + outRefundNo);
|
||||||
|
}
|
||||||
|
// 租户一致性校验已移除(与支付回调同理:配置可能由 webApp 降级提供)
|
||||||
|
|
||||||
|
if (refund.getState().equals(RefundState.PART.getId())) {
|
||||||
|
refund.setStatus(OrderStatus.PART_REFUNDED.getId());
|
||||||
|
} else {
|
||||||
|
refund.setStatus(OrderStatus.REFUNDED.getId());
|
||||||
|
}
|
||||||
|
refund.setRefundTime(new Date());
|
||||||
|
refundService.updateById(refund);
|
||||||
|
|
||||||
|
Order order = orderService.getOrderByNumberWithFallback(refund.getOrderNo(), config.getTenantId());
|
||||||
|
if (order != null) {
|
||||||
|
if (refund.getState().equals(RefundState.PART.getId())) {
|
||||||
|
order.setOrderStatus(OrderStatus.PART_REFUNDED.getId());
|
||||||
|
} else {
|
||||||
|
order.setOrderStatus(OrderStatus.REFUNDED.getId());
|
||||||
|
}
|
||||||
|
orderService.updateOrder(order);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 工具方法 ====================
|
||||||
|
|
||||||
|
private Map<String, String> toMap(HttpServletRequest request) {
|
||||||
|
// 支付宝 form 回调按 biz 参数 charset 编码(默认 UTF-8)。
|
||||||
|
// 必须在容器解析参数前 setCharacterEncoding;这里在读取任何参数前先尝试设置 UTF-8,
|
||||||
|
// 避免先 getParameter 触发解析后再 setCharacterEncoding 不生效的问题。
|
||||||
|
try {
|
||||||
|
request.setCharacterEncoding("UTF-8");
|
||||||
|
} catch (java.io.UnsupportedEncodingException ignored) {
|
||||||
|
}
|
||||||
|
Map<String, String> params = new HashMap<>();
|
||||||
|
Map<String, String[]> requestParams = request.getParameterMap();
|
||||||
|
for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
|
||||||
|
String name = entry.getKey();
|
||||||
|
String[] values = entry.getValue();
|
||||||
|
String valueStr = (values != null && values.length > 0) ? values[0] : "";
|
||||||
|
params.put(name, valueStr);
|
||||||
|
}
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仅保留排查必需的非敏感字段,避免回调日志泄露 buyer/sign 等信息
|
||||||
|
*/
|
||||||
|
private Map<String, String> summarizeNotify(Map<String, String> params) {
|
||||||
|
Set<String> safeKeys = Set.of(
|
||||||
|
"out_trade_no", "trade_no", "trade_status",
|
||||||
|
"app_id", "auth_app_id", "out_biz_no",
|
||||||
|
"refund_status", "gmt_payment", "gmt_refund");
|
||||||
|
Map<String, String> safe = new LinkedHashMap<>();
|
||||||
|
for (String k : safeKeys) {
|
||||||
|
String v = params.get(k);
|
||||||
|
if (v != null) {
|
||||||
|
safe.put(k, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return safe;
|
||||||
|
}
|
||||||
|
}
|
||||||
+210
@@ -0,0 +1,210 @@
|
|||||||
|
package com.central.order.controller;
|
||||||
|
|
||||||
|
import com.central.alipay.config.AlipayClientFactory;
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import com.central.common.model.PageResult;
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.order.service.IAlipayConfigService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝配置管理控制器
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Tag(name = "支付宝配置管理", description = "alipay_config 表 CRUD,供管理后台和 Feign 内部调用")
|
||||||
|
@RequestMapping("/alipay/config")
|
||||||
|
public class AlipayConfigController {
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private IAlipayConfigService alipayConfigService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private AlipayClientFactory alipayClientFactory;
|
||||||
|
|
||||||
|
// ==================== 管理后台 CRUD 端点 ====================
|
||||||
|
|
||||||
|
@Operation(summary = "分页查询支付宝配置",
|
||||||
|
description = "支持按 type/tenantId/appId/status 筛选,出参 PageResult<AlipayConfig>,敏感字段已脱敏")
|
||||||
|
@Parameter(name = "page", description = "页码", in = ParameterIn.QUERY, example = "1")
|
||||||
|
@Parameter(name = "limit", description = "每页条数", in = ParameterIn.QUERY, example = "10")
|
||||||
|
@Parameter(name = "searchKey", description = "检索字段:type/appId/tenantId", in = ParameterIn.QUERY)
|
||||||
|
@Parameter(name = "searchValue", description = "检索关键字", in = ParameterIn.QUERY)
|
||||||
|
@GetMapping("/list")
|
||||||
|
public Result<PageResult<AlipayConfig>> list(@RequestParam Map<String, Object> params) {
|
||||||
|
PageResult<AlipayConfig> pageResult = alipayConfigService.findList(params);
|
||||||
|
if (pageResult != null && pageResult.getData() != null) {
|
||||||
|
pageResult.getData().forEach(this::maskSensitive);
|
||||||
|
}
|
||||||
|
return Result.succeed(pageResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "根据ID查询支付宝配置",
|
||||||
|
description = "返回单条 AlipayConfig,敏感字段(私钥/公钥/authToken/encryptKey)已脱敏")
|
||||||
|
@Parameter(name = "id", description = "配置主键ID", required = true, in = ParameterIn.PATH, example = "1")
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public Result<AlipayConfig> getById(@PathVariable Long id) {
|
||||||
|
AlipayConfig config = alipayConfigService.getById(id);
|
||||||
|
maskSensitive(config);
|
||||||
|
return Result.succeed(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "新增支付宝配置",
|
||||||
|
description = "Body 为 AlipayConfig JSON,必填:tenantId/type/appId")
|
||||||
|
@io.swagger.v3.oas.annotations.parameters.RequestBody(
|
||||||
|
description = "支付宝配置对象", required = true,
|
||||||
|
content = @Content(schema = @Schema(implementation = AlipayConfig.class)))
|
||||||
|
@PostMapping
|
||||||
|
public Result<Boolean> save(@RequestBody AlipayConfig config) {
|
||||||
|
boolean result = alipayConfigService.saveConfig(config);
|
||||||
|
if (result) {
|
||||||
|
// 新增配置可能复用现有 appId(同 appId 不同 subMerchantId / 不同 type),保险起见清空全部缓存
|
||||||
|
alipayClientFactory.clearAllCache();
|
||||||
|
}
|
||||||
|
return Result.succeed(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "更新支付宝配置",
|
||||||
|
description = "Body 为 AlipayConfig JSON(含 id),增量更新;敏感字段(appPrivateKey/alipayPublicKey/authToken/encryptKey)传入掩码 ****** 表示保留原值")
|
||||||
|
@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "支付宝配置对象(含 id)", required = true)
|
||||||
|
@PutMapping
|
||||||
|
public Result<Boolean> update(@RequestBody AlipayConfig config) {
|
||||||
|
// 当字段值为掩码时,保留库中原值,避免管理后台误覆盖为 ******
|
||||||
|
if (config.getId() != null) {
|
||||||
|
AlipayConfig original = alipayConfigService.getById(config.getId());
|
||||||
|
if (original != null) {
|
||||||
|
if (isMasked(config.getAppPrivateKey())) {
|
||||||
|
config.setAppPrivateKey(original.getAppPrivateKey());
|
||||||
|
}
|
||||||
|
if (isMasked(config.getAlipayPublicKey())) {
|
||||||
|
config.setAlipayPublicKey(original.getAlipayPublicKey());
|
||||||
|
}
|
||||||
|
if (isMasked(config.getAuthToken())) {
|
||||||
|
config.setAuthToken(original.getAuthToken());
|
||||||
|
}
|
||||||
|
if (isMasked(config.getEncryptKey())) {
|
||||||
|
config.setEncryptKey(original.getEncryptKey());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
boolean result = alipayConfigService.updateConfig(config);
|
||||||
|
if (result) {
|
||||||
|
// 更新后清理缓存:可能改了密钥/证书/subMerchantId/启停,必须使旧 AlipayClient 失效
|
||||||
|
alipayClientFactory.clearCache(config);
|
||||||
|
}
|
||||||
|
return Result.succeed(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除支付宝配置")
|
||||||
|
@Parameter(name = "id", description = "配置主键ID", required = true, in = ParameterIn.PATH, example = "1")
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public Result<Boolean> delete(@PathVariable Long id) {
|
||||||
|
AlipayConfig original = alipayConfigService.getById(id);
|
||||||
|
boolean result = alipayConfigService.deleteConfig(id);
|
||||||
|
if (result && original != null) {
|
||||||
|
alipayClientFactory.clearCache(original);
|
||||||
|
}
|
||||||
|
return Result.succeed(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "切换配置启用/禁用状态",
|
||||||
|
description = "Body: {\"status\": 0|1}")
|
||||||
|
@Parameter(name = "id", description = "配置主键ID", required = true, in = ParameterIn.PATH, example = "1")
|
||||||
|
@io.swagger.v3.oas.annotations.parameters.RequestBody(
|
||||||
|
description = "{\"status\": 1} 启用, {\"status\": 0} 禁用", required = true)
|
||||||
|
@PatchMapping("/{id}/status")
|
||||||
|
public Result<Boolean> toggleStatus(@PathVariable Long id, @RequestBody Map<String, Object> body) {
|
||||||
|
AlipayConfig config = alipayConfigService.getById(id);
|
||||||
|
if (config == null) {
|
||||||
|
return Result.failed("配置不存在");
|
||||||
|
}
|
||||||
|
config.setStatus(Integer.valueOf(body.get("status").toString()));
|
||||||
|
boolean result = alipayConfigService.updateConfig(config);
|
||||||
|
if (result) {
|
||||||
|
// 启停切换后必须清理缓存,避免禁用配置仍被复用
|
||||||
|
alipayClientFactory.clearCache(config);
|
||||||
|
}
|
||||||
|
return Result.succeed(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Feign 调用端点(返回原始实体,无 Result 包装) ====================
|
||||||
|
|
||||||
|
@Operation(summary = "根据类型+租户ID查询配置(Feign内部调用)",
|
||||||
|
description = "供 AlipayClientFactory 调用,出参为原始 AlipayConfig 或 null")
|
||||||
|
@Parameter(name = "type", description = "MINI(小程序登录)/ PAY(交易支付)", required = true, in = ParameterIn.PATH)
|
||||||
|
@Parameter(name = "tenantId", description = "租户ID", required = true, in = ParameterIn.QUERY, example = "tenant-001")
|
||||||
|
@GetMapping("/type/{type}")
|
||||||
|
public AlipayConfig getConfig(@PathVariable String type, @RequestParam String tenantId) {
|
||||||
|
return alipayConfigService.getConfigByTypeAndTenantId(type, tenantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "根据AppId+类型查询配置(Feign内部调用)",
|
||||||
|
description = "供 AlipayAuthenticationProvider 调用")
|
||||||
|
@Parameter(name = "appId", description = "支付宝 AppId", required = true, in = ParameterIn.PATH, example = "2021000000000001")
|
||||||
|
@Parameter(name = "type", description = "MINI / PAY", in = ParameterIn.QUERY)
|
||||||
|
@GetMapping("/app/{appId}")
|
||||||
|
public AlipayConfig getConfigByAppId(@PathVariable("appId") String appId,
|
||||||
|
@RequestParam(required = false) String type) {
|
||||||
|
if (type != null && !type.isEmpty()) {
|
||||||
|
return alipayConfigService.getConfigByAppIdAndType(appId, type);
|
||||||
|
}
|
||||||
|
return alipayConfigService.getConfigByAppId(appId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "根据AppId查询配置不区分类型(Feign内部调用)",
|
||||||
|
description = "供回调验签使用")
|
||||||
|
@Parameter(name = "appId", description = "支付宝 AppId", required = true, in = ParameterIn.PATH, example = "2021000000000001")
|
||||||
|
@GetMapping("/app/{appId}/any")
|
||||||
|
public AlipayConfig getConfigByAppIdAny(@PathVariable("appId") String appId) {
|
||||||
|
return alipayConfigService.getConfigByAppId(appId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "根据子商户号查询配置(Feign内部调用,ISV模式)")
|
||||||
|
@Parameter(name = "subMerchantId", description = "间连商户号 smid", required = true, in = ParameterIn.PATH, example = "2088xxxx")
|
||||||
|
@GetMapping("/sub/{subMerchantId}")
|
||||||
|
public AlipayConfig getConfigBySubMerchantId(@PathVariable("subMerchantId") String subMerchantId) {
|
||||||
|
return alipayConfigService.getConfigBySubMerchantId(subMerchantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 内部工具:敏感字段脱敏 ====================
|
||||||
|
|
||||||
|
private static final String MASK = "******";
|
||||||
|
|
||||||
|
private void maskSensitive(AlipayConfig config) {
|
||||||
|
if (config == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (config.getAppPrivateKey() != null && !config.getAppPrivateKey().isEmpty()) {
|
||||||
|
config.setAppPrivateKey(MASK);
|
||||||
|
}
|
||||||
|
if (config.getAlipayPublicKey() != null && !config.getAlipayPublicKey().isEmpty()) {
|
||||||
|
config.setAlipayPublicKey(MASK);
|
||||||
|
}
|
||||||
|
if (config.getAuthToken() != null && !config.getAuthToken().isEmpty()) {
|
||||||
|
config.setAuthToken(MASK);
|
||||||
|
}
|
||||||
|
if (config.getEncryptKey() != null && !config.getEncryptKey().isEmpty()) {
|
||||||
|
config.setEncryptKey(MASK);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isMasked(String value) {
|
||||||
|
return MASK.equals(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
package com.central.order.controller;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.order.service.ICtripDistOrderService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/ctrip/dist/order")
|
||||||
|
@Tag(name = "携程分销订单-手动触发")
|
||||||
|
public class CtripDistOrderController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICtripDistOrderService ctripDistOrderService;
|
||||||
|
|
||||||
|
@Operation(summary = "手动触发创建携程分销订单")
|
||||||
|
@PostMapping("/manualCreate")
|
||||||
|
public Result<String> manualCreateCtripDistOrder(
|
||||||
|
@Parameter(description = "本地订单号") @RequestParam String orderNo,
|
||||||
|
@Parameter(description = "订单金额(分)") @RequestParam String orderAmount,
|
||||||
|
@Parameter(description = "携程产品ID") @RequestParam Long ctripProductId,
|
||||||
|
@Parameter(description = "租户ID") @RequestParam String tenantId,
|
||||||
|
@Parameter(description = "用户手机号") @RequestParam(required = false) String mobile) {
|
||||||
|
log.info("手动触发创建携程分销订单,orderNo: {}, ctripProductId: {}", orderNo, ctripProductId);
|
||||||
|
try {
|
||||||
|
ctripDistOrderService.createCtripDistOrder(orderNo, orderAmount, ctripProductId, tenantId, mobile);
|
||||||
|
return Result.succeed("携程分销订单创建请求已提交(异步处理中)");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("手动触发创建携程分销订单异常,orderNo: {}", orderNo, e);
|
||||||
|
return Result.failed("创建失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
-5
@@ -595,15 +595,10 @@ public class OrderController {
|
|||||||
@Operation(summary = "后台管理更新订单")
|
@Operation(summary = "后台管理更新订单")
|
||||||
@PostMapping("/update/order")
|
@PostMapping("/update/order")
|
||||||
public Result updateOrder(@RequestBody Order order) {
|
public Result updateOrder(@RequestBody Order order) {
|
||||||
LoginAppUser loginAppUser = LoginUserContextHolder.getUser();
|
|
||||||
//
|
|
||||||
if (loginAppUser.getId() == 1 || loginAppUser.getId() == 1073) {
|
|
||||||
boolean res = orderService.updateOrder(order);
|
boolean res = orderService.updateOrder(order);
|
||||||
if (res) {
|
if (res) {
|
||||||
return Result.succeed("已更新");
|
return Result.succeed("已更新");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return Result.failed("请重试");
|
return Result.failed("请重试");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+37
-11
@@ -6,6 +6,7 @@ import com.central.common.feign.UserService;
|
|||||||
import com.central.common.model.*;
|
import com.central.common.model.*;
|
||||||
import com.central.order.constants.EditTaskStatus;
|
import com.central.order.constants.EditTaskStatus;
|
||||||
import com.central.order.enums.OrderStatus;
|
import com.central.order.enums.OrderStatus;
|
||||||
|
import com.central.order.enums.PayTypeEnum;
|
||||||
import com.central.order.feign.FileCenterService;
|
import com.central.order.feign.FileCenterService;
|
||||||
import com.central.order.model.*;
|
import com.central.order.model.*;
|
||||||
import com.central.order.model.params.FileDownloadRequest;
|
import com.central.order.model.params.FileDownloadRequest;
|
||||||
@@ -93,6 +94,9 @@ public class OrderFileController {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private WxMiniSubscribeService wxMiniSubscribeService;
|
private WxMiniSubscribeService wxMiniSubscribeService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private AlipayMiniSubscribeService alipayMiniSubscribeService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IEditTaskService editTaskService;
|
private IEditTaskService editTaskService;
|
||||||
|
|
||||||
@@ -314,6 +318,8 @@ public class OrderFileController {
|
|||||||
if (updateResult) {
|
if (updateResult) {
|
||||||
log.info("订单状态已更新为UPLOADED: orderNo={}, oldStatus={}, newStatus={}",
|
log.info("订单状态已更新为UPLOADED: orderNo={}, oldStatus={}, newStatus={}",
|
||||||
latestOrder.getOrderNo(), oldStatus, OrderStatus.UPLOADED.getId());
|
latestOrder.getOrderNo(), oldStatus, OrderStatus.UPLOADED.getId());
|
||||||
|
// 首次达标才预热订单文件到CDN,避免重复预热
|
||||||
|
prefetchOrderFilesToCdn(latestOrder.getOrderNo());
|
||||||
} else {
|
} else {
|
||||||
log.error("订单状态更新为UPLOADED失败: orderNo={}", latestOrder.getOrderNo());
|
log.error("订单状态更新为UPLOADED失败: orderNo={}", latestOrder.getOrderNo());
|
||||||
}
|
}
|
||||||
@@ -322,9 +328,6 @@ public class OrderFileController {
|
|||||||
//发送用户素材上传成功通知
|
//发送用户素材上传成功通知
|
||||||
sendMessageForResouresUploaded(latestOrder,tourism);
|
sendMessageForResouresUploaded(latestOrder,tourism);
|
||||||
|
|
||||||
// 预热订单相关的文件到CDN
|
|
||||||
prefetchOrderFilesToCdn(latestOrder.getOrderNo());
|
|
||||||
|
|
||||||
// 7分钟后如果状态仍为UPLOADED,则自动更新为COMPLETE;若已完成则不再安排
|
// 7分钟后如果状态仍为UPLOADED,则自动更新为COMPLETE;若已完成则不再安排
|
||||||
if (!isComplete) {
|
if (!isComplete) {
|
||||||
scheduleAutoCompleteIfStillUploaded(latestOrder.getOrderNo());
|
scheduleAutoCompleteIfStillUploaded(latestOrder.getOrderNo());
|
||||||
@@ -418,12 +421,6 @@ public class OrderFileController {
|
|||||||
* @param tourism
|
* @param tourism
|
||||||
*/
|
*/
|
||||||
private void sendMessageForResouresUploaded(Order order, Tourism tourism) {
|
private void sendMessageForResouresUploaded(Order order, Tourism tourism) {
|
||||||
// 发送小程序订阅消息,用户素材上传完成
|
|
||||||
SysUser sysUser = userCenterService.findUserById(order.getUserId());
|
|
||||||
|
|
||||||
if (sysUser.getOpenId() != null) {
|
|
||||||
|
|
||||||
String tip = "素材上传完成";
|
|
||||||
String orderName = tourism.getTourismName();
|
String orderName = tourism.getTourismName();
|
||||||
String pageUrl = "pages/album/album";
|
String pageUrl = "pages/album/album";
|
||||||
// 处理支付时间为空的情况
|
// 处理支付时间为空的情况
|
||||||
@@ -431,16 +428,31 @@ public class OrderFileController {
|
|||||||
if (order.getPayTime() != null) {
|
if (order.getPayTime() != null) {
|
||||||
payTimeStr = DateUtils.sdf.format(order.getPayTime());
|
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(
|
wxMiniSubscribeService.sendServiceProcessMsg(
|
||||||
sysUser.getOpenId(),
|
sysUser.getOpenId(),
|
||||||
orderName,
|
orderName,
|
||||||
tip,
|
"素材上传完成",
|
||||||
order.getOrderNo(),
|
order.getOrderNo(),
|
||||||
payTimeStr,
|
payTimeStr,
|
||||||
"",
|
"",
|
||||||
pageUrl
|
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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -464,9 +476,14 @@ public class OrderFileController {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 收集所有文件的URL
|
// 收集所有文件的URL(跳过视频文件,视频不做预热,避免CDN回源流量暴增)
|
||||||
List<String> fileUrls = new ArrayList<>();
|
List<String> fileUrls = new ArrayList<>();
|
||||||
for (OrderFile orderFile : orderFiles) {
|
for (OrderFile orderFile : orderFiles) {
|
||||||
|
// 跳过视频文件:视频体积大且点播命中率低,预热会造成大量CDN回源流量
|
||||||
|
if (isVideoFile(orderFile.getFileType())) {
|
||||||
|
log.debug("跳过视频文件预热,文件路径: {}, 类型: {}", orderFile.getFilePath(), orderFile.getFileType());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
String viewUrl = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
String viewUrl = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||||
if (viewUrl != null && !viewUrl.trim().isEmpty()) {
|
if (viewUrl != null && !viewUrl.trim().isEmpty()) {
|
||||||
@@ -519,6 +536,15 @@ public class OrderFileController {
|
|||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否为视频文件
|
||||||
|
* @param fileType 文件类型(如 video/mp4、image/jpeg)
|
||||||
|
* @return 是否为视频
|
||||||
|
*/
|
||||||
|
private boolean isVideoFile(String fileType) {
|
||||||
|
return fileType != null && fileType.startsWith("video/");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@Operation(summary = "删除文件")
|
@Operation(summary = "删除文件")
|
||||||
@DeleteMapping( "/{id}")
|
@DeleteMapping( "/{id}")
|
||||||
|
|||||||
+52
@@ -1,5 +1,6 @@
|
|||||||
package com.central.order.controller;
|
package com.central.order.controller;
|
||||||
|
|
||||||
|
import com.central.alipay.service.AlipayQrcodeService;
|
||||||
import com.central.common.model.PageResult;
|
import com.central.common.model.PageResult;
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.common.utils.StringUtils;
|
import com.central.common.utils.StringUtils;
|
||||||
@@ -21,6 +22,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
|||||||
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.beans.factory.annotation.Value;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
@@ -59,6 +61,15 @@ public class QrCodeController {
|
|||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IPackagePlanService packagePlanService;
|
private IPackagePlanService packagePlanService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private AlipayQrcodeService alipayQrcodeService;
|
||||||
|
|
||||||
|
@Value("${zlt.security.alipay.pagePath:pages/link/link}")
|
||||||
|
private String alipayPagePath;
|
||||||
|
|
||||||
|
@Value("${zlt.security.alipay.queryKey:uuid}")
|
||||||
|
private String alipayQueryKey;
|
||||||
/**
|
/**
|
||||||
* 列表
|
* 列表
|
||||||
*/
|
*/
|
||||||
@@ -73,6 +84,9 @@ public class QrCodeController {
|
|||||||
if (pageResult.getResp_code() == 0){
|
if (pageResult.getResp_code() == 0){
|
||||||
for (QrCode qrCode: pageResult.getData()){
|
for (QrCode qrCode: pageResult.getData()){
|
||||||
qrCode.setViewUrl(fileCenterService.getViewUrlByPath(qrCode.getFilePath()));
|
qrCode.setViewUrl(fileCenterService.getViewUrlByPath(qrCode.getFilePath()));
|
||||||
|
if (qrCode.getAlipayFilePath() != null && !qrCode.getAlipayFilePath().isEmpty()) {
|
||||||
|
qrCode.setAlipayViewUrl(fileCenterService.getS3ViewUrlByPath(qrCode.getAlipayFilePath()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return pageResult;
|
return pageResult;
|
||||||
@@ -252,4 +266,42 @@ public class QrCodeController {
|
|||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "为已存在的二维码生成支付宝小程序码(同行追加,不另起一行)")
|
||||||
|
@PostMapping("/{id}/alipay")
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public Result<QrCode> generateAlipayQrcode(@PathVariable("id") Long id) throws Exception {
|
||||||
|
QrCode qrCode = qrCodeService.getById(id);
|
||||||
|
Assert.notNull(qrCode, "二维码不存在");
|
||||||
|
Assert.hasText(qrCode.getCodeId(), "codeId 缺失");
|
||||||
|
Assert.hasText(qrCode.getTenantId(), "tenantId 缺失");
|
||||||
|
|
||||||
|
String qrCodeUrl = alipayQrcodeService.createMiniQrcode(
|
||||||
|
qrCode.getTenantId(),
|
||||||
|
qrCode.getCodeId(),
|
||||||
|
alipayPagePath,
|
||||||
|
alipayQueryKey,
|
||||||
|
qrCode.getName());
|
||||||
|
if (qrCodeUrl == null || qrCodeUrl.isEmpty()) {
|
||||||
|
return Result.failed("支付宝二维码生成失败:qr_code_url 为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
Result<Map> upload = fileCenterService.uploadQrCodeToS3ByUrl(qrCode.getCodeId(), qrCodeUrl, "png");
|
||||||
|
if (upload == null || upload.getResp_code() != 0) {
|
||||||
|
return Result.failed("支付宝二维码上传 S3 失败");
|
||||||
|
}
|
||||||
|
Object fileId = upload.getData().get("fileId");
|
||||||
|
Object filePath = upload.getData().get("filePath");
|
||||||
|
if (fileId == null || filePath == null) {
|
||||||
|
return Result.failed("支付宝二维码上传响应缺少 fileId/filePath");
|
||||||
|
}
|
||||||
|
qrCode.setAlipayFileId(fileId.toString());
|
||||||
|
qrCode.setAlipayFilePath(filePath.toString());
|
||||||
|
qrCodeService.updateById(qrCode);
|
||||||
|
|
||||||
|
// 列表展示用:同步把 view url 拉一次
|
||||||
|
qrCode.setViewUrl(fileCenterService.getViewUrlByPath(qrCode.getFilePath()));
|
||||||
|
qrCode.setAlipayViewUrl(fileCenterService.getS3ViewUrlByPath(qrCode.getAlipayFilePath()));
|
||||||
|
return Result.succeed(qrCode, "支付宝二维码生成成功");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+142
-6
@@ -5,7 +5,10 @@ import com.central.common.feign.UserService;
|
|||||||
import com.central.common.model.PageResult;
|
import com.central.common.model.PageResult;
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.common.model.SysUser;
|
import com.central.common.model.SysUser;
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import com.central.alipay.service.AlipayRefundService;
|
||||||
import com.central.order.enums.OrderStatus;
|
import com.central.order.enums.OrderStatus;
|
||||||
|
import com.central.order.enums.PayTypeEnum;
|
||||||
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.QrCode;
|
import com.central.order.model.QrCode;
|
||||||
@@ -64,6 +67,15 @@ public class RefundController {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private IQrCodeService qrCodeService;
|
private IQrCodeService qrCodeService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private com.central.order.service.ICtripDistOrderService ctripDistOrderService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private com.central.order.service.IAlipayConfigService alipayConfigService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private AlipayRefundService alipayRefundService;
|
||||||
|
|
||||||
@Value("${tencent.refund-notify-url}")
|
@Value("${tencent.refund-notify-url}")
|
||||||
private String refundNotifyUrl;
|
private String refundNotifyUrl;
|
||||||
|
|
||||||
@@ -153,6 +165,12 @@ public class RefundController {
|
|||||||
// 检查订单是否存在
|
// 检查订单是否存在
|
||||||
Order order = orderService.getOrderByNumber(refund.getOrderNo());
|
Order order = orderService.getOrderByNumber(refund.getOrderNo());
|
||||||
Assert.notNull(order, "ORDER DATA不存在");
|
Assert.notNull(order, "ORDER DATA不存在");
|
||||||
|
// 校验退款单存在并与订单一致
|
||||||
|
com.central.order.model.Refund refundDb = refundService.getRefundByNo(refund.getRefundNo());
|
||||||
|
Assert.notNull(refundDb, "退款订单不存在");
|
||||||
|
if (!order.getOrderNo().equals(refundDb.getOrderNo())) {
|
||||||
|
return Result.failed("退款单与订单不匹配");
|
||||||
|
}
|
||||||
if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){
|
if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){
|
||||||
return Result.failed("请重试");
|
return Result.failed("请重试");
|
||||||
}
|
}
|
||||||
@@ -160,14 +178,23 @@ public class RefundController {
|
|||||||
return Result.failed("该状态不支持审核");
|
return Result.failed("该状态不支持审核");
|
||||||
}
|
}
|
||||||
if (refund.getState().equals(RefundState.APPROVED.getId())){
|
if (refund.getState().equals(RefundState.APPROVED.getId())){
|
||||||
dealRefundRequest(order);
|
// 同步退款(支付宝/微信)成功后,立即推进本地退款单与订单为已退款,避免长期停留在退款中
|
||||||
|
routeRefundByPayType(order, null);
|
||||||
|
refundDb.setState(RefundState.APPROVED.getId());
|
||||||
|
refundDb.setStatus(OrderStatus.REFUNDED.getId());
|
||||||
|
refundDb.setRefundTime(new java.util.Date());
|
||||||
|
refundService.updateById(refundDb);
|
||||||
|
order.setOrderStatus(OrderStatus.REFUNDED.getId());
|
||||||
|
orderService.updateOrder(order);
|
||||||
return Result.succeed("已处理退款");
|
return Result.succeed("已处理退款");
|
||||||
}
|
}
|
||||||
if (refund.getState().equals(RefundState.REFUSED.getId())){
|
if (refund.getState().equals(RefundState.REFUSED.getId())){
|
||||||
order.setOrderStatus(OrderStatus.REFUND_FAILED.getId());
|
order.setOrderStatus(OrderStatus.REFUND_FAILED.getId());
|
||||||
refund.setStatus(OrderStatus.REFUND_FAILED.getId());
|
refundDb.setStatus(OrderStatus.REFUND_FAILED.getId());
|
||||||
|
refundDb.setState(RefundState.REFUSED.getId());
|
||||||
|
refundDb.setApproveReason(refund.getApproveReason());
|
||||||
orderService.updateOrder(order);
|
orderService.updateOrder(order);
|
||||||
refundService.updateById(refund);
|
refundService.updateById(refundDb);
|
||||||
return Result.succeed("处理成功");
|
return Result.succeed("处理成功");
|
||||||
}
|
}
|
||||||
return Result.failed("处理退款失败");
|
return Result.failed("处理退款失败");
|
||||||
@@ -183,7 +210,19 @@ public class RefundController {
|
|||||||
Order order = orderService.getOrderByNumber(refundRequest.getOrderNo());
|
Order order = orderService.getOrderByNumber(refundRequest.getOrderNo());
|
||||||
Assert.notNull(order, "ORDER DATA不存在");
|
Assert.notNull(order, "ORDER DATA不存在");
|
||||||
com.central.order.model.Refund refundorder = refundService.getRefundByNo(refundRequest.getRefundNo());
|
com.central.order.model.Refund refundorder = refundService.getRefundByNo(refundRequest.getRefundNo());
|
||||||
Assert.notNull(order, "退款订单不存在");
|
Assert.notNull(refundorder, "退款订单不存在");
|
||||||
|
// 退款单必须与订单匹配(订单号、租户、用户)
|
||||||
|
if (!order.getOrderNo().equals(refundorder.getOrderNo())) {
|
||||||
|
return Result.failed("退款单与订单不匹配");
|
||||||
|
}
|
||||||
|
if (order.getTenantId() != null && refundorder.getTenantId() != null
|
||||||
|
&& !order.getTenantId().equals(refundorder.getTenantId())) {
|
||||||
|
return Result.failed("退款单与订单租户不一致");
|
||||||
|
}
|
||||||
|
if (order.getUserId() != null && refundorder.getUserId() != null
|
||||||
|
&& !order.getUserId().equals(refundorder.getUserId())) {
|
||||||
|
return Result.failed("退款单与订单用户不一致");
|
||||||
|
}
|
||||||
if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){
|
if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){
|
||||||
return Result.failed("订单状态不支持退款");
|
return Result.failed("订单状态不支持退款");
|
||||||
}
|
}
|
||||||
@@ -192,20 +231,35 @@ public class RefundController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (refundRequest.getState().equals(RefundState.APPROVED.getId())){
|
if (refundRequest.getState().equals(RefundState.APPROVED.getId())){
|
||||||
dealCustomRefundAmountRequest(order,null);
|
routeRefundByPayType(order, null);
|
||||||
refundorder.setApproveReason(refundRequest.getApproveReason());
|
refundorder.setApproveReason(refundRequest.getApproveReason());
|
||||||
refundorder.setState(refundRequest.getState()); //全额退款
|
refundorder.setState(refundRequest.getState()); //全额退款
|
||||||
|
// 同步全额退款成功后,推进本地状态到已退款
|
||||||
|
refundorder.setStatus(OrderStatus.REFUNDED.getId());
|
||||||
|
refundorder.setRefundTime(new java.util.Date());
|
||||||
refundService.updateById(refundorder);
|
refundService.updateById(refundorder);
|
||||||
|
order.setOrderStatus(OrderStatus.REFUNDED.getId());
|
||||||
|
orderService.updateOrder(order);
|
||||||
|
// 全额退款成功后,根据二维码配置判断是否需要异步退订携程分销订单
|
||||||
|
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
|
||||||
|
if (qrCode != null && qrCode.getEnableCtripOrder() != null && qrCode.getEnableCtripOrder() == 1) {
|
||||||
|
ctripDistOrderService.cancelCtripDistOrder(order.getOrderNo(), "用户申请全额退款");
|
||||||
|
}
|
||||||
return Result.succeed("已处理全额退款");
|
return Result.succeed("已处理全额退款");
|
||||||
}
|
}
|
||||||
if (refundRequest.getState().equals(RefundState.PART.getId())){
|
if (refundRequest.getState().equals(RefundState.PART.getId())){
|
||||||
dealCustomRefundAmountRequest(order,refundRequest.getRefundAmount());
|
routeRefundByPayType(order, refundRequest.getRefundAmount());
|
||||||
refundorder.setApproveReason(refundRequest.getApproveReason());
|
refundorder.setApproveReason(refundRequest.getApproveReason());
|
||||||
refundorder.setState(refundRequest.getState()); //部分退款
|
refundorder.setState(refundRequest.getState()); //部分退款
|
||||||
if(refundRequest.getRefundAmount()!=null){
|
if(refundRequest.getRefundAmount()!=null){
|
||||||
refundorder.setRefundAmount(refundRequest.getRefundAmount());
|
refundorder.setRefundAmount(refundRequest.getRefundAmount());
|
||||||
}
|
}
|
||||||
|
// 同步部分退款成功后,推进本地状态到部分已退款
|
||||||
|
refundorder.setStatus(OrderStatus.PART_REFUNDED.getId());
|
||||||
|
refundorder.setRefundTime(new java.util.Date());
|
||||||
refundService.updateById(refundorder);
|
refundService.updateById(refundorder);
|
||||||
|
order.setOrderStatus(OrderStatus.PART_REFUNDED.getId());
|
||||||
|
orderService.updateOrder(order);
|
||||||
return Result.succeed("已处理部分退款");
|
return Result.succeed("已处理部分退款");
|
||||||
}
|
}
|
||||||
if (refundRequest.getState().equals(RefundState.REFUSED.getId())){
|
if (refundRequest.getState().equals(RefundState.REFUSED.getId())){
|
||||||
@@ -302,6 +356,88 @@ public class RefundController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按 payType 路由退款到对应渠道
|
||||||
|
*
|
||||||
|
* @param order 订单
|
||||||
|
* @param customAmount 自定义退款金额(null 表示全额退款)
|
||||||
|
*/
|
||||||
|
private void routeRefundByPayType(Order order, String customAmount) {
|
||||||
|
PayTypeEnum channel = PayTypeEnum.getByCode(order.getPayType());
|
||||||
|
|
||||||
|
// 历史订单 payType 为 null 的兜底:走微信退款
|
||||||
|
if (channel == null) {
|
||||||
|
log.warn("订单 payType 为空,兜底走微信退款,orderNo: {}", order.getOrderNo());
|
||||||
|
if (customAmount != null) {
|
||||||
|
dealCustomRefundAmountRequest(order, customAmount);
|
||||||
|
} else {
|
||||||
|
dealRefundRequest(order);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (channel) {
|
||||||
|
case WECHAT_PAY:
|
||||||
|
if (customAmount != null) {
|
||||||
|
dealCustomRefundAmountRequest(order, customAmount);
|
||||||
|
} else {
|
||||||
|
dealRefundRequest(order);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case ALIPAY_PAY:
|
||||||
|
alipayRefund(order, customAmount);
|
||||||
|
break;
|
||||||
|
case COUPON_PAY:
|
||||||
|
log.info("优惠券支付退款,orderNo: {}", order.getOrderNo());
|
||||||
|
// 优惠券退款逻辑由现有流程处理
|
||||||
|
break;
|
||||||
|
case FEIPAI_VERIFY:
|
||||||
|
throw new RuntimeException("第三方核销订单不支持系统退款");
|
||||||
|
default:
|
||||||
|
throw new RuntimeException("未知支付类型: " + order.getPayType());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝退款
|
||||||
|
*/
|
||||||
|
private void alipayRefund(Order order, String customAmount) {
|
||||||
|
try {
|
||||||
|
TenantContextHolder.setTenant(order.getTenantId());
|
||||||
|
// 获取支付宝配置
|
||||||
|
AlipayConfig config = alipayConfigService.getConfigByTypeAndTenantId("PAY", order.getTenantId());
|
||||||
|
if (config == null) {
|
||||||
|
log.error("支付宝支付配置不存在,租户ID: {}", order.getTenantId());
|
||||||
|
throw new RuntimeException("支付宝支付配置不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
AlipayRefundService.AlipayRefundRequest req = new AlipayRefundService.AlipayRefundRequest();
|
||||||
|
req.setOutTradeNo(order.getOrderNo());
|
||||||
|
req.setOutRequestNo("RF" + order.getOrderNo());
|
||||||
|
req.setRefundReason("用户申请退款");
|
||||||
|
|
||||||
|
// 退款金额:DB 与 customAmount 均以"分"存储,支付宝 SDK refund_amount 需要"元"
|
||||||
|
String refundAmountFen = customAmount != null ? customAmount : order.getOrderAmount();
|
||||||
|
String refundAmount = StringUtils.fenToYuanAmount(refundAmountFen);
|
||||||
|
req.setRefundAmount(refundAmount);
|
||||||
|
|
||||||
|
com.alipay.api.response.AlipayTradeRefundResponse response = alipayRefundService.refund(config, req);
|
||||||
|
|
||||||
|
if (!response.isSuccess()) {
|
||||||
|
log.error("支付宝退款失败, subCode: {}, subMsg: {}", response.getSubCode(), response.getSubMsg());
|
||||||
|
throw new RuntimeException("支付宝退款失败: " + response.getSubMsg());
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("支付宝退款成功,订单号: {}, 退款金额: {}, fundChange: {}",
|
||||||
|
order.getOrderNo(), refundAmount, response.getFundChange());
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("支付宝退款请求失败,订单号: {}, 异常: {}", order.getOrderNo(), e.getMessage(), e);
|
||||||
|
throw new RuntimeException("支付宝退款失败: " + e.getMessage(), e);
|
||||||
|
} finally {
|
||||||
|
TenantContextHolder.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 微信退款申请
|
* 微信退款申请
|
||||||
* @param order
|
* @param order
|
||||||
|
|||||||
+3
@@ -4,6 +4,7 @@ import com.central.common.context.TenantContextHolder;
|
|||||||
import com.central.common.feign.UserService;
|
import com.central.common.feign.UserService;
|
||||||
import com.central.common.model.SysUser;
|
import com.central.common.model.SysUser;
|
||||||
import com.central.order.enums.OrderStatus;
|
import com.central.order.enums.OrderStatus;
|
||||||
|
import com.central.order.enums.PayTypeEnum;
|
||||||
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.QrCode;
|
import com.central.order.model.QrCode;
|
||||||
@@ -158,6 +159,7 @@ public class WxPayController {
|
|||||||
|
|
||||||
// 2. 更新订单状态
|
// 2. 更新订单状态
|
||||||
order.setOrderStatus(OrderStatus.PAID.getId());
|
order.setOrderStatus(OrderStatus.PAID.getId());
|
||||||
|
order.setPayType(PayTypeEnum.WECHAT_PAY.getCode());
|
||||||
order.setPayTime(new Date());
|
order.setPayTime(new Date());
|
||||||
orderService.updateOrder(order);
|
orderService.updateOrder(order);
|
||||||
|
|
||||||
@@ -220,6 +222,7 @@ public class WxPayController {
|
|||||||
|
|
||||||
// 2. 更新订单状态
|
// 2. 更新订单状态
|
||||||
order.setOrderStatus(OrderStatus.PAID.getId());
|
order.setOrderStatus(OrderStatus.PAID.getId());
|
||||||
|
order.setPayType(PayTypeEnum.WECHAT_PAY.getCode());
|
||||||
order.setPayTime(new Date());
|
order.setPayTime(new Date());
|
||||||
orderService.updateOrder(order);
|
orderService.updateOrder(order);
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,17 @@ public enum PayTypeEnum {
|
|||||||
/**
|
/**
|
||||||
* 优惠券支付
|
* 优惠券支付
|
||||||
*/
|
*/
|
||||||
COUPON_PAY(2, "优惠券支付");
|
COUPON_PAY(2, "优惠券支付"),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 第三方聚到核销(补齐遗留常量)
|
||||||
|
*/
|
||||||
|
FEIPAI_VERIFY(3, "第三方聚到核销"),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝支付(本期新增)
|
||||||
|
*/
|
||||||
|
ALIPAY_PAY(4, "支付宝支付");
|
||||||
|
|
||||||
private final Integer code;
|
private final Integer code;
|
||||||
private final String desc;
|
private final String desc;
|
||||||
|
|||||||
+8
@@ -4,8 +4,10 @@ import com.central.common.constant.ServiceNameConstants;
|
|||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.order.feign.fallback.CouponCenterServiceFallbackFactory;
|
import com.central.order.feign.fallback.CouponCenterServiceFallbackFactory;
|
||||||
import org.springframework.cloud.openfeign.FeignClient;
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -17,4 +19,10 @@ public interface CouponCenterService {
|
|||||||
*/
|
*/
|
||||||
@PostMapping("/ctrip/dist/order/create")
|
@PostMapping("/ctrip/dist/order/create")
|
||||||
Result<String> createCtripDistOrder(@RequestBody Map<String, Object> params);
|
Result<String> createCtripDistOrder(@RequestBody Map<String, Object> params);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 退订携程分销订单
|
||||||
|
*/
|
||||||
|
@PostMapping("/ctrip/dist/order/cancel/{orderNo}")
|
||||||
|
Result<String> cancelCtripDistOrder(@PathVariable("orderNo") String orderNo, @RequestParam("reason") String reason);
|
||||||
}
|
}
|
||||||
|
|||||||
+27
@@ -8,6 +8,8 @@ import com.central.order.model.dto.AgeDeviceLocationDTO;
|
|||||||
import com.central.order.model.dto.BoatRealtimePositionDTO;
|
import com.central.order.model.dto.BoatRealtimePositionDTO;
|
||||||
import com.central.order.model.dto.DroneLatestTrackPointDTO;
|
import com.central.order.model.dto.DroneLatestTrackPointDTO;
|
||||||
import com.central.order.mission.VO.TakeoffRequestVO;
|
import com.central.order.mission.VO.TakeoffRequestVO;
|
||||||
|
import com.central.order.mission.VO.FlyToPointRequestVO;
|
||||||
|
import com.central.order.mission.VO.FlyToPointUpdateRequestVO;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import org.springframework.cloud.openfeign.FeignClient;
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
@@ -39,6 +41,10 @@ public interface DeviceCenterService {
|
|||||||
@PostMapping("/device/command/takeoff")
|
@PostMapping("/device/command/takeoff")
|
||||||
Result<String> takeoff(@RequestBody TakeoffRequestVO request);
|
Result<String> takeoff(@RequestBody TakeoffRequestVO request);
|
||||||
|
|
||||||
|
@Operation(summary = "无人机返航")
|
||||||
|
@PostMapping("/device/command/return")
|
||||||
|
Result<String> returnHome(@RequestParam("deviceSn") String deviceSn);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 执行航线任务
|
* 执行航线任务
|
||||||
*
|
*
|
||||||
@@ -133,4 +139,25 @@ public interface DeviceCenterService {
|
|||||||
@Operation(summary = "获取无人机最新轨迹点")
|
@Operation(summary = "获取无人机最新轨迹点")
|
||||||
@GetMapping("/api/device/drone/track/latest/{deviceSn}")
|
@GetMapping("/api/device/drone/track/latest/{deviceSn}")
|
||||||
Result<DroneLatestTrackPointDTO> getDroneLatestTrackPoint(@PathVariable("deviceSn") String deviceSn);
|
Result<DroneLatestTrackPointDTO> getDroneLatestTrackPoint(@PathVariable("deviceSn") String deviceSn);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行 - 首次飞向目标点
|
||||||
|
*/
|
||||||
|
@Operation(summary = "无人机指点飞行 - 飞向目标")
|
||||||
|
@PostMapping("/device/command/flyToPoint")
|
||||||
|
Result<String> flyToPoint(@RequestBody FlyToPointRequestVO request);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行 - 更新目标点(连续指点)
|
||||||
|
*/
|
||||||
|
@Operation(summary = "无人机指点飞行 - 更新目标点")
|
||||||
|
@PostMapping("/device/command/flyToPointUpdate")
|
||||||
|
Result<String> flyToPointUpdate(@RequestBody FlyToPointUpdateRequestVO request);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行 - 停止指点飞行
|
||||||
|
*/
|
||||||
|
@Operation(summary = "无人机指点飞行 - 停止")
|
||||||
|
@PostMapping("/device/command/flyToPointStop")
|
||||||
|
Result<String> flyToPointStop(@RequestParam("deviceSn") String deviceSn);
|
||||||
}
|
}
|
||||||
|
|||||||
+14
@@ -36,6 +36,20 @@ public interface FileCenterService {
|
|||||||
@GetMapping("/qrcode/{codeId}")
|
@GetMapping("/qrcode/{codeId}")
|
||||||
Result<Map> uploadQrCodeFile(@PathVariable("codeId") String codeId) throws Exception;
|
Result<Map> uploadQrCodeFile(@PathVariable("codeId") String codeId) throws Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 拉取外部图片 URL 字节并强制入 S3(用于支付宝小程序二维码)
|
||||||
|
*/
|
||||||
|
@GetMapping("/qrcode/s3/by-url")
|
||||||
|
Result<Map> uploadQrCodeToS3ByUrl(@RequestParam("codeId") String codeId,
|
||||||
|
@RequestParam("qrUrl") String qrUrl,
|
||||||
|
@RequestParam(value = "suffix", required = false, defaultValue = "png") String suffix) throws Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 强制返回 S3 预签名 URL(绕开智能路由)
|
||||||
|
*/
|
||||||
|
@GetMapping("/files/s3/path")
|
||||||
|
String getS3ViewUrlByPath(@RequestParam("path") String path);
|
||||||
|
|
||||||
@PostMapping("/path")
|
@PostMapping("/path")
|
||||||
FileInfo creatFileInfo(@RequestBody String path);
|
FileInfo creatFileInfo(@RequestBody String path);
|
||||||
|
|
||||||
|
|||||||
+6
@@ -20,6 +20,12 @@ public class CouponCenterServiceFallbackFactory implements FallbackFactory<Coupo
|
|||||||
log.error("调用coupon-center创建携程分销订单失败,params: {}", params, cause);
|
log.error("调用coupon-center创建携程分销订单失败,params: {}", params, cause);
|
||||||
return Result.failed("调用coupon-center失败: " + cause.getMessage());
|
return Result.failed("调用coupon-center失败: " + cause.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> cancelCtripDistOrder(String orderNo, String reason) {
|
||||||
|
log.error("调用coupon-center退订携程分销订单失败,orderNo: {}, reason: {}", orderNo, reason, cause);
|
||||||
|
return Result.failed("调用coupon-center退订失败: " + cause.getMessage());
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+26
@@ -7,6 +7,8 @@ import com.central.order.model.dto.AgeDeviceLocationDTO;
|
|||||||
import com.central.order.model.dto.BoatRealtimePositionDTO;
|
import com.central.order.model.dto.BoatRealtimePositionDTO;
|
||||||
import com.central.order.model.dto.DroneLatestTrackPointDTO;
|
import com.central.order.model.dto.DroneLatestTrackPointDTO;
|
||||||
import com.central.order.mission.VO.TakeoffRequestVO;
|
import com.central.order.mission.VO.TakeoffRequestVO;
|
||||||
|
import com.central.order.mission.VO.FlyToPointRequestVO;
|
||||||
|
import com.central.order.mission.VO.FlyToPointUpdateRequestVO;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.cloud.openfeign.FallbackFactory;
|
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
@@ -43,6 +45,12 @@ public class DeviceCenterServiceFallbackFactory implements FallbackFactory<Devic
|
|||||||
return Result.failed("设备中心服务调用失败");
|
return Result.failed("设备中心服务调用失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> returnHome(String deviceSn) {
|
||||||
|
log.error("调用设备中心returnHome失败: deviceSn={}, error={}", deviceSn, cause.getMessage());
|
||||||
|
return Result.failed("设备中心服务调用失败");
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Result<String> executeWayline(String deviceSn, String waylineId, String missionCode) {
|
public Result<String> executeWayline(String deviceSn, String waylineId, String missionCode) {
|
||||||
log.error("调用设备中心executeWayline失败: deviceSn={}, waylineId={}, missionCode={}, error={}",
|
log.error("调用设备中心executeWayline失败: deviceSn={}, waylineId={}, missionCode={}, error={}",
|
||||||
@@ -98,6 +106,24 @@ public class DeviceCenterServiceFallbackFactory implements FallbackFactory<Devic
|
|||||||
log.error("调用设备中心getDroneLatestTrackPoint失败: deviceSn={}, error={}", deviceSn, cause.getMessage());
|
log.error("调用设备中心getDroneLatestTrackPoint失败: deviceSn={}, error={}", deviceSn, cause.getMessage());
|
||||||
return Result.failed("设备中心服务调用失败");
|
return Result.failed("设备中心服务调用失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> flyToPoint(FlyToPointRequestVO request) {
|
||||||
|
log.error("调用设备中心flyToPoint失败: deviceSn={}, error={}", request.getDeviceSn(), cause.getMessage());
|
||||||
|
return Result.failed("设备中心服务调用失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> flyToPointUpdate(FlyToPointUpdateRequestVO request) {
|
||||||
|
log.error("调用设备中心flyToPointUpdate失败: deviceSn={}, error={}", request.getDeviceSn(), cause.getMessage());
|
||||||
|
return Result.failed("设备中心服务调用失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> flyToPointStop(String deviceSn) {
|
||||||
|
log.error("调用设备中心flyToPointStop失败: deviceSn={}, error={}", deviceSn, cause.getMessage());
|
||||||
|
return Result.failed("设备中心服务调用失败");
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+11
@@ -41,6 +41,17 @@ public class FileCenterServiceFallbackFactory implements FallbackFactory<FileCen
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Map> uploadQrCodeToS3ByUrl(String codeId, String qrUrl, String suffix) throws Exception {
|
||||||
|
log.warn("file-center 调用失败,支付宝二维码上传降级返回 null, codeId={}", codeId, cause);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getS3ViewUrlByPath(String path) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public FileInfo creatFileInfo(String path) {
|
public FileInfo creatFileInfo(String path) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
+75
-87
@@ -11,6 +11,7 @@ import com.central.order.model.Message;
|
|||||||
import com.central.order.model.Order;
|
import com.central.order.model.Order;
|
||||||
import com.central.order.model.QrCode;
|
import com.central.order.model.QrCode;
|
||||||
import com.central.order.model.Tourism;
|
import com.central.order.model.Tourism;
|
||||||
|
import com.central.order.enums.PayTypeEnum;
|
||||||
import com.central.order.service.*;
|
import com.central.order.service.*;
|
||||||
import com.central.order.service.impl.FeipaiNotifyServiceImpl;
|
import com.central.order.service.impl.FeipaiNotifyServiceImpl;
|
||||||
import com.central.order.util.DateUtils;
|
import com.central.order.util.DateUtils;
|
||||||
@@ -42,6 +43,8 @@ public class OrderStatusChangeListener {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private WxMiniSubscribeService wxMiniSubscribeService;
|
private WxMiniSubscribeService wxMiniSubscribeService;
|
||||||
@Autowired
|
@Autowired
|
||||||
|
private AlipayMiniSubscribeService alipayMiniSubscribeService;
|
||||||
|
@Autowired
|
||||||
private FeipaiNotifyServiceImpl feipaiNotifyService;
|
private FeipaiNotifyServiceImpl feipaiNotifyService;
|
||||||
|
|
||||||
@EventListener
|
@EventListener
|
||||||
@@ -164,27 +167,15 @@ public class OrderStatusChangeListener {
|
|||||||
|
|
||||||
private void handlePaymentSuccess(Order order, Tourism tourism) {
|
private void handlePaymentSuccess(Order order, Tourism tourism) {
|
||||||
try {
|
try {
|
||||||
// 1. 发送微信通知
|
// 1. 查询订单排队信息
|
||||||
|
|
||||||
SysUser sysUser = userCenterService.findUserById(order.getUserId());
|
|
||||||
// 2. 查询订单排队信息
|
|
||||||
Integer queue = orderService.getOrderRankingByOrderIdAndDevice(order.getId(), order.getDeviceSn());
|
Integer queue = orderService.getOrderRankingByOrderIdAndDevice(order.getId(), order.getDeviceSn());
|
||||||
|
|
||||||
// 发送小程序订阅消息
|
|
||||||
if (sysUser.getOpenId() != null) {
|
|
||||||
String tip = "支付成功,当前排第"+queue+"位";
|
|
||||||
String orderName = tourism.getTourismName();
|
String orderName = tourism.getTourismName();
|
||||||
String pageUrl = "pages/task/task";
|
String pageUrl = "pages/task/task";
|
||||||
wxMiniSubscribeService.sendServiceProcessMsg(
|
String tip = "支付成功,当前排第" + queue + "位";
|
||||||
sysUser.getOpenId(),
|
String orderTime = DateUtils.sdf.format(order.getPayTime());
|
||||||
orderName,
|
|
||||||
tip,
|
// 根据 payType 发送小程序通知(微信 or 支付宝)
|
||||||
order.getOrderNo(),
|
sendSubscribeMsgByPayType(order, orderName, tip, order.getOrderNo(), orderTime, pageUrl);
|
||||||
DateUtils.sdf.format(order.getPayTime()),
|
|
||||||
"",
|
|
||||||
pageUrl
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 记录支付成功日志
|
// 2. 记录支付成功日志
|
||||||
log.info("订单支付成功: orderNo={}, amount={}, tourismName={}",
|
log.info("订单支付成功: orderNo={}, amount={}, tourismName={}",
|
||||||
@@ -231,108 +222,74 @@ public class OrderStatusChangeListener {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 退款申请成功(退款中)通知
|
* 退款申请成功(退款中)通知
|
||||||
* @param order
|
|
||||||
* @param tourism
|
|
||||||
*/
|
*/
|
||||||
private void sendMessageForRefunding(Order order, Tourism tourism) {
|
private void sendMessageForRefunding(Order order, Tourism tourism) {
|
||||||
// 发送小程序订阅消息,用户素材上传完成
|
try {
|
||||||
SysUser sysUser = userCenterService.findUserById(order.getUserId());
|
|
||||||
|
|
||||||
if (sysUser.getOpenId() != null) {
|
|
||||||
|
|
||||||
String tip = "您的订单正在退款中";
|
|
||||||
String orderName = tourism.getTourismName();
|
String orderName = tourism.getTourismName();
|
||||||
String pageUrl = "pages/task/task";
|
String pageUrl = "pages/task/task";
|
||||||
wxMiniSubscribeService.sendServiceProcessMsg(
|
String orderTime = DateUtils.sdf.format(order.getPayTime());
|
||||||
sysUser.getOpenId(),
|
|
||||||
orderName,
|
sendSubscribeMsgByPayType(order, orderName, "您的订单正在退款中",
|
||||||
tip,
|
order.getOrderNo(), orderTime, pageUrl);
|
||||||
order.getOrderNo(),
|
} catch (Exception e) {
|
||||||
DateUtils.sdf.format(order.getPayTime()),
|
log.error("退款中通知发送失败,不影响主流程: orderNo={}", order.getOrderNo(), e);
|
||||||
"",
|
|
||||||
pageUrl
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 退款完成通知
|
* 退款完成通知
|
||||||
* @param order
|
|
||||||
* @param tourism
|
|
||||||
*/
|
*/
|
||||||
private void sendMessageForRefunded(Order order, Tourism tourism) {
|
private void sendMessageForRefunded(Order order, Tourism tourism) {
|
||||||
// 发送小程序订阅消息,用户素材上传完成
|
try {
|
||||||
SysUser sysUser = userCenterService.findUserById(order.getUserId());
|
|
||||||
|
|
||||||
if (sysUser.getOpenId() != null) {
|
|
||||||
|
|
||||||
String tip = "您的订单退款已完成";
|
|
||||||
String orderName = tourism.getTourismName();
|
String orderName = tourism.getTourismName();
|
||||||
String pageUrl = "pages/task/task";
|
String pageUrl = "pages/task/task";
|
||||||
wxMiniSubscribeService.sendServiceProcessMsg(
|
String orderTime = DateUtils.sdf.format(order.getPayTime());
|
||||||
sysUser.getOpenId(),
|
|
||||||
orderName,
|
sendSubscribeMsgByPayType(order, orderName, "您的订单退款已完成",
|
||||||
tip,
|
order.getOrderNo(), orderTime, pageUrl);
|
||||||
order.getOrderNo(),
|
} catch (Exception e) {
|
||||||
DateUtils.sdf.format(order.getPayTime()),
|
log.error("退款完成通知发送失败,不影响主流程: orderNo={}", order.getOrderNo(), e);
|
||||||
"",
|
|
||||||
pageUrl
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 素材上传完成小程序通知
|
* 素材上传完成小程序通知
|
||||||
* @param order
|
|
||||||
* @param tourism
|
|
||||||
*/
|
*/
|
||||||
private void sendMessageForResouresUploaded(Order order, Tourism tourism) {
|
private void sendMessageForResouresUploaded(Order order, Tourism tourism) {
|
||||||
// 发送小程序订阅消息,用户素材上传完成
|
try {
|
||||||
SysUser sysUser = userCenterService.findUserById(order.getUserId());
|
|
||||||
|
|
||||||
if (sysUser.getOpenId() != null) {
|
|
||||||
|
|
||||||
String tip = "素材上传完成";
|
|
||||||
String orderName = tourism.getTourismName();
|
String orderName = tourism.getTourismName();
|
||||||
String pageUrl = "pages/album/album";
|
String pageUrl = "pages/album/album";
|
||||||
wxMiniSubscribeService.sendServiceProcessMsg(
|
String orderTime = "";
|
||||||
sysUser.getOpenId(),
|
if (order.getPayTime() != null) {
|
||||||
orderName,
|
orderTime = DateUtils.sdf.format(order.getPayTime());
|
||||||
tip,
|
}
|
||||||
order.getOrderNo(),
|
|
||||||
DateUtils.sdf.format(order.getPayTime()),
|
sendSubscribeMsgByPayType(order, orderName, "素材上传完成",
|
||||||
"",
|
order.getOrderNo(), orderTime, pageUrl);
|
||||||
pageUrl
|
} catch (Exception e) {
|
||||||
);
|
log.error("素材上传通知发送失败,不影响主流程: orderNo={}", order.getOrderNo(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 订单完成后通知下一位用户
|
* 订单完成后通知下一位用户
|
||||||
* @param order
|
|
||||||
* @param tourism
|
|
||||||
*/
|
*/
|
||||||
private void sendMessageToNextOrderUser(Order order, Tourism tourism) {
|
private void sendMessageToNextOrderUser(Order order, Tourism tourism) {
|
||||||
// 新增:查找下一个排队用户
|
try {
|
||||||
Order nextOrder = orderService.getNextQueueOrder(order.getTourismId(), order.getId());
|
Order nextOrder = orderService.getNextQueueOrder(order.getTourismId(), order.getId());
|
||||||
if (nextOrder != null) {
|
if (nextOrder != null && tourism != null) {
|
||||||
SysUser nextUser = userCenterService.findUserById(nextOrder.getUserId());
|
String activityName = tourism.getTourismName();
|
||||||
if (nextUser != null && nextUser.getOpenId() != null && tourism != null) {
|
|
||||||
String activityName = tourism.getTourismName(); // 活动名称
|
|
||||||
String remark = "即将为您进行拍摄服务";
|
String remark = "即将为您进行拍摄服务";
|
||||||
String activityNo = nextOrder.getOrderNo(); // 活动编号
|
String activityNo = nextOrder.getOrderNo();
|
||||||
String pageUrl = "pages/album/album";
|
String pageUrl = "pages/album/album";
|
||||||
wxMiniSubscribeService.sendServiceProcessMsg(
|
String orderTime = DateUtils.sdf.format(nextOrder.getPayTime());
|
||||||
nextUser.getOpenId(),
|
|
||||||
activityName,
|
sendSubscribeMsgByPayType(nextOrder, activityName, remark,
|
||||||
remark,
|
activityNo, orderTime, pageUrl);
|
||||||
activityNo,
|
log.info("已通知下一个排队用户: userId={}, orderNo={}", nextOrder.getUserId(), activityNo);
|
||||||
DateUtils.sdf.format(nextOrder.getPayTime()),
|
|
||||||
"",
|
|
||||||
pageUrl
|
|
||||||
);
|
|
||||||
log.info("已通知下一个排队用户: userId={}, openId={}, orderNo={}", nextUser.getId(), nextUser.getOpenId(), activityNo);
|
|
||||||
}
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("通知下一位排队用户失败,不影响主流程: orderNo={}", order.getOrderNo(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -345,4 +302,35 @@ public class OrderStatusChangeListener {
|
|||||||
&& qrCode.getEnableVideoEdit() == 1
|
&& qrCode.getEnableVideoEdit() == 1
|
||||||
&& qrCode.getTemplateId() != null; // 确保有模板ID
|
&& 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(核销) 不发送小程序通知
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
package com.central.order.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import com.central.db.mapper.SuperMapper;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝配置 Mapper
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface AlipayConfigMapper extends SuperMapper<AlipayConfig> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询(支持按 type / tenantId / appId / status 筛选)
|
||||||
|
*/
|
||||||
|
List<AlipayConfig> findList(Page<AlipayConfig> page, @Param("p") Map<String, Object> params);
|
||||||
|
}
|
||||||
@@ -45,6 +45,10 @@ public interface OrderMapper extends SuperMapper<Order> {
|
|||||||
// 根据订单编号查询订单信息
|
// 根据订单编号查询订单信息
|
||||||
Order getOrderByNumber(@Param("orderNumber") String orderNumber);
|
Order getOrderByNumber(@Param("orderNumber") String orderNumber);
|
||||||
|
|
||||||
|
// 根据订单编号+租户ID查询订单信息(用于支付/退款回调严格隔离)
|
||||||
|
Order getOrderByNumberAndTenant(@Param("orderNumber") String orderNumber,
|
||||||
|
@Param("tenantId") String tenantId);
|
||||||
|
|
||||||
List<Order> findListByUser(Page<Order> page, @Param("p") Map<String, Object> params);
|
List<Order> findListByUser(Page<Order> page, @Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
@Select("SELECT \n" +
|
@Select("SELECT \n" +
|
||||||
|
|||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
package com.central.order.mission.VO;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行(首次飞向目标)Feign 请求 VO
|
||||||
|
*
|
||||||
|
* @author dzc
|
||||||
|
* @date 2026-01-23
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class FlyToPointRequestVO {
|
||||||
|
/** 设备SN */
|
||||||
|
private String deviceSn;
|
||||||
|
/** 飞行会话ID(= missionCode) */
|
||||||
|
private String flyToId;
|
||||||
|
/** 目标纬度 */
|
||||||
|
private Double latitude;
|
||||||
|
/** 目标经度 */
|
||||||
|
private Double longitude;
|
||||||
|
/** 目标椭球高 */
|
||||||
|
private Float height;
|
||||||
|
/** 最大飞行速度(m/s),默认 12 */
|
||||||
|
private Float maxSpeed;
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
package com.central.order.mission.VO;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行更新目标(连续指点)Feign 请求 VO
|
||||||
|
* 注意:设备协议不含 fly_to_id,仅传 max_speed + points
|
||||||
|
*
|
||||||
|
* @author dzc
|
||||||
|
* @date 2026-01-23
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class FlyToPointUpdateRequestVO {
|
||||||
|
/** 设备SN */
|
||||||
|
private String deviceSn;
|
||||||
|
/** 目标纬度 */
|
||||||
|
private Double latitude;
|
||||||
|
/** 目标经度 */
|
||||||
|
private Double longitude;
|
||||||
|
/** 目标椭球高 */
|
||||||
|
private Float height;
|
||||||
|
/** 最大飞行速度(m/s),默认 12 */
|
||||||
|
private Float maxSpeed;
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package com.central.order.mission.command;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行目标下发参数。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class FlyToPointTargetCommand {
|
||||||
|
|
||||||
|
private Double latitude;
|
||||||
|
private Double longitude;
|
||||||
|
private Float height;
|
||||||
|
private Float maxSpeed;
|
||||||
|
private String clearanceStatus;
|
||||||
|
private Float clearanceMeters;
|
||||||
|
private Float candidateSurfaceHeight;
|
||||||
|
private boolean riskAcknowledged;
|
||||||
|
private String riskReason;
|
||||||
|
private Long riskAcknowledgedUserId;
|
||||||
|
private String riskAcknowledgedUsername;
|
||||||
|
|
||||||
|
public void validateRiskAcknowledgement() {
|
||||||
|
if (!"VERIFIED".equals(clearanceStatus) && !riskAcknowledged) {
|
||||||
|
throw new IllegalArgumentException("路径净空未验证,请确认风险后再发送目标");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
package com.central.order.mission.command;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行目标更新接口请求。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class FlyToPointUpdateRequest {
|
||||||
|
private String missionCode;
|
||||||
|
private Double latitude;
|
||||||
|
private Double longitude;
|
||||||
|
private Float height;
|
||||||
|
private Float maxSpeed;
|
||||||
|
private String clearanceStatus;
|
||||||
|
private Float clearanceMeters;
|
||||||
|
private Float candidateSurfaceHeight;
|
||||||
|
private Boolean riskAcknowledged;
|
||||||
|
private String riskReason;
|
||||||
|
|
||||||
|
public FlyToPointTargetCommand toCommand() {
|
||||||
|
return FlyToPointTargetCommand.builder()
|
||||||
|
.latitude(latitude)
|
||||||
|
.longitude(longitude)
|
||||||
|
.height(height)
|
||||||
|
.maxSpeed(maxSpeed == null ? 12f : maxSpeed)
|
||||||
|
.clearanceStatus(clearanceStatus == null ? "UNVERIFIED" : clearanceStatus)
|
||||||
|
.clearanceMeters(clearanceMeters)
|
||||||
|
.candidateSurfaceHeight(candidateSurfaceHeight)
|
||||||
|
.riskAcknowledged(Boolean.TRUE.equals(riskAcknowledged))
|
||||||
|
.riskReason(riskReason)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
+111
@@ -8,6 +8,8 @@ import com.central.common.model.Result;
|
|||||||
import com.central.order.feign.FileCenterService;
|
import com.central.order.feign.FileCenterService;
|
||||||
import com.central.order.mission.enums.MissionStatus;
|
import com.central.order.mission.enums.MissionStatus;
|
||||||
import com.central.order.mission.enums.MissionType;
|
import com.central.order.mission.enums.MissionType;
|
||||||
|
import com.central.order.mission.command.FlyToPointTargetCommand;
|
||||||
|
import com.central.order.mission.command.FlyToPointUpdateRequest;
|
||||||
import com.central.order.mission.model.Mission;
|
import com.central.order.mission.model.Mission;
|
||||||
import com.central.order.mission.model.MissionImage;
|
import com.central.order.mission.model.MissionImage;
|
||||||
import com.central.order.mission.service.IMissionImageService;
|
import com.central.order.mission.service.IMissionImageService;
|
||||||
@@ -279,6 +281,115 @@ public class MissionController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 指点飞行编排接口 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开始指点飞行
|
||||||
|
*/
|
||||||
|
@Operation(summary = "开始指点飞行")
|
||||||
|
@PostMapping("/startFlyToPoint")
|
||||||
|
public Result<Map<String, Object>> startFlyToPoint(@RequestBody Map<String, Object> params) {
|
||||||
|
try {
|
||||||
|
TenantContextHolder.setTenant("webApp");
|
||||||
|
|
||||||
|
String deviceSn = (String) params.get("deviceSn");
|
||||||
|
if (!StringUtils.hasText(deviceSn)) {
|
||||||
|
return Result.failed("设备SN不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
Double dockLatitude = params.get("dockLatitude") != null ?
|
||||||
|
Double.parseDouble(params.get("dockLatitude").toString()) : null;
|
||||||
|
Double dockLongitude = params.get("dockLongitude") != null ?
|
||||||
|
Double.parseDouble(params.get("dockLongitude").toString()) : null;
|
||||||
|
Float dockHeight = params.get("dockHeight") != null ?
|
||||||
|
Float.parseFloat(params.get("dockHeight").toString()) : null;
|
||||||
|
Boolean isAirborne = params.get("isAirborne") != null ?
|
||||||
|
(Boolean) params.get("isAirborne") : false;
|
||||||
|
|
||||||
|
String missionCode = missionService.startFlyToPoint(deviceSn, dockLatitude, dockLongitude, dockHeight, isAirborne);
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("missionCode", missionCode);
|
||||||
|
return Result.succeed(result, "指点飞行任务已开始");
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("开始指点飞行异常", e);
|
||||||
|
return Result.failed("开始指点飞行失败: " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
TenantContextHolder.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新指点飞行目标点
|
||||||
|
*/
|
||||||
|
@Operation(summary = "更新指点飞行目标点")
|
||||||
|
@PostMapping("/flyToPointUpdate")
|
||||||
|
public Result<String> flyToPointUpdate(@RequestBody FlyToPointUpdateRequest request) {
|
||||||
|
try {
|
||||||
|
TenantContextHolder.setTenant("webApp");
|
||||||
|
|
||||||
|
String missionCode = request.getMissionCode();
|
||||||
|
if (!StringUtils.hasText(missionCode)) {
|
||||||
|
return Result.failed("任务编码不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
FlyToPointTargetCommand command = request.toCommand();
|
||||||
|
// 第一版没有服务端路径净空验证能力,不能信任客户端声明“已验证”。
|
||||||
|
command.setClearanceStatus("UNVERIFIED");
|
||||||
|
|
||||||
|
if (command.getLatitude() == null || command.getLongitude() == null || command.getHeight() == null) {
|
||||||
|
return Result.failed("目标经纬度和高度不能为空");
|
||||||
|
}
|
||||||
|
if (command.getLatitude() < -90 || command.getLatitude() > 90
|
||||||
|
|| command.getLongitude() < -180 || command.getLongitude() > 180) {
|
||||||
|
return Result.failed("目标经纬度不合法");
|
||||||
|
}
|
||||||
|
|
||||||
|
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||||
|
if (user == null) {
|
||||||
|
return Result.failed("用户未登录,无法确认飞行风险");
|
||||||
|
}
|
||||||
|
command.setRiskAcknowledgedUserId(user.getId());
|
||||||
|
command.setRiskAcknowledgedUsername(user.getUsername());
|
||||||
|
command.validateRiskAcknowledgement();
|
||||||
|
|
||||||
|
missionService.flyToPointUpdate(missionCode, command);
|
||||||
|
return Result.succeed("目标点已更新");
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("更新指点飞行目标点异常", e);
|
||||||
|
return Result.failed("更新目标点失败: " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
TenantContextHolder.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 结束指点飞行
|
||||||
|
*/
|
||||||
|
@Operation(summary = "结束指点飞行")
|
||||||
|
@PostMapping("/endFlyToPoint")
|
||||||
|
public Result<String> endFlyToPoint(@RequestBody Map<String, Object> params) {
|
||||||
|
try {
|
||||||
|
TenantContextHolder.setTenant("webApp");
|
||||||
|
|
||||||
|
String missionCode = (String) params.get("missionCode");
|
||||||
|
if (!StringUtils.hasText(missionCode)) {
|
||||||
|
return Result.failed("任务编码不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
missionService.endFlyToPoint(missionCode);
|
||||||
|
return Result.succeed("指点飞行已结束,返航中");
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("结束指点飞行异常", e);
|
||||||
|
return Result.failed("结束指点飞行失败: " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
TenantContextHolder.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取当前登录人的任务及图片列表
|
* 获取当前登录人的任务及图片列表
|
||||||
*/
|
*/
|
||||||
|
|||||||
+9
-1
@@ -13,7 +13,8 @@ import lombok.Getter;
|
|||||||
public enum MissionType implements ZltEnum {
|
public enum MissionType implements ZltEnum {
|
||||||
WAYLINE(1, "航线任务"),
|
WAYLINE(1, "航线任务"),
|
||||||
TAKEOFF(2, "一键起飞任务"),
|
TAKEOFF(2, "一键起飞任务"),
|
||||||
BOAT_ROUTE(3, "无人船航线任务");
|
BOAT_ROUTE(3, "无人船航线任务"),
|
||||||
|
FLY_TO_POINT(4, "指点飞行任务");
|
||||||
|
|
||||||
MissionType(Integer id, String content) {
|
MissionType(Integer id, String content) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
@@ -58,4 +59,11 @@ public enum MissionType implements ZltEnum {
|
|||||||
public static boolean isBoatRouteTask(Integer type) {
|
public static boolean isBoatRouteTask(Integer type) {
|
||||||
return type != null && type.equals(BOAT_ROUTE.getId());
|
return type != null && type.equals(BOAT_ROUTE.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否为指点飞行任务
|
||||||
|
*/
|
||||||
|
public static boolean isFlyToPointTask(Integer type) {
|
||||||
|
return type != null && type.equals(FLY_TO_POINT.getId());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
package com.central.order.mission.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.central.order.mission.model.MissionFlyToPoint;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface MissionFlyToPointMapper extends BaseMapper<MissionFlyToPoint> {
|
||||||
|
}
|
||||||
+5
@@ -34,6 +34,11 @@ public interface MissionMapper extends BaseMapper<Mission> {
|
|||||||
*/
|
*/
|
||||||
Mission getByMissionCode(@Param("missionCode") String missionCode);
|
Mission getByMissionCode(@Param("missionCode") String missionCode);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 锁定任务行,串行化同一指点飞行会话的目标更新。
|
||||||
|
*/
|
||||||
|
Mission getByMissionCodeForUpdate(@Param("missionCode") String missionCode);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 更新任务状态
|
* 更新任务状态
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -108,4 +108,7 @@ public class Mission extends SuperEntity {
|
|||||||
@Schema(description = "任务状态描述")
|
@Schema(description = "任务状态描述")
|
||||||
@TableField(exist = false)
|
@TableField(exist = false)
|
||||||
private transient String missionStatusDesc;
|
private transient String missionStatusDesc;
|
||||||
|
|
||||||
|
@Schema(description = "会话阶段:ACTIVE / RETURNING")
|
||||||
|
private String phase;
|
||||||
}
|
}
|
||||||
|
|||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
package com.central.order.mission.model;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import com.central.common.model.SuperEntity;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指点飞行每次下发目标及风险确认审计记录。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = false)
|
||||||
|
@TableName("mission_fly_to_point")
|
||||||
|
public class MissionFlyToPoint extends SuperEntity {
|
||||||
|
private String missionCode;
|
||||||
|
private String flyToId;
|
||||||
|
private String commandId;
|
||||||
|
private Integer seq;
|
||||||
|
private String commandType;
|
||||||
|
private Double latitude;
|
||||||
|
private Double longitude;
|
||||||
|
private Float height;
|
||||||
|
private Float maxSpeed;
|
||||||
|
private String status;
|
||||||
|
private String clearanceStatus;
|
||||||
|
private Float clearanceMeters;
|
||||||
|
private Float candidateSurfaceHeight;
|
||||||
|
private Integer riskAcknowledged;
|
||||||
|
private String riskReason;
|
||||||
|
private Long riskAcknowledgedUserId;
|
||||||
|
private String riskAcknowledgedUsername;
|
||||||
|
}
|
||||||
+33
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
|
|||||||
import com.central.common.model.PageResult;
|
import com.central.common.model.PageResult;
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.order.mission.model.Mission;
|
import com.central.order.mission.model.Mission;
|
||||||
|
import com.central.order.mission.command.FlyToPointTargetCommand;
|
||||||
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -96,4 +97,36 @@ public interface IMissionService extends IService<Mission> {
|
|||||||
* @return 下发成功返回true
|
* @return 下发成功返回true
|
||||||
*/
|
*/
|
||||||
boolean dispatchMissionToDevice(Mission mission);
|
boolean dispatchMissionToDevice(Mission mission);
|
||||||
|
|
||||||
|
// ==================== 指点飞行编排接口 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开始指点飞行
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
* @param dockLatitude 机库纬度
|
||||||
|
* @param dockLongitude 机库经度
|
||||||
|
* @param dockHeight 机库高度
|
||||||
|
* @param isAirborne 是否已升空(前端 SSE 判断)
|
||||||
|
* @return 任务编码
|
||||||
|
*/
|
||||||
|
String startFlyToPoint(String deviceSn, Double dockLatitude, Double dockLongitude, Float dockHeight, boolean isAirborne);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新指点飞行目标点
|
||||||
|
*
|
||||||
|
* @param missionCode 任务编码
|
||||||
|
* @param latitude 目标纬度
|
||||||
|
* @param longitude 目标经度
|
||||||
|
* @param height 目标椭球高
|
||||||
|
* @param maxSpeed 最大速度
|
||||||
|
*/
|
||||||
|
void flyToPointUpdate(String missionCode, FlyToPointTargetCommand command);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 结束指点飞行
|
||||||
|
*
|
||||||
|
* @param missionCode 任务编码
|
||||||
|
*/
|
||||||
|
void endFlyToPoint(String missionCode);
|
||||||
}
|
}
|
||||||
|
|||||||
+225
@@ -6,10 +6,14 @@ import com.central.common.model.PageResult;
|
|||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.order.feign.DeviceCenterService;
|
import com.central.order.feign.DeviceCenterService;
|
||||||
import com.central.order.mission.VO.TakeoffRequestVO;
|
import com.central.order.mission.VO.TakeoffRequestVO;
|
||||||
|
import com.central.order.mission.VO.FlyToPointRequestVO;
|
||||||
|
import com.central.order.mission.command.FlyToPointTargetCommand;
|
||||||
import com.central.order.mission.enums.MissionStatus;
|
import com.central.order.mission.enums.MissionStatus;
|
||||||
import com.central.order.mission.enums.MissionType;
|
import com.central.order.mission.enums.MissionType;
|
||||||
import com.central.order.mission.mapper.MissionMapper;
|
import com.central.order.mission.mapper.MissionMapper;
|
||||||
|
import com.central.order.mission.mapper.MissionFlyToPointMapper;
|
||||||
import com.central.order.mission.model.Mission;
|
import com.central.order.mission.model.Mission;
|
||||||
|
import com.central.order.mission.model.MissionFlyToPoint;
|
||||||
import com.central.order.mission.service.IMissionService;
|
import com.central.order.mission.service.IMissionService;
|
||||||
import com.central.order.weather.model.WeatherCheckResult;
|
import com.central.order.weather.model.WeatherCheckResult;
|
||||||
import com.central.order.weather.service.IWeatherRuleValidator;
|
import com.central.order.weather.service.IWeatherRuleValidator;
|
||||||
@@ -38,6 +42,9 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
|
|||||||
@Resource
|
@Resource
|
||||||
DeviceCenterService deviceCenterService;
|
DeviceCenterService deviceCenterService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
MissionFlyToPointMapper missionFlyToPointMapper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IWeatherRuleValidator weatherRuleValidator;
|
private IWeatherRuleValidator weatherRuleValidator;
|
||||||
|
|
||||||
@@ -249,6 +256,13 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean dispatchMissionToDevice(Mission mission) {
|
public boolean dispatchMissionToDevice(Mission mission) {
|
||||||
|
return dispatchMissionToDevice(mission, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 下发任务到设备(带升空状态)
|
||||||
|
*/
|
||||||
|
public boolean dispatchMissionToDevice(Mission mission, boolean isAirborne) {
|
||||||
try {
|
try {
|
||||||
Integer missionType = mission.getMissionType();
|
Integer missionType = mission.getMissionType();
|
||||||
|
|
||||||
@@ -311,6 +325,33 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
|
|||||||
log.error("无人船航线任务下发失败: missionCode={}, error={}", mission.getMissionCode(), errorMsg);
|
log.error("无人船航线任务下发失败: missionCode={}, error={}", mission.getMissionCode(), errorMsg);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
} else if (MissionType.isFlyToPointTask(missionType)) {
|
||||||
|
// 指点飞行任务:前端 SSE 判断是否已升空
|
||||||
|
log.info("下发指点飞行任务到设备: missionCode={}, deviceSn={}, isAirborne={}",
|
||||||
|
mission.getMissionCode(), mission.getDeviceSn(), isAirborne);
|
||||||
|
|
||||||
|
if (!isAirborne) {
|
||||||
|
// 未升空 → 先起飞
|
||||||
|
TakeoffRequestVO takeoffRequestVO = new TakeoffRequestVO();
|
||||||
|
takeoffRequestVO.setTargetHeight(mission.getTargetHeight() != null ? mission.getTargetHeight().floatValue() : 20f);
|
||||||
|
takeoffRequestVO.setDeviceSn(mission.getDeviceSn());
|
||||||
|
takeoffRequestVO.setFlightId(mission.getMissionCode());
|
||||||
|
takeoffRequestVO.setTargetLatitude(mission.getTargetLatitude() != null ? mission.getTargetLatitude().doubleValue() : 0d);
|
||||||
|
takeoffRequestVO.setTargetLongitude(mission.getTargetLongitude() != null ? mission.getTargetLongitude().doubleValue() : 0d);
|
||||||
|
Result<String> takeoffResult = deviceCenterService.takeoff(takeoffRequestVO);
|
||||||
|
if (takeoffResult == null || takeoffResult.getResp_code() != 0) {
|
||||||
|
log.error("指点飞行起飞命令失败: missionCode={}", mission.getMissionCode());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
log.info("指点飞行起飞命令已发送: missionCode={}", mission.getMissionCode());
|
||||||
|
} else {
|
||||||
|
log.info("无人机已升空,跳过起飞步骤: missionCode={}", mission.getMissionCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 命令入队成功 → 任务状态为 DOING
|
||||||
|
updateMissionStatus(mission.getMissionCode(), MissionStatus.DOING.getId());
|
||||||
|
return true;
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
log.error("未知的任务类型: {}", missionType);
|
log.error("未知的任务类型: {}", missionType);
|
||||||
return false;
|
return false;
|
||||||
@@ -321,4 +362,188 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 指点飞行编排方法 ====================
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public String startFlyToPoint(String deviceSn, Double dockLatitude, Double dockLongitude, Float dockHeight, boolean isAirborne) {
|
||||||
|
log.info("开始指点飞行: deviceSn={}, dock=({}, {}, {})", deviceSn, dockLatitude, dockLongitude, dockHeight);
|
||||||
|
|
||||||
|
// 1. 创建 FLY_TO_POINT 任务
|
||||||
|
Mission mission = new Mission();
|
||||||
|
mission.setDeviceSn(deviceSn);
|
||||||
|
mission.setMissionType(MissionType.FLY_TO_POINT.getId());
|
||||||
|
mission.setMissionName("指点飞行任务");
|
||||||
|
mission.setMissionStatus(MissionStatus.PENDING.getId());
|
||||||
|
mission.setTargetLatitude(dockLatitude != null ? java.math.BigDecimal.valueOf(dockLatitude) : null);
|
||||||
|
mission.setTargetLongitude(dockLongitude != null ? java.math.BigDecimal.valueOf(dockLongitude) : null);
|
||||||
|
mission.setTargetHeight(java.math.BigDecimal.valueOf(20));
|
||||||
|
mission.setPhase("ACTIVE");
|
||||||
|
|
||||||
|
String missionCode = generateMissionCode();
|
||||||
|
mission.setMissionCode(missionCode);
|
||||||
|
|
||||||
|
save(mission);
|
||||||
|
log.info("指点飞行任务已创建: missionCode={}", missionCode);
|
||||||
|
|
||||||
|
// 2. 执行任务(dispatchMissionToDevice 会处理起飞逻辑)
|
||||||
|
boolean dispatched = dispatchMissionToDevice(mission, isAirborne);
|
||||||
|
if (!dispatched) {
|
||||||
|
log.error("指点飞行任务下发失败: missionCode={}", missionCode);
|
||||||
|
throw new RuntimeException("任务下发失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
return missionCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void flyToPointUpdate(String missionCode, FlyToPointTargetCommand command) {
|
||||||
|
command.validateRiskAcknowledgement();
|
||||||
|
Double latitude = command.getLatitude();
|
||||||
|
Double longitude = command.getLongitude();
|
||||||
|
Float height = command.getHeight();
|
||||||
|
Float maxSpeed = command.getMaxSpeed();
|
||||||
|
log.info("更新指点飞行目标: missionCode={}, target=({}, {}, {})", missionCode, latitude, longitude, height);
|
||||||
|
|
||||||
|
Mission mission = baseMapper.getByMissionCodeForUpdate(missionCode);
|
||||||
|
if (mission == null) {
|
||||||
|
throw new RuntimeException("任务不存在: " + missionCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 校验状态
|
||||||
|
if (!MissionStatus.DOING.getId().equals(mission.getMissionStatus())) {
|
||||||
|
throw new RuntimeException("任务状态不允许更新目标: " + mission.getMissionStatus());
|
||||||
|
}
|
||||||
|
if (!"ACTIVE".equals(mission.getPhase())) {
|
||||||
|
throw new RuntimeException("飞行已结束,无法更新目标");
|
||||||
|
}
|
||||||
|
|
||||||
|
String deviceSn = mission.getDeviceSn();
|
||||||
|
|
||||||
|
// 判断是否首次指点:查询 mission_fly_to_point 子表
|
||||||
|
boolean isFirstTarget = !hasSentFirstFlyToPoint(missionCode);
|
||||||
|
|
||||||
|
Result<String> result;
|
||||||
|
String commandType;
|
||||||
|
if (isFirstTarget) {
|
||||||
|
FlyToPointRequestVO requestVO = new FlyToPointRequestVO();
|
||||||
|
requestVO.setDeviceSn(deviceSn);
|
||||||
|
requestVO.setFlyToId(missionCode);
|
||||||
|
requestVO.setLatitude(latitude);
|
||||||
|
requestVO.setLongitude(longitude);
|
||||||
|
requestVO.setHeight(height);
|
||||||
|
requestVO.setMaxSpeed(maxSpeed != null ? maxSpeed : 12f);
|
||||||
|
|
||||||
|
result = deviceCenterService.flyToPoint(requestVO);
|
||||||
|
if (result == null || result.getResp_code() != 0) {
|
||||||
|
throw new RuntimeException("指点飞行命令失败: " + (result != null ? result.getResp_msg() : "无响应"));
|
||||||
|
}
|
||||||
|
commandType = "fly_to_point";
|
||||||
|
log.info("首次指点飞行命令已发送: missionCode={}, commandId={}", missionCode, result.getData());
|
||||||
|
} else {
|
||||||
|
// 设备端不支持 fly_to_point_update,连续改飞复用 fly_to_point 并沿用同一会话标识。
|
||||||
|
FlyToPointRequestVO requestVO = new FlyToPointRequestVO();
|
||||||
|
requestVO.setDeviceSn(deviceSn);
|
||||||
|
requestVO.setFlyToId(missionCode);
|
||||||
|
requestVO.setLatitude(latitude);
|
||||||
|
requestVO.setLongitude(longitude);
|
||||||
|
requestVO.setHeight(height);
|
||||||
|
requestVO.setMaxSpeed(maxSpeed != null ? maxSpeed : 12f);
|
||||||
|
|
||||||
|
result = deviceCenterService.flyToPoint(requestVO);
|
||||||
|
if (result == null || result.getResp_code() != 0) {
|
||||||
|
throw new RuntimeException("目标更新命令失败: " + (result != null ? result.getResp_msg() : "无响应"));
|
||||||
|
}
|
||||||
|
commandType = "fly_to_point";
|
||||||
|
log.info("目标更新命令已发送: missionCode={}, commandId={}", missionCode, result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
MissionFlyToPoint record = new MissionFlyToPoint();
|
||||||
|
record.setMissionCode(missionCode);
|
||||||
|
record.setFlyToId(missionCode);
|
||||||
|
record.setCommandId(result.getData());
|
||||||
|
record.setSeq(nextTargetSequence(missionCode));
|
||||||
|
record.setCommandType(commandType);
|
||||||
|
record.setLatitude(latitude);
|
||||||
|
record.setLongitude(longitude);
|
||||||
|
record.setHeight(height);
|
||||||
|
record.setMaxSpeed(maxSpeed != null ? maxSpeed : 12f);
|
||||||
|
record.setStatus("SENT");
|
||||||
|
record.setClearanceStatus(command.getClearanceStatus());
|
||||||
|
record.setClearanceMeters(command.getClearanceMeters());
|
||||||
|
record.setCandidateSurfaceHeight(command.getCandidateSurfaceHeight());
|
||||||
|
record.setRiskAcknowledged(command.isRiskAcknowledged() ? 1 : 0);
|
||||||
|
record.setRiskReason(command.getRiskReason());
|
||||||
|
record.setRiskAcknowledgedUserId(command.getRiskAcknowledgedUserId());
|
||||||
|
record.setRiskAcknowledgedUsername(command.getRiskAcknowledgedUsername());
|
||||||
|
missionFlyToPointMapper.insert(record);
|
||||||
|
|
||||||
|
mission.setTargetLatitude(java.math.BigDecimal.valueOf(latitude));
|
||||||
|
mission.setTargetLongitude(java.math.BigDecimal.valueOf(longitude));
|
||||||
|
mission.setTargetHeight(java.math.BigDecimal.valueOf(height));
|
||||||
|
updateById(mission);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void endFlyToPoint(String missionCode) {
|
||||||
|
log.info("结束指点飞行: missionCode={}", missionCode);
|
||||||
|
|
||||||
|
Mission mission = baseMapper.getByMissionCodeForUpdate(missionCode);
|
||||||
|
if (mission == null) {
|
||||||
|
throw new RuntimeException("任务不存在: " + missionCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 校验状态
|
||||||
|
if (!MissionStatus.DOING.getId().equals(mission.getMissionStatus())) {
|
||||||
|
throw new RuntimeException("任务状态不允许结束: " + mission.getMissionStatus());
|
||||||
|
}
|
||||||
|
if (!"ACTIVE".equals(mission.getPhase())) {
|
||||||
|
log.warn("任务已处于返航状态,忽略重复结束请求: missionCode={}", missionCode);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String deviceSn = mission.getDeviceSn();
|
||||||
|
|
||||||
|
// 1. 原子更新 phase = RETURNING(防止并发更新目标)
|
||||||
|
mission.setPhase("RETURNING");
|
||||||
|
updateById(mission);
|
||||||
|
|
||||||
|
// 2. 设备端不支持 fly_to_point_stop,直接发送一键返航命令。
|
||||||
|
Result<String> returnResult = deviceCenterService.returnHome(deviceSn);
|
||||||
|
// 返航命令失败不会阻塞流程(phase 保持 RETURNING)
|
||||||
|
if (returnResult == null || returnResult.getResp_code() != 0) {
|
||||||
|
log.error("返航命令失败,任务保持 RETURNING: missionCode={}", missionCode);
|
||||||
|
throw new RuntimeException("返航命令失败,任务未结束: " + (returnResult != null ? returnResult.getResp_msg() : "无响应"));
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("指点飞行结束流程完成,等待降落: missionCode={}", missionCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否已发送过首次 fly_to_point 指令
|
||||||
|
*/
|
||||||
|
private boolean hasSentFirstFlyToPoint(String missionCode) {
|
||||||
|
return missionFlyToPointMapper.selectCount(
|
||||||
|
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<MissionFlyToPoint>()
|
||||||
|
.eq(MissionFlyToPoint::getMissionCode, missionCode)
|
||||||
|
.eq(MissionFlyToPoint::getCommandType, "fly_to_point")) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int nextTargetSequence(String missionCode) {
|
||||||
|
Long count = missionFlyToPointMapper.selectCount(
|
||||||
|
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<MissionFlyToPoint>()
|
||||||
|
.eq(MissionFlyToPoint::getMissionCode, missionCode));
|
||||||
|
return count.intValue() + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成任务编码
|
||||||
|
*/
|
||||||
|
private String generateMissionCode() {
|
||||||
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
|
||||||
|
return "FP" + sdf.format(new Date());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ public class Order extends SuperEntity {
|
|||||||
@Schema(description = "订单状态")
|
@Schema(description = "订单状态")
|
||||||
private Integer orderStatus;
|
private Integer orderStatus;
|
||||||
|
|
||||||
@Schema(description = "支付类型(1:微信支付,2:优惠券支付, 3: 第三方聚到核销)")
|
@Schema(description = "支付类型(1:微信支付,2:优惠券支付,3:第三方聚到核销,4:支付宝支付)")
|
||||||
private Integer payType;
|
private Integer payType;
|
||||||
|
|
||||||
private Date payTime;
|
private Date payTime;
|
||||||
|
|||||||
@@ -132,4 +132,22 @@ public class QrCode extends SuperEntity {
|
|||||||
@Schema(description = "携程产品ID")
|
@Schema(description = "携程产品ID")
|
||||||
private Long ctripProductId;
|
private Long ctripProductId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝小程序二维码 fileId(S3)
|
||||||
|
*/
|
||||||
|
@Schema(description = "支付宝小程序二维码 fileId(S3)")
|
||||||
|
private String alipayFileId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝小程序二维码对象路径(S3 bucket/objectKey)
|
||||||
|
*/
|
||||||
|
@Schema(description = "支付宝小程序二维码对象路径(S3 bucket/objectKey)")
|
||||||
|
private String alipayFilePath;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝小程序二维码访问 URL(运行时填充,不入库)
|
||||||
|
*/
|
||||||
|
@Schema(description = "支付宝小程序二维码访问 URL(运行时填充,不入库)")
|
||||||
|
private transient String alipayViewUrl;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+29
@@ -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);
|
||||||
|
}
|
||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
package com.central.order.service;
|
||||||
|
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import com.central.common.model.PageResult;
|
||||||
|
import com.central.common.service.ISuperService;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝配置 Service 接口
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
public interface IAlipayConfigService extends ISuperService<AlipayConfig> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询
|
||||||
|
*/
|
||||||
|
PageResult<AlipayConfig> findList(Map<String, Object> params);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据类型和租户ID查询配置
|
||||||
|
*/
|
||||||
|
AlipayConfig getConfigByTypeAndTenantId(String type, String tenantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据 AppId 和类型查询配置
|
||||||
|
*/
|
||||||
|
AlipayConfig getConfigByAppIdAndType(String appId, String type);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据 AppId 查询配置(不区分类型)
|
||||||
|
*/
|
||||||
|
AlipayConfig getConfigByAppId(String appId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据子商户号查询配置(ISV 模式)
|
||||||
|
*/
|
||||||
|
AlipayConfig getConfigBySubMerchantId(String subMerchantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存配置
|
||||||
|
*/
|
||||||
|
boolean saveConfig(AlipayConfig config);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新配置
|
||||||
|
*/
|
||||||
|
boolean updateConfig(AlipayConfig config);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除配置
|
||||||
|
*/
|
||||||
|
boolean deleteConfig(Long id);
|
||||||
|
}
|
||||||
+8
@@ -14,4 +14,12 @@ public interface ICtripDistOrderService {
|
|||||||
* @param mobile 用户手机号(可为null,为null时使用默认值)
|
* @param mobile 用户手机号(可为null,为null时使用默认值)
|
||||||
*/
|
*/
|
||||||
void createCtripDistOrder(String orderNo, String orderAmount, Long ctripProductId, String tenantId, String mobile);
|
void createCtripDistOrder(String orderNo, String orderAmount, Long ctripProductId, String tenantId, String mobile);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 异步退订携程分销订单
|
||||||
|
*
|
||||||
|
* @param orderNo 本地订单号
|
||||||
|
* @param reason 退订原因
|
||||||
|
*/
|
||||||
|
void cancelCtripDistOrder(String orderNo, String reason);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,6 +57,17 @@ public interface IOrderService extends ISuperService<Order> {
|
|||||||
*/
|
*/
|
||||||
Order getOrderByNumber(String orderNumber);
|
Order getOrderByNumber(String orderNumber);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订单编号+租户ID 查询订单(支付/退款回调严格隔离)
|
||||||
|
*/
|
||||||
|
Order getOrderByNumberAndTenant(String orderNumber, String tenantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订单编号查询订单(优先按租户查询,查不到则降级仅按订单号查询)
|
||||||
|
* 用于支付宝回调等场景,配置租户可能与订单租户不一致的情况
|
||||||
|
*/
|
||||||
|
Order getOrderByNumberWithFallback(String orderNumber, String tenantId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 订单信息更新
|
* 订单信息更新
|
||||||
* @param order
|
* @param order
|
||||||
|
|||||||
+103
@@ -0,0 +1,103 @@
|
|||||||
|
package com.central.order.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import com.central.common.model.PageResult;
|
||||||
|
import com.central.common.service.impl.SuperServiceImpl;
|
||||||
|
import com.central.order.mapper.AlipayConfigMapper;
|
||||||
|
import com.central.order.service.IAlipayConfigService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.commons.collections4.MapUtils;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝配置 Service 实现
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class AlipayConfigServiceImpl
|
||||||
|
extends SuperServiceImpl<AlipayConfigMapper, AlipayConfig>
|
||||||
|
implements IAlipayConfigService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PageResult<AlipayConfig> findList(Map<String, Object> params) {
|
||||||
|
Page<AlipayConfig> page = new Page<>(
|
||||||
|
MapUtils.getInteger(params, "page", 1),
|
||||||
|
MapUtils.getInteger(params, "limit", 10));
|
||||||
|
List<AlipayConfig> list = baseMapper.findList(page, params);
|
||||||
|
return PageResult.<AlipayConfig>builder()
|
||||||
|
.data(list).resp_code(0).count(page.getTotal()).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AlipayConfig getConfigByTypeAndTenantId(String type, String tenantId) {
|
||||||
|
// 1. 先按当前租户查询
|
||||||
|
AlipayConfig config = queryByTypeAndTenantId(type, tenantId);
|
||||||
|
if (config != null) {
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
// 2. 查不到时降级到 webApp 默认配置
|
||||||
|
if (!"webApp".equals(tenantId)) {
|
||||||
|
log.info("当前租户[{}]未配置支付宝[{}],降级使用 webApp 默认配置", tenantId, type);
|
||||||
|
config = queryByTypeAndTenantId(type, "webApp");
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AlipayConfig queryByTypeAndTenantId(String type, String tenantId) {
|
||||||
|
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(AlipayConfig::getType, type)
|
||||||
|
.eq(AlipayConfig::getTenantId, tenantId)
|
||||||
|
.eq(AlipayConfig::getStatus, 1);
|
||||||
|
return baseMapper.selectOne(wrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AlipayConfig getConfigByAppIdAndType(String appId, String type) {
|
||||||
|
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(AlipayConfig::getAppId, appId)
|
||||||
|
.eq(AlipayConfig::getType, type)
|
||||||
|
.eq(AlipayConfig::getStatus, 1);
|
||||||
|
return baseMapper.selectOne(wrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AlipayConfig getConfigByAppId(String appId) {
|
||||||
|
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(AlipayConfig::getAppId, appId)
|
||||||
|
.eq(AlipayConfig::getStatus, 1)
|
||||||
|
.last("LIMIT 1");
|
||||||
|
return baseMapper.selectOne(wrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AlipayConfig getConfigBySubMerchantId(String subMerchantId) {
|
||||||
|
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(AlipayConfig::getSubMerchantId, subMerchantId)
|
||||||
|
.eq(AlipayConfig::getStatus, 1);
|
||||||
|
return baseMapper.selectOne(wrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean saveConfig(AlipayConfig config) {
|
||||||
|
return save(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean updateConfig(AlipayConfig config) {
|
||||||
|
return updateById(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean deleteConfig(Long id) {
|
||||||
|
return removeById(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
+219
@@ -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) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
@@ -41,4 +41,20 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
|||||||
log.error("携程分销订单创建异常,orderNo: {}", orderNo, e);
|
log.error("携程分销订单创建异常,orderNo: {}", orderNo, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Async
|
||||||
|
@Override
|
||||||
|
public void cancelCtripDistOrder(String orderNo, String reason) {
|
||||||
|
log.info("开始异步退订携程分销订单,orderNo: {}, reason: {}", orderNo, reason);
|
||||||
|
try {
|
||||||
|
Result<String> result = couponCenterService.cancelCtripDistOrder(orderNo, reason);
|
||||||
|
if (result != null && result.getResp_code() == 0) {
|
||||||
|
log.info("携程分销订单退订成功,orderNo: {}", orderNo);
|
||||||
|
} else {
|
||||||
|
log.error("携程分销订单退订失败,orderNo: {}, result: {}", orderNo, result);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("携程分销订单退订异常,orderNo: {}", orderNo, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+17
@@ -279,6 +279,23 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
|||||||
return baseMapper.getOrderByNumber(orderNumber);
|
return baseMapper.getOrderByNumber(orderNumber);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Order getOrderByNumberAndTenant(String orderNumber, String tenantId) {
|
||||||
|
return baseMapper.getOrderByNumberAndTenant(orderNumber, tenantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Order getOrderByNumberWithFallback(String orderNumber, String tenantId) {
|
||||||
|
// 先按订单号+租户严格查询
|
||||||
|
Order order = baseMapper.getOrderByNumberAndTenant(orderNumber, tenantId);
|
||||||
|
if (order != null) {
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
// 降级:仅按订单号查询(回调场景配置租户可能与订单租户不一致)
|
||||||
|
log.info("按租户[{}]未查到订单[{}],降级按订单号查询", tenantId, orderNumber);
|
||||||
|
return baseMapper.getOrderByNumber(orderNumber);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean updateOrder(Order order) {
|
public boolean updateOrder(Order order) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
package com.central.order.util;
|
package com.central.order.util;
|
||||||
|
|
||||||
import javax.servlet.ServletInputStream;
|
import jakarta.servlet.ServletInputStream;
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
|
|||||||
@@ -26,4 +26,16 @@ public class StringUtils {
|
|||||||
return "0.00元";
|
return "0.00元";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分(字符串)转元(字符串,纯数字,保留两位小数),用于支付宝 SDK total_amount/refund_amount。
|
||||||
|
*/
|
||||||
|
public static String fenToYuanAmount(String fenStr) {
|
||||||
|
if (fenStr == null || fenStr.isEmpty()) {
|
||||||
|
return "0.00";
|
||||||
|
}
|
||||||
|
long fen = Long.parseLong(fenStr.trim());
|
||||||
|
return new java.math.BigDecimal(fen).movePointLeft(2)
|
||||||
|
.setScale(2, java.math.RoundingMode.HALF_UP).toPlainString();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- 指点飞行安全审计字段;适用于已执行初始迁移的数据库。
|
||||||
|
ALTER TABLE mission_fly_to_point
|
||||||
|
ADD COLUMN clearance_status VARCHAR(20) NOT NULL DEFAULT 'UNVERIFIED' COMMENT '净空状态:VERIFIED / UNVERIFIED',
|
||||||
|
ADD COLUMN clearance_meters FLOAT DEFAULT NULL COMMENT '计算得到的最小净空(米)',
|
||||||
|
ADD COLUMN candidate_surface_height FLOAT DEFAULT NULL COMMENT '点击命中的模型或地形表面椭球高,仅审计使用',
|
||||||
|
ADD COLUMN risk_acknowledged TINYINT NOT NULL DEFAULT 0 COMMENT '是否已确认未验证净空风险',
|
||||||
|
ADD COLUMN risk_reason VARCHAR(512) DEFAULT NULL COMMENT '风险原因',
|
||||||
|
ADD COLUMN risk_acknowledged_user_id BIGINT DEFAULT NULL COMMENT '确认风险的账户ID',
|
||||||
|
ADD COLUMN risk_acknowledged_username VARCHAR(64) DEFAULT NULL COMMENT '确认风险的账户名';
|
||||||
|
|
||||||
|
ALTER TABLE mission_fly_to_point
|
||||||
|
ADD UNIQUE KEY uk_mission_fly_to_point_seq (mission_code, seq);
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- =====================================================
|
||||||
|
-- 指点飞行功能 - 数据库迁移脚本
|
||||||
|
-- =====================================================
|
||||||
|
|
||||||
|
-- 1. missions 表新增 phase 字段
|
||||||
|
ALTER TABLE missions ADD COLUMN phase VARCHAR(20) DEFAULT 'ACTIVE' COMMENT '会话阶段:ACTIVE / RETURNING';
|
||||||
|
|
||||||
|
-- 2. 创建 mission_fly_to_point 子表(记录每次目标更新)
|
||||||
|
CREATE TABLE IF NOT EXISTS mission_fly_to_point (
|
||||||
|
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键',
|
||||||
|
mission_code VARCHAR(64) NOT NULL COMMENT '关联任务编码',
|
||||||
|
fly_to_id VARCHAR(64) NOT NULL COMMENT '飞行会话ID(= missionCode)',
|
||||||
|
command_id VARCHAR(64) DEFAULT NULL COMMENT '设备命令ID',
|
||||||
|
seq INT DEFAULT 1 COMMENT '目标序号(1, 2, 3...)',
|
||||||
|
command_type VARCHAR(32) NOT NULL COMMENT '指令类型:fly_to_point / fly_to_point_update',
|
||||||
|
latitude DOUBLE COMMENT '目标纬度',
|
||||||
|
longitude DOUBLE COMMENT '目标经度',
|
||||||
|
height FLOAT COMMENT '目标椭球高',
|
||||||
|
max_speed FLOAT DEFAULT 12 COMMENT '最大速度',
|
||||||
|
status VARCHAR(20) DEFAULT 'SENT' COMMENT '状态:SENT / REACHED / FAILED',
|
||||||
|
create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
INDEX idx_mission_code (mission_code),
|
||||||
|
INDEX idx_fly_to_id (fly_to_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='指点飞行目标点记录表';
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
|
<mapper namespace="com.central.order.mapper.AlipayConfigMapper">
|
||||||
|
|
||||||
|
<select id="findList" resultType="com.central.alipay.entity.AlipayConfig">
|
||||||
|
SELECT * FROM alipay_config
|
||||||
|
<where>
|
||||||
|
<if test='p.type != null and p.type != ""'>
|
||||||
|
AND type = #{p.type}
|
||||||
|
</if>
|
||||||
|
<if test='p.tenantId != null and p.tenantId != ""'>
|
||||||
|
AND tenant_id = #{p.tenantId}
|
||||||
|
</if>
|
||||||
|
<if test='p.appId != null and p.appId != ""'>
|
||||||
|
AND app_id = #{p.appId}
|
||||||
|
</if>
|
||||||
|
<if test='p.status != null'>
|
||||||
|
AND status = #{p.status}
|
||||||
|
</if>
|
||||||
|
<if test='p.searchKey != null and p.searchKey != "" and p.searchValue != null and p.searchValue != ""'>
|
||||||
|
<choose>
|
||||||
|
<when test='p.searchKey == "type"'>
|
||||||
|
AND type = #{p.searchValue}
|
||||||
|
</when>
|
||||||
|
<when test='p.searchKey == "appId"'>
|
||||||
|
AND app_id LIKE CONCAT('%', #{p.searchValue}, '%')
|
||||||
|
</when>
|
||||||
|
<when test='p.searchKey == "tenantId"'>
|
||||||
|
AND tenant_id LIKE CONCAT('%', #{p.searchValue}, '%')
|
||||||
|
</when>
|
||||||
|
</choose>
|
||||||
|
</if>
|
||||||
|
</where>
|
||||||
|
ORDER BY create_time DESC
|
||||||
|
</select>
|
||||||
|
|
||||||
|
</mapper>
|
||||||
@@ -28,6 +28,7 @@
|
|||||||
<result column="is_del" property="isDel"/>
|
<result column="is_del" property="isDel"/>
|
||||||
<result column="create_time" property="createTime"/>
|
<result column="create_time" property="createTime"/>
|
||||||
<result column="update_time" property="updateTime"/>
|
<result column="update_time" property="updateTime"/>
|
||||||
|
<result column="phase" property="phase"/>
|
||||||
<!-- 临时字段 -->
|
<!-- 临时字段 -->
|
||||||
<result column="tourism_name" property="tourismName"/>
|
<result column="tourism_name" property="tourismName"/>
|
||||||
<result column="image_count" property="imageCount"/>
|
<result column="image_count" property="imageCount"/>
|
||||||
@@ -40,7 +41,7 @@
|
|||||||
m.workspace_id, m.tourism_id, m.mission_status,
|
m.workspace_id, m.tourism_id, m.mission_status,
|
||||||
m.target_latitude, m.target_longitude, m.target_height,
|
m.target_latitude, m.target_longitude, m.target_height,
|
||||||
m.start_time, m.end_time, m.creator_id, m.creator_name, m.remark,
|
m.start_time, m.end_time, m.creator_id, m.creator_name, m.remark,
|
||||||
m.tenant_id, m.is_del, m.create_time, m.update_time
|
m.tenant_id, m.is_del, m.create_time, m.update_time, m.phase
|
||||||
</sql>
|
</sql>
|
||||||
|
|
||||||
<!-- 分页查询任务列表 -->
|
<!-- 分页查询任务列表 -->
|
||||||
@@ -99,6 +100,15 @@
|
|||||||
AND m.is_del = 0
|
AND m.is_del = 0
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<select id="getByMissionCodeForUpdate" resultMap="BaseResultMap">
|
||||||
|
SELECT
|
||||||
|
<include refid="Base_Column_List"/>
|
||||||
|
FROM missions m
|
||||||
|
WHERE m.mission_code = #{missionCode}
|
||||||
|
AND m.is_del = 0
|
||||||
|
FOR UPDATE
|
||||||
|
</select>
|
||||||
|
|
||||||
<!-- 更新任务状态 -->
|
<!-- 更新任务状态 -->
|
||||||
<update id="updateMissionStatus">
|
<update id="updateMissionStatus">
|
||||||
UPDATE missions
|
UPDATE missions
|
||||||
|
|||||||
@@ -108,4 +108,9 @@
|
|||||||
SELECT * FROM orders WHERE order_no = #{orderNumber}
|
SELECT * FROM orders WHERE order_no = #{orderNumber}
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<!-- 根据订单编号 + 租户ID 查询订单信息(用于支付/退款回调按配置租户严格定位订单) -->
|
||||||
|
<select id="getOrderByNumberAndTenant" resultMap="OrderResultMap">
|
||||||
|
SELECT * FROM orders WHERE order_no = #{orderNumber} AND tenant_id = #{tenantId}
|
||||||
|
</select>
|
||||||
|
|
||||||
</mapper>
|
</mapper>
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-- 二维码表添加支付宝小程序二维码相关字段
|
||||||
|
-- 用途:在同一行 qrcodes 上挂支付宝小程序二维码图(与微信码共用 code_id 与所有业务字段)
|
||||||
|
-- 一行业务、两张图:用户扫微信码进微信小程序,扫支付宝码进支付宝小程序,后端用同一 code_id 命中同一行
|
||||||
|
ALTER TABLE qrcodes
|
||||||
|
ADD COLUMN alipay_file_id VARCHAR(64) NULL COMMENT '支付宝小程序二维码 fileId(S3)',
|
||||||
|
ADD COLUMN alipay_file_path VARCHAR(512) NULL COMMENT '支付宝小程序二维码对象 path(S3 bucket/objectKey)';
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
package com.central.order.mission.command;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
class FlyToPointTargetCommandTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 未验证路径且未确认风险时拒绝发送() {
|
||||||
|
FlyToPointTargetCommand command = FlyToPointTargetCommand.builder()
|
||||||
|
.clearanceStatus("UNVERIFIED")
|
||||||
|
.riskAcknowledged(false)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, command::validateRiskAcknowledgement);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 已验证路径无需风险确认即可发送() {
|
||||||
|
FlyToPointTargetCommand command = FlyToPointTargetCommand.builder()
|
||||||
|
.clearanceStatus("VERIFIED")
|
||||||
|
.riskAcknowledged(false)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertDoesNotThrow(command::validateRiskAcknowledgement);
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
@@ -145,11 +145,53 @@ public class SysUserController {
|
|||||||
return appUserService.findByWxOpenid(openId,mobile,unionId);
|
return appUserService.findByWxOpenid(openId,mobile,unionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据支付宝userId查询用户信息(Feign内部调用)
|
||||||
|
* <p>
|
||||||
|
* 已有用户按 openId 匹配后更新信息返回;新用户自动注册。
|
||||||
|
*
|
||||||
|
* @param alipayUserId 支付宝 userId(alipay.system.oauth.token 返回,必填)
|
||||||
|
* @param unionId 支付宝 union_id(同 PID 下唯一,可选)
|
||||||
|
* @param mobile 手机号(自动注册时填入,可选)
|
||||||
|
* @param appId 支付宝应用ID(预留,可选)
|
||||||
|
* @return SysUser 系统用户对象(含 id/username/mobile/openId/enabled)
|
||||||
|
*/
|
||||||
|
@GetMapping(value = "/users-anon/alipayOpenId")
|
||||||
|
@Operation(summary = "根据支付宝userId查询或注册用户(Feign内部)",
|
||||||
|
description = "入参:alipayUserId(必填)+unionId+mobile+appId(可选)。"
|
||||||
|
+ "出参:SysUser 对象。逻辑:已有用户更新信息,新用户自动创建。")
|
||||||
|
@Parameter(name = "alipayUserId", description = "支付宝 userId(alipay.system.oauth.token 返回)", required = true, example = "2088xxxxxxxxxxxx")
|
||||||
|
@Parameter(name = "unionId", description = "支付宝 union_id(同 PID 下唯一)")
|
||||||
|
@Parameter(name = "mobile", description = "手机号(注册时填入)", example = "138xxxx1234")
|
||||||
|
@Parameter(name = "appId", description = "支付宝应用ID(预留)", example = "2021000000000001")
|
||||||
|
public SysUser findByAlipayOpenId(@RequestParam("alipayUserId") String alipayUserId,
|
||||||
|
@RequestParam(required = false) String unionId,
|
||||||
|
@RequestParam(required = false) String mobile,
|
||||||
|
@RequestParam(required = false) String appId) throws Exception {
|
||||||
|
return appUserService.findByAlipayOpenid(alipayUserId, unionId, mobile, appId);
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/users/{id}")
|
@GetMapping("/users/{id}")
|
||||||
public SysUser findUserById(@PathVariable Long id) {
|
public SysUser findUserById(@PathVariable Long id) {
|
||||||
return appUserService.getById(id);
|
return appUserService.getById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据系统用户ID查询支付宝 openId(供 order-center 下单时获取 buyerId)
|
||||||
|
*
|
||||||
|
* @param userId 系统用户ID
|
||||||
|
* @param appId 支付宝应用ID
|
||||||
|
* @return 支付宝 userId,无映射时返回 null
|
||||||
|
*/
|
||||||
|
@GetMapping("/users/{userId}/alipay-openid")
|
||||||
|
@Operation(summary = "根据系统用户ID查询支付宝openId",
|
||||||
|
description = "查询 sys_user_third_openid 映射表,获取该用户在指定支付宝应用下的 openId")
|
||||||
|
@Parameter(name = "userId", description = "系统用户ID", required = true, example = "1001")
|
||||||
|
@Parameter(name = "appId", description = "支付宝应用ID", required = true, example = "2021000000000001")
|
||||||
|
public String getAlipayOpenIdByUserId(@PathVariable Long userId, @RequestParam String appId) {
|
||||||
|
return appUserService.getAlipayOpenIdByUserId(userId, appId);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 管理后台修改用户
|
* 管理后台修改用户
|
||||||
*
|
*
|
||||||
|
|||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package com.central.user.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.central.user.model.SysUserThirdOpenid;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 第三方用户 OpenId 映射 Mapper
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface SysUserThirdOpenidMapper extends BaseMapper<SysUserThirdOpenid> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.central.user.model;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 第三方用户 OpenId 映射表
|
||||||
|
* <p>
|
||||||
|
* 统一管理微信/支付宝等各家 openId/userId,与 SysUser.openId 解耦。
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sys_user_third_openid")
|
||||||
|
@Schema(description = "第三方用户OpenId映射")
|
||||||
|
public class SysUserThirdOpenid {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
@Schema(description = "主键")
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "系统用户ID")
|
||||||
|
private Long userId;
|
||||||
|
|
||||||
|
@Schema(description = "第三方平台:WECHAT / ALIPAY", example = "ALIPAY")
|
||||||
|
private String provider;
|
||||||
|
|
||||||
|
@Schema(description = "第三方应用ID")
|
||||||
|
private String appId;
|
||||||
|
|
||||||
|
@Schema(description = "第三方用户唯一标识", example = "2088123456789012")
|
||||||
|
private String openId;
|
||||||
|
|
||||||
|
@Schema(description = "第三方 unionId(微信 unionId / 支付宝 union_id)")
|
||||||
|
private String unionId;
|
||||||
|
|
||||||
|
@Schema(description = "手机号")
|
||||||
|
private String mobile;
|
||||||
|
}
|
||||||
@@ -31,6 +31,16 @@ public interface ISysUserService extends ISuperService<SysUser> {
|
|||||||
|
|
||||||
SysUser findByWxOpenid(String wxOpenid,String mobile,String unionId) throws Exception;
|
SysUser findByWxOpenid(String wxOpenid,String mobile,String unionId) throws Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据支付宝userId查询用户(关联或自动注册)
|
||||||
|
*/
|
||||||
|
SysUser findByAlipayOpenid(String alipayUserId, String unionId, String mobile, String appId) throws Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据系统用户ID查询支付宝 openId(从 sys_user_third_openid 映射表)
|
||||||
|
*/
|
||||||
|
String getAlipayOpenIdByUserId(Long userId, String appId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 通过SysUser 把roles和permissions也查询出来
|
* 通过SysUser 把roles和permissions也查询出来
|
||||||
* @param sysUser
|
* @param sysUser
|
||||||
|
|||||||
+138
-2
@@ -5,9 +5,9 @@ import cn.hutool.core.util.ObjectUtil;
|
|||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.central.common.constant.CommonConstant;
|
import com.central.common.constant.CommonConstant;
|
||||||
import com.central.common.context.LoginUserContextHolder;
|
|
||||||
import com.central.common.datascope.annotation.IgnoreTenantScope;
|
import com.central.common.datascope.annotation.IgnoreTenantScope;
|
||||||
import com.central.common.lock.DistributedLock;
|
import com.central.common.lock.DistributedLock;
|
||||||
|
import com.central.common.lock.ZLock;
|
||||||
import com.central.common.model.PageResult;
|
import com.central.common.model.PageResult;
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.common.model.SysRole;
|
import com.central.common.model.SysRole;
|
||||||
@@ -22,8 +22,10 @@ import com.central.common.context.LoginUserContextHolder;
|
|||||||
import com.central.user.feign.OrderCenterService;
|
import com.central.user.feign.OrderCenterService;
|
||||||
import com.central.user.mapper.SysRoleMenuMapper;
|
import com.central.user.mapper.SysRoleMenuMapper;
|
||||||
import com.central.user.mapper.SysUserMapper;
|
import com.central.user.mapper.SysUserMapper;
|
||||||
|
import com.central.user.mapper.SysUserThirdOpenidMapper;
|
||||||
import com.central.user.model.SysRoleUser;
|
import com.central.user.model.SysRoleUser;
|
||||||
import com.central.user.model.SysUserExcel;
|
import com.central.user.model.SysUserExcel;
|
||||||
|
import com.central.user.model.SysUserThirdOpenid;
|
||||||
import com.central.user.service.ISysRoleUserService;
|
import com.central.user.service.ISysRoleUserService;
|
||||||
import com.central.user.service.ISysUserService;
|
import com.central.user.service.ISysUserService;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -58,6 +60,9 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
@Resource
|
@Resource
|
||||||
private SysRoleMenuMapper roleMenuMapper;
|
private SysRoleMenuMapper roleMenuMapper;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private SysUserThirdOpenidMapper sysUserThirdOpenidMapper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private DistributedLock lock;
|
private DistributedLock lock;
|
||||||
|
|
||||||
@@ -106,7 +111,25 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
sysUser.setMobile(mobile);
|
sysUser.setMobile(mobile);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 创建新用户
|
// 未找到 → 先按手机号匹配已有账号(支付宝用户改用微信登录时自动关联)
|
||||||
|
sysUser = null;
|
||||||
|
if (StringUtils.isNotEmpty(mobile)) {
|
||||||
|
sysUser = this.selectByMobile(mobile);
|
||||||
|
if (ObjectUtil.isNotEmpty(sysUser)) {
|
||||||
|
log.info("微信登录按手机号关联已有用户: userId={}, mobile={}", sysUser.getId(), mobile);
|
||||||
|
// 将微信 openId 写入已有用户
|
||||||
|
sysUser.setOpenId(wxOpenid);
|
||||||
|
if (StringUtils.isNotEmpty(unionId)) {
|
||||||
|
sysUser.setUnionId(unionId);
|
||||||
|
}
|
||||||
|
if (StringUtils.isNotEmpty(mobile)) {
|
||||||
|
sysUser.setMobile(mobile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sysUser == null) {
|
||||||
|
// 全新用户
|
||||||
sysUser = new SysUser();
|
sysUser = new SysUser();
|
||||||
sysUser.setOpenId(wxOpenid);
|
sysUser.setOpenId(wxOpenid);
|
||||||
sysUser.setUsername(wxOpenid);
|
sysUser.setUsername(wxOpenid);
|
||||||
@@ -116,6 +139,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
sysUser.setMobile(mobile);
|
sysUser.setMobile(mobile);
|
||||||
sysUser.setUnionId(unionId);
|
sysUser.setUnionId(unionId);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
String username = sysUser.getUsername();
|
String username = sysUser.getUsername();
|
||||||
boolean result = super.saveOrUpdateIdempotency(sysUser, lock,
|
boolean result = super.saveOrUpdateIdempotency(sysUser, lock,
|
||||||
@@ -126,6 +150,118 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
return result ? sysUser : new SysUser();
|
return result ? sysUser : new SysUser();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SysUser findByAlipayOpenid(String alipayUserId, String unionId, String mobile, String appId) throws Exception {
|
||||||
|
log.info("支付宝登录: alipayUserId={}, unionId={}, mobile={}, appId={}", alipayUserId, unionId, mobile, appId);
|
||||||
|
|
||||||
|
// 1. 查 sys_user_third_openid 映射表(不走 SysUser.openId,避免与 grantType=openId 冲突)
|
||||||
|
QueryWrapper<SysUserThirdOpenid> mappingQuery = new QueryWrapper<SysUserThirdOpenid>()
|
||||||
|
.eq("provider", "ALIPAY")
|
||||||
|
.eq("app_id", appId)
|
||||||
|
.eq("open_id", alipayUserId);
|
||||||
|
SysUserThirdOpenid mapping = sysUserThirdOpenidMapper.selectOne(mappingQuery);
|
||||||
|
|
||||||
|
SysUser sysUser = null;
|
||||||
|
if (mapping != null) {
|
||||||
|
// 已有映射 → 查到对应的 SysUser
|
||||||
|
sysUser = baseMapper.selectById(mapping.getUserId());
|
||||||
|
if (sysUser == null) {
|
||||||
|
log.error("sys_user_third_openid 映射存在但 SysUser 不存在: userId={}", mapping.getUserId());
|
||||||
|
throw new RuntimeException("用户数据异常");
|
||||||
|
}
|
||||||
|
// 更新映射信息
|
||||||
|
if (StringUtils.isNotEmpty(mobile)) {
|
||||||
|
sysUser.setMobile(mobile);
|
||||||
|
mapping.setMobile(mobile);
|
||||||
|
}
|
||||||
|
if (StringUtils.isNotEmpty(unionId)) {
|
||||||
|
mapping.setUnionId(unionId);
|
||||||
|
}
|
||||||
|
sysUserThirdOpenidMapper.updateById(mapping);
|
||||||
|
log.info("支付宝用户已存在: userId={}, alipayUserId={}", sysUser.getId(), alipayUserId);
|
||||||
|
} else {
|
||||||
|
// 无映射 → 先按手机号匹配已有账号(分布式锁防并发重复创建)
|
||||||
|
String lockKey = "alipay:user:" + alipayUserId;
|
||||||
|
ZLock zLock = null;
|
||||||
|
try {
|
||||||
|
zLock = lock.tryLock(lockKey, 5, java.util.concurrent.TimeUnit.SECONDS);
|
||||||
|
if (zLock == null) {
|
||||||
|
log.warn("获取分布式锁失败,可能并发登录: {}", alipayUserId);
|
||||||
|
throw new RuntimeException("系统繁忙,请稍后重试");
|
||||||
|
}
|
||||||
|
// 双重检查:获取锁后再查一次映射表
|
||||||
|
SysUserThirdOpenid recheck = sysUserThirdOpenidMapper.selectOne(mappingQuery);
|
||||||
|
if (recheck != null) {
|
||||||
|
sysUser = baseMapper.selectById(recheck.getUserId());
|
||||||
|
} else if (StringUtils.isNotEmpty(mobile)) {
|
||||||
|
sysUser = selectByMobile(mobile);
|
||||||
|
if (ObjectUtil.isNotEmpty(sysUser)) {
|
||||||
|
log.info("按手机号关联已有用户: userId={}, mobile={}", sysUser.getId(), mobile);
|
||||||
|
sysUser.setMobile(mobile);
|
||||||
|
super.saveOrUpdateIdempotency(sysUser, lock,
|
||||||
|
LOCK_KEY_USERNAME + sysUser.getUsername(),
|
||||||
|
new QueryWrapper<SysUser>().eq("username", sysUser.getUsername()),
|
||||||
|
sysUser.getUsername() + "已存在");
|
||||||
|
insertThirdOpenidMapping(sysUser.getId(), "ALIPAY", appId, alipayUserId, unionId, mobile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sysUser == null) {
|
||||||
|
sysUser = new SysUser();
|
||||||
|
sysUser.setUsername("alipay_" + alipayUserId);
|
||||||
|
sysUser.setType(UserType.APP.name());
|
||||||
|
sysUser.setPassword(alipayUserId);
|
||||||
|
sysUser.setEnabled(Boolean.TRUE);
|
||||||
|
sysUser.setMobile(mobile);
|
||||||
|
boolean saved = super.saveOrUpdateIdempotency(sysUser, lock,
|
||||||
|
LOCK_KEY_USERNAME + sysUser.getUsername(),
|
||||||
|
new QueryWrapper<SysUser>().eq("username", sysUser.getUsername()),
|
||||||
|
sysUser.getUsername() + "已存在");
|
||||||
|
if (!saved) { return new SysUser(); }
|
||||||
|
log.info("创建支付宝新用户: userId={}, alipayUserId={}", sysUser.getId(), alipayUserId);
|
||||||
|
insertThirdOpenidMapping(sysUser.getId(), "ALIPAY", appId, alipayUserId, unionId, mobile);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("支付宝用户关联加锁异常", e);
|
||||||
|
throw new RuntimeException("登录失败: " + e.getMessage(), e);
|
||||||
|
} finally {
|
||||||
|
if (zLock != null) {
|
||||||
|
try { lock.unlock(zLock); } catch (Exception ignored) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return sysUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getAlipayOpenIdByUserId(Long userId, String appId) {
|
||||||
|
QueryWrapper<SysUserThirdOpenid> query = new QueryWrapper<SysUserThirdOpenid>()
|
||||||
|
.eq("user_id", userId)
|
||||||
|
.eq("provider", "ALIPAY")
|
||||||
|
.eq("app_id", appId);
|
||||||
|
SysUserThirdOpenid mapping = sysUserThirdOpenidMapper.selectOne(query);
|
||||||
|
return mapping != null ? mapping.getOpenId() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 插入 sys_user_third_openid 映射记录(依赖 DB 唯一索引 uk_provider_appid_openid 保证幂等)
|
||||||
|
*/
|
||||||
|
private void insertThirdOpenidMapping(Long userId, String provider, String appId,
|
||||||
|
String openId, String unionId, String mobile) {
|
||||||
|
try {
|
||||||
|
SysUserThirdOpenid mapping = new SysUserThirdOpenid();
|
||||||
|
mapping.setUserId(userId);
|
||||||
|
mapping.setProvider(provider);
|
||||||
|
mapping.setAppId(appId);
|
||||||
|
mapping.setOpenId(openId);
|
||||||
|
mapping.setUnionId(unionId);
|
||||||
|
mapping.setMobile(mobile);
|
||||||
|
sysUserThirdOpenidMapper.insert(mapping);
|
||||||
|
} catch (org.springframework.dao.DuplicateKeyException e) {
|
||||||
|
log.info("sys_user_third_openid 映射已存在, userId={}, provider={}, openId={}", userId, provider, openId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setUserPermission(SysUser sysUser) {
|
public void setUserPermission(SysUser sysUser) {
|
||||||
if (sysUser != null) {
|
if (sysUser != null) {
|
||||||
|
|||||||
@@ -25,5 +25,7 @@
|
|||||||
<module>zlt-zookeeper-spring-boot-starter</module>
|
<module>zlt-zookeeper-spring-boot-starter</module>
|
||||||
<module>zlt-wechat-common-core</module>
|
<module>zlt-wechat-common-core</module>
|
||||||
<module>zlt-wechat-spring-boot-starter</module>
|
<module>zlt-wechat-spring-boot-starter</module>
|
||||||
|
<module>zlt-alipay-common-core</module>
|
||||||
|
<module>zlt-alipay-spring-boot-starter</module>
|
||||||
</modules>
|
</modules>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>com.zlt</groupId>
|
||||||
|
<artifactId>zlt-commons</artifactId>
|
||||||
|
<version>6.0.0</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>zlt-alipay-common-core</artifactId>
|
||||||
|
<description>支付宝核心功能模块(实体、Feign接口、配置属性)</description>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- 基础依赖 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.zlt</groupId>
|
||||||
|
<artifactId>zlt-common-core</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-context</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.zlt</groupId>
|
||||||
|
<artifactId>zlt-db-spring-boot-starter</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<!-- Knife4j (Swagger annotations) -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.xiaoymin</groupId>
|
||||||
|
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
package com.central.alipay.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝全局配置属性(仅承载全局默认值,运行时配置走 alipay_config 表)
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@ConfigurationProperties(prefix = "zlt.alipay")
|
||||||
|
public class AlipayProperties {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否启用支付宝模块
|
||||||
|
*/
|
||||||
|
private boolean enabled = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网关地址
|
||||||
|
*/
|
||||||
|
private String gatewayUrl = "https://openapi.alipay.com/gateway.do";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签名算法
|
||||||
|
*/
|
||||||
|
private String signType = "RSA2";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 字符集
|
||||||
|
*/
|
||||||
|
private String charset = "UTF-8";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式
|
||||||
|
*/
|
||||||
|
private String format = "json";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AlipayClient 缓存过期时间(秒)
|
||||||
|
*/
|
||||||
|
private int cacheExpireSeconds = 600;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付异步通知地址(全局默认,可被 DB 覆盖)
|
||||||
|
*/
|
||||||
|
private String notifyUrl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 退款异步通知地址(全局默认,可被 DB 覆盖)
|
||||||
|
*/
|
||||||
|
private String refundNotifyUrl;
|
||||||
|
}
|
||||||
+92
@@ -0,0 +1,92 @@
|
|||||||
|
package com.central.alipay.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝配置实体(对标 WechatConfig)
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("alipay_config")
|
||||||
|
@Schema(description = "支付宝配置")
|
||||||
|
public class AlipayConfig {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
@Schema(description = "主键ID", example = "1")
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Schema(description = "租户ID", example = "tenant-001")
|
||||||
|
private String tenantId;
|
||||||
|
|
||||||
|
@Schema(description = "配置类型:MINI=小程序登录,PAY=交易支付", example = "PAY", allowableValues = {"MINI", "PAY"})
|
||||||
|
private String type;
|
||||||
|
|
||||||
|
@Schema(description = "支付宝 AppId", example = "2021000000000001")
|
||||||
|
private String appId;
|
||||||
|
|
||||||
|
@Schema(description = "应用私钥(PKCS8,入库加密)", accessMode = Schema.AccessMode.WRITE_ONLY)
|
||||||
|
private String appPrivateKey;
|
||||||
|
|
||||||
|
@Schema(description = "支付宝公钥(用于回调验签)", accessMode = Schema.AccessMode.WRITE_ONLY)
|
||||||
|
private String alipayPublicKey;
|
||||||
|
|
||||||
|
@Schema(description = "签名算法", example = "RSA2", allowableValues = {"RSA2", "RSA"})
|
||||||
|
private String signType;
|
||||||
|
|
||||||
|
@Schema(description = "字符集", example = "UTF-8")
|
||||||
|
private String charset;
|
||||||
|
|
||||||
|
@Schema(description = "格式", example = "json")
|
||||||
|
private String format;
|
||||||
|
|
||||||
|
@Schema(description = "网关地址", example = "https://openapi.alipay.com/gateway.do")
|
||||||
|
private String gatewayUrl;
|
||||||
|
|
||||||
|
@Schema(description = "支付异步通知地址(type=PAY 时有效)", example = "https://api.example.com/alipay/pay/notify")
|
||||||
|
private String notifyUrl;
|
||||||
|
|
||||||
|
@Schema(description = "退款异步通知地址(type=PAY 时有效)", example = "https://api.example.com/alipay/refund/notify")
|
||||||
|
private String refundNotifyUrl;
|
||||||
|
|
||||||
|
@Schema(description = "是否 ISV(服务商)模式", example = "false")
|
||||||
|
private Boolean isServiceMode;
|
||||||
|
|
||||||
|
@Schema(description = "ISV 合作伙伴 PID", example = "2088xxxxxxxxxxxx")
|
||||||
|
private String pid;
|
||||||
|
|
||||||
|
@Schema(description = "ISV 代调用时使用的 app_auth_token", accessMode = Schema.AccessMode.WRITE_ONLY)
|
||||||
|
private String authToken;
|
||||||
|
|
||||||
|
@Schema(description = "商家应用 AppId(被代调用方)", example = "2021xxxxxxxxxxxx")
|
||||||
|
private String subAppId;
|
||||||
|
|
||||||
|
@Schema(description = "间连商户号 smid", example = "2088xxxxxxxxxxxx")
|
||||||
|
private String subMerchantId;
|
||||||
|
|
||||||
|
@Schema(description = "AES 接口内容加解密 Key", accessMode = Schema.AccessMode.WRITE_ONLY)
|
||||||
|
private String encryptKey;
|
||||||
|
|
||||||
|
@Schema(description = "是否公钥证书模式", example = "false")
|
||||||
|
private Boolean certMode;
|
||||||
|
|
||||||
|
@Schema(description = "应用公钥证书路径(证书模式)")
|
||||||
|
private String appCertPath;
|
||||||
|
|
||||||
|
@Schema(description = "支付宝公钥证书路径(证书模式)")
|
||||||
|
private String alipayCertPath;
|
||||||
|
|
||||||
|
@Schema(description = "支付宝根证书路径(证书模式)")
|
||||||
|
private String alipayRootCertPath;
|
||||||
|
|
||||||
|
@Schema(description = "状态:0=禁用,1=启用", example = "1", allowableValues = {"0", "1"})
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
@Schema(description = "备注", example = "生产环境支付配置")
|
||||||
|
private String remark;
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package com.central.alipay.feign;
|
||||||
|
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import com.central.alipay.feign.fallback.AlipayConfigServiceFallbackFactory;
|
||||||
|
import com.central.common.constant.ServiceNameConstants;
|
||||||
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝配置 Feign 客户端(服务端在 order-center)
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@FeignClient(name = ServiceNameConstants.ORDER_SERVICE, fallbackFactory = AlipayConfigServiceFallbackFactory.class, dismiss404 = true)
|
||||||
|
public interface AlipayConfigService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据类型和租户ID查询配置
|
||||||
|
*/
|
||||||
|
@GetMapping(value = "/alipay/config/type/{type}")
|
||||||
|
AlipayConfig getConfig(@PathVariable("type") String type, @RequestParam("tenantId") String tenantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据 AppId 和类型查询配置
|
||||||
|
*/
|
||||||
|
@GetMapping(value = "/alipay/config/app/{appId}")
|
||||||
|
AlipayConfig getConfigByAppId(@PathVariable("appId") String appId, @RequestParam("type") String type);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据 AppId 查询配置(不区分类型,用于回调定位)
|
||||||
|
*/
|
||||||
|
@GetMapping(value = "/alipay/config/app/{appId}/any")
|
||||||
|
AlipayConfig getConfigByAppId(@PathVariable("appId") String appId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据子商户号获取配置(ISV 模式专用)
|
||||||
|
*/
|
||||||
|
@GetMapping(value = "/alipay/config/sub/{subMerchantId}")
|
||||||
|
AlipayConfig getConfigBySubMerchantId(@PathVariable("subMerchantId") String subMerchantId);
|
||||||
|
}
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
package com.central.alipay.feign.fallback;
|
||||||
|
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import com.central.alipay.feign.AlipayConfigService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AlipayConfigService 降级工厂
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
public class AlipayConfigServiceFallbackFactory implements FallbackFactory<AlipayConfigService> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AlipayConfigService create(Throwable throwable) {
|
||||||
|
log.error("AlipayConfigService 调用失败", throwable);
|
||||||
|
return new AlipayConfigService() {
|
||||||
|
@Override
|
||||||
|
public AlipayConfig getConfig(String type, String tenantId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AlipayConfig getConfigByAppId(String appId, String type) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AlipayConfig getConfigByAppId(String appId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AlipayConfig getConfigBySubMerchantId(String subMerchantId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
com.central.alipay.feign.fallback.AlipayConfigServiceFallbackFactory
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
-- =====================================================
|
||||||
|
-- 支付宝配置表(对标 wechat_config)
|
||||||
|
-- 归属:order-center
|
||||||
|
-- =====================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS `alipay_config` (
|
||||||
|
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
|
`tenant_id` VARCHAR(64) DEFAULT NULL COMMENT '租户ID',
|
||||||
|
`type` VARCHAR(16) NOT NULL COMMENT '配置类型:MINI-小程序登录,PAY-交易支付',
|
||||||
|
`app_id` VARCHAR(64) NOT NULL COMMENT '支付宝 AppId',
|
||||||
|
`app_private_key` TEXT COMMENT '应用私钥(PKCS8,入库建议加密)',
|
||||||
|
`alipay_public_key` TEXT COMMENT '支付宝公钥(用于回调验签)',
|
||||||
|
`sign_type` VARCHAR(16) DEFAULT 'RSA2' COMMENT '签名算法',
|
||||||
|
`charset` VARCHAR(16) DEFAULT 'UTF-8' COMMENT '字符集',
|
||||||
|
`format` VARCHAR(16) DEFAULT 'json' COMMENT '格式',
|
||||||
|
`gateway_url` VARCHAR(256) DEFAULT 'https://openapi.alipay.com/gateway.do' COMMENT '网关地址',
|
||||||
|
`notify_url` VARCHAR(256) DEFAULT NULL COMMENT '支付异步通知地址',
|
||||||
|
`refund_notify_url` VARCHAR(256) DEFAULT NULL COMMENT '退款异步通知地址',
|
||||||
|
`is_service_mode` TINYINT(1) DEFAULT 0 COMMENT '是否 ISV(服务商)模式',
|
||||||
|
`pid` VARCHAR(64) DEFAULT NULL COMMENT 'ISV 合作伙伴 PID',
|
||||||
|
`auth_token` VARCHAR(128) DEFAULT NULL COMMENT 'ISV 代调用时使用的 app_auth_token',
|
||||||
|
`sub_app_id` VARCHAR(64) DEFAULT NULL COMMENT '商家应用 AppId(被代调用方)',
|
||||||
|
`sub_merchant_id` VARCHAR(64) DEFAULT NULL COMMENT '间连商户号(smid)',
|
||||||
|
`encrypt_key` VARCHAR(128) DEFAULT NULL COMMENT 'AES 接口内容加解密 Key',
|
||||||
|
`cert_mode` TINYINT(1) DEFAULT 0 COMMENT '是否公钥证书模式:0-普通公钥,1-证书模式',
|
||||||
|
`app_cert_path` VARCHAR(256) DEFAULT NULL COMMENT '应用公钥证书路径',
|
||||||
|
`alipay_cert_path` VARCHAR(256) DEFAULT NULL COMMENT '支付宝公钥证书路径',
|
||||||
|
`alipay_root_cert_path` VARCHAR(256) DEFAULT NULL COMMENT '支付宝根证书路径',
|
||||||
|
`status` TINYINT DEFAULT 1 COMMENT '状态:0-禁用,1-启用',
|
||||||
|
`remark` VARCHAR(255) DEFAULT NULL COMMENT '备注',
|
||||||
|
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_tenant_type_appid` (`tenant_id`, `type`, `app_id`),
|
||||||
|
KEY `idx_tenant_type` (`tenant_id`, `type`),
|
||||||
|
KEY `idx_app_id` (`app_id`),
|
||||||
|
KEY `idx_sub_merchant_id` (`sub_merchant_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='支付宝配置表';
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
-- =====================================================
|
||||||
|
-- 第三方用户 OpenId 映射表
|
||||||
|
-- 统一管理微信/支付宝等各家 openId/unionId
|
||||||
|
-- =====================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS `sys_user_third_openid` (
|
||||||
|
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
|
`user_id` BIGINT NOT NULL COMMENT '系统用户ID',
|
||||||
|
`provider` VARCHAR(16) NOT NULL COMMENT '第三方平台:WECHAT / ALIPAY',
|
||||||
|
`app_id` VARCHAR(64) NOT NULL COMMENT '第三方应用ID',
|
||||||
|
`open_id` VARCHAR(128) NOT NULL COMMENT '第三方用户唯一标识',
|
||||||
|
`union_id` VARCHAR(128) DEFAULT NULL COMMENT '第三方 unionId(微信开放平台 unionId / 支付宝 PID 下 union_id)',
|
||||||
|
`mobile` VARCHAR(20) DEFAULT NULL COMMENT '手机号',
|
||||||
|
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_provider_appid_openid` (`provider`, `app_id`, `open_id`),
|
||||||
|
KEY `idx_user_provider` (`user_id`, `provider`),
|
||||||
|
KEY `idx_provider_unionid` (`provider`, `union_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='第三方用户OpenId映射表';
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>com.zlt</groupId>
|
||||||
|
<artifactId>zlt-commons</artifactId>
|
||||||
|
<version>6.0.0</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>zlt-alipay-spring-boot-starter</artifactId>
|
||||||
|
<description>支付宝 Spring Boot 启动器(SDK 工厂 + 登录/支付/退款服务)</description>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- 支付宝核心模块 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.zlt</groupId>
|
||||||
|
<artifactId>zlt-alipay-common-core</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- 支付宝 SDK -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alipay.sdk</groupId>
|
||||||
|
<artifactId>alipay-sdk-java</artifactId>
|
||||||
|
<version>4.40.816.ALL</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Spring Boot 相关依赖 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||||
|
<optional>true</optional>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-autoconfigure</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
package com.central.alipay.config;
|
||||||
|
|
||||||
|
import com.central.alipay.notify.AlipayNotifyVerifier;
|
||||||
|
import com.central.alipay.service.AlipayLoginService;
|
||||||
|
import com.central.alipay.service.AlipayPayService;
|
||||||
|
import com.central.alipay.service.AlipayQrcodeService;
|
||||||
|
import com.central.alipay.service.AlipayRefundService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝模块自动配置
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Configuration
|
||||||
|
@EnableConfigurationProperties(AlipayProperties.class)
|
||||||
|
@AutoConfigureAfter({FeignAutoConfiguration.class, WebMvcAutoConfiguration.class})
|
||||||
|
@ConditionalOnProperty(prefix = "zlt.alipay", name = "enabled", havingValue = "true", matchIfMissing = true)
|
||||||
|
public class AlipayAutoConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AlipayClientFactory alipayClientFactory() {
|
||||||
|
log.info("AlipayClientFactory 已加载");
|
||||||
|
return new AlipayClientFactory();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AlipayLoginService alipayLoginService() {
|
||||||
|
log.info("AlipayLoginService 已加载");
|
||||||
|
return new AlipayLoginService();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AlipayPayService alipayPayService() {
|
||||||
|
log.info("AlipayPayService 已加载");
|
||||||
|
return new AlipayPayService();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AlipayRefundService alipayRefundService() {
|
||||||
|
log.info("AlipayRefundService 已加载");
|
||||||
|
return new AlipayRefundService();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AlipayQrcodeService alipayQrcodeService() {
|
||||||
|
log.info("AlipayQrcodeService 已加载");
|
||||||
|
return new AlipayQrcodeService();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AlipayNotifyVerifier alipayNotifyVerifier() {
|
||||||
|
log.info("AlipayNotifyVerifier 已加载");
|
||||||
|
return new AlipayNotifyVerifier();
|
||||||
|
}
|
||||||
|
}
|
||||||
+157
@@ -0,0 +1,157 @@
|
|||||||
|
package com.central.alipay.config;
|
||||||
|
|
||||||
|
import com.alipay.api.AlipayApiException;
|
||||||
|
import com.alipay.api.AlipayClient;
|
||||||
|
import com.alipay.api.CertAlipayRequest;
|
||||||
|
import com.alipay.api.DefaultAlipayClient;
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import com.central.alipay.feign.AlipayConfigService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝客户端工厂(多租户 AlipayClient 缓存)
|
||||||
|
* <p>
|
||||||
|
* 对标 WxPayConfigFactory 的设计模式:
|
||||||
|
* - ConcurrentHashMap 按 (appId, subMerchantId) 缓存 AlipayClient
|
||||||
|
* - 支持普通直连模式与 ISV(服务商)模式
|
||||||
|
* - 支持普通公钥模式与证书模式
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
public class AlipayClientFactory {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private AlipayConfigService alipayConfigService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private AlipayProperties alipayProperties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AlipayClient 缓存(key: appId + "::" + (subMerchantId|""))
|
||||||
|
*/
|
||||||
|
private final Map<String, AlipayClient> clientCache = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据租户ID获取 AlipayClient(直连模式)
|
||||||
|
*/
|
||||||
|
public AlipayClient getClient(String tenantId) {
|
||||||
|
AlipayConfig config = alipayConfigService.getConfig("PAY", tenantId);
|
||||||
|
if (config == null) {
|
||||||
|
throw new RuntimeException("支付宝支付配置不存在,tenantId: " + tenantId);
|
||||||
|
}
|
||||||
|
return createAlipayClient(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据子商户号获取 AlipayClient(ISV 模式)
|
||||||
|
*/
|
||||||
|
public AlipayClient getClientBySubMerchantId(String subMerchantId) {
|
||||||
|
AlipayConfig config = alipayConfigService.getConfigBySubMerchantId(subMerchantId);
|
||||||
|
if (config == null) {
|
||||||
|
throw new RuntimeException("未找到子商户支付宝配置: " + subMerchantId);
|
||||||
|
}
|
||||||
|
return createAlipayClient(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据 AlipayConfig 创建(或从缓存中读取)AlipayClient
|
||||||
|
*/
|
||||||
|
public AlipayClient createAlipayClient(AlipayConfig config) {
|
||||||
|
String cacheKey = buildCacheKey(config);
|
||||||
|
return clientCache.computeIfAbsent(cacheKey, k -> doBuild(config));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除指定 appId+subMerchantId 的缓存(配置变更时调用)
|
||||||
|
*/
|
||||||
|
public void clearCache(AlipayConfig config) {
|
||||||
|
String key = buildCacheKey(config);
|
||||||
|
clientCache.remove(key);
|
||||||
|
log.info("清除支付宝客户端缓存,key: {}", key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除所有缓存
|
||||||
|
*/
|
||||||
|
public void clearAllCache() {
|
||||||
|
clientCache.clear();
|
||||||
|
log.info("清除所有支付宝客户端缓存");
|
||||||
|
}
|
||||||
|
|
||||||
|
private String buildCacheKey(AlipayConfig config) {
|
||||||
|
String sub = config.getSubMerchantId() != null ? config.getSubMerchantId() : "";
|
||||||
|
return config.getAppId() + "::" + sub;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AlipayClient doBuild(AlipayConfig config) {
|
||||||
|
String gatewayUrl = config.getGatewayUrl() != null
|
||||||
|
? config.getGatewayUrl() : alipayProperties.getGatewayUrl();
|
||||||
|
String signType = config.getSignType() != null
|
||||||
|
? config.getSignType() : alipayProperties.getSignType();
|
||||||
|
String charset = config.getCharset() != null
|
||||||
|
? config.getCharset() : alipayProperties.getCharset();
|
||||||
|
String format = config.getFormat() != null
|
||||||
|
? config.getFormat() : alipayProperties.getFormat();
|
||||||
|
|
||||||
|
String appPrivateKey = config.getAppPrivateKey();
|
||||||
|
if (appPrivateKey == null || appPrivateKey.isEmpty()) {
|
||||||
|
throw new RuntimeException("应用私钥不能为空,appId: " + config.getAppId());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Boolean.TRUE.equals(config.getCertMode())) {
|
||||||
|
return buildCertClient(config, gatewayUrl, signType, charset, format, appPrivateKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
String alipayPublicKey = config.getAlipayPublicKey();
|
||||||
|
if (alipayPublicKey == null || alipayPublicKey.isEmpty()) {
|
||||||
|
throw new RuntimeException("支付宝公钥不能为空,appId: " + config.getAppId());
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("创建支付宝客户端(公钥模式),appId: {}, subMerchantId: {}",
|
||||||
|
config.getAppId(), config.getSubMerchantId());
|
||||||
|
return new DefaultAlipayClient(
|
||||||
|
gatewayUrl,
|
||||||
|
config.getAppId(),
|
||||||
|
appPrivateKey,
|
||||||
|
format,
|
||||||
|
charset,
|
||||||
|
alipayPublicKey,
|
||||||
|
signType
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private AlipayClient buildCertClient(AlipayConfig config,
|
||||||
|
String gatewayUrl, String signType, String charset,
|
||||||
|
String format, String appPrivateKey) {
|
||||||
|
if (config.getAppCertPath() == null || config.getAlipayCertPath() == null
|
||||||
|
|| config.getAlipayRootCertPath() == null) {
|
||||||
|
throw new RuntimeException("证书模式下 appCertPath/alipayCertPath/alipayRootCertPath 不能为空, appId: "
|
||||||
|
+ config.getAppId());
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
CertAlipayRequest req = new CertAlipayRequest();
|
||||||
|
req.setServerUrl(gatewayUrl);
|
||||||
|
req.setAppId(config.getAppId());
|
||||||
|
req.setPrivateKey(appPrivateKey);
|
||||||
|
req.setFormat(format);
|
||||||
|
req.setCharset(charset);
|
||||||
|
req.setSignType(signType);
|
||||||
|
req.setCertPath(config.getAppCertPath());
|
||||||
|
req.setAlipayPublicCertPath(config.getAlipayCertPath());
|
||||||
|
req.setRootCertPath(config.getAlipayRootCertPath());
|
||||||
|
// encryptKey 在 SDK 4.38+ 已从 CertAlipayRequest 移除,
|
||||||
|
// 加解密 Key 需通过 DefaultAlipayClient 构造后单独设置或走支付宝后台配置
|
||||||
|
log.info("创建支付宝客户端(证书模式),appId: {}, subMerchantId: {}",
|
||||||
|
config.getAppId(), config.getSubMerchantId());
|
||||||
|
return new DefaultAlipayClient(req);
|
||||||
|
} catch (AlipayApiException e) {
|
||||||
|
throw new RuntimeException("证书模式 AlipayClient 创建失败: " + e.getErrMsg(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
package com.central.alipay.config;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import java.security.KeyFactory;
|
||||||
|
import java.security.PrivateKey;
|
||||||
|
import java.security.spec.PKCS8EncodedKeySpec;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝私钥工具类
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
public class AlipayPrivateKeyUtils {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 PKCS8 格式的私钥字符串加载 PrivateKey
|
||||||
|
*/
|
||||||
|
public static PrivateKey getPrivateKey(String privateKeyStr) {
|
||||||
|
if (privateKeyStr == null || privateKeyStr.trim().isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("私钥字符串不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
String privateKeyPEM = privateKeyStr
|
||||||
|
.replace("-----BEGIN PRIVATE KEY-----", "")
|
||||||
|
.replace("-----END PRIVATE KEY-----", "")
|
||||||
|
.replaceAll("\\s+", "");
|
||||||
|
|
||||||
|
byte[] decoded = Base64.getDecoder().decode(privateKeyPEM);
|
||||||
|
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
|
||||||
|
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||||
|
return keyFactory.generatePrivate(keySpec);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
log.error("私钥格式错误: {}", e.getMessage());
|
||||||
|
throw new IllegalArgumentException("私钥格式错误: " + e.getMessage(), e);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("解析私钥失败", e);
|
||||||
|
throw new RuntimeException("解析私钥失败: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移除 PEM 头尾标记并去除空白
|
||||||
|
*/
|
||||||
|
public static String cleanPemKey(String key) {
|
||||||
|
if (key == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return key.replace("-----BEGIN PRIVATE KEY-----", "")
|
||||||
|
.replace("-----END PRIVATE KEY-----", "")
|
||||||
|
.replace("-----BEGIN PUBLIC KEY-----", "")
|
||||||
|
.replace("-----END PUBLIC KEY-----", "")
|
||||||
|
.replaceAll("\\s+", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
+63
@@ -0,0 +1,63 @@
|
|||||||
|
package com.central.alipay.notify;
|
||||||
|
|
||||||
|
import com.alipay.api.AlipayApiException;
|
||||||
|
import com.alipay.api.internal.util.AlipaySignature;
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝异步回调验签器
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class AlipayNotifyVerifier {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证支付宝回调签名
|
||||||
|
* <p>
|
||||||
|
* 自动根据配置选择验签方式:
|
||||||
|
* - certMode=true:使用 rsaCertCheckV1(基于支付宝公钥证书路径 alipayCertPath)
|
||||||
|
* - certMode=false:使用 rsaCheckV1(基于支付宝公钥 alipayPublicKey)
|
||||||
|
*
|
||||||
|
* @param params 回调参数(从 HttpServletRequest 收集)
|
||||||
|
* @param config 支付宝配置
|
||||||
|
* @return true-验签通过,false-验签失败
|
||||||
|
*/
|
||||||
|
public boolean verify(Map<String, String> params, AlipayConfig config) {
|
||||||
|
try {
|
||||||
|
String signType = config.getSignType() != null ? config.getSignType() : "RSA2";
|
||||||
|
String charset = config.getCharset() != null ? config.getCharset() : "UTF-8";
|
||||||
|
|
||||||
|
boolean result;
|
||||||
|
if (Boolean.TRUE.equals(config.getCertMode())) {
|
||||||
|
String alipayCertPath = config.getAlipayCertPath();
|
||||||
|
if (alipayCertPath == null || alipayCertPath.isEmpty()) {
|
||||||
|
log.error("证书模式下 alipayCertPath 为空,无法验签, appId: {}", config.getAppId());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
result = AlipaySignature.rsaCertCheckV1(params, alipayCertPath, charset, signType);
|
||||||
|
} else {
|
||||||
|
String alipayPublicKey = config.getAlipayPublicKey();
|
||||||
|
if (alipayPublicKey == null || alipayPublicKey.isEmpty()) {
|
||||||
|
log.error("支付宝公钥为空,无法验签, appId: {}", config.getAppId());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
result = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType);
|
||||||
|
}
|
||||||
|
if (!result) {
|
||||||
|
log.warn("支付宝回调验签失败, appId: {}, signType: {}, certMode: {}",
|
||||||
|
config.getAppId(), signType, config.getCertMode());
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
} catch (AlipayApiException e) {
|
||||||
|
log.error("支付宝回调验签异常", e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+182
@@ -0,0 +1,182 @@
|
|||||||
|
package com.central.alipay.service;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.alipay.api.AlipayApiException;
|
||||||
|
import com.alipay.api.AlipayClient;
|
||||||
|
import com.alipay.api.internal.util.AlipayEncrypt;
|
||||||
|
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
|
||||||
|
import com.alipay.api.request.AlipayUserInfoShareRequest;
|
||||||
|
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
|
||||||
|
import com.alipay.api.response.AlipayUserInfoShareResponse;
|
||||||
|
import com.central.alipay.config.AlipayClientFactory;
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝小程序登录服务
|
||||||
|
* <p>
|
||||||
|
* 封装支付宝 code → user_id 的完整流程:
|
||||||
|
* 1. alipay.system.oauth.token 用 auth_code 换 access_token + user_id
|
||||||
|
* 2. alipay.user.info.share 获取用户信息(unionId/avatar/nickName,不含手机号)
|
||||||
|
* 3. 可选:本地 AES 解密手机号(前端 my.getPhoneNumber 返回的 response 字段,使用商家 encryptKey 解密)
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class AlipayLoginService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private AlipayClientFactory clientFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 小程序登录结果
|
||||||
|
*/
|
||||||
|
public static class AlipayLoginResult {
|
||||||
|
private String userId;
|
||||||
|
private String openId;
|
||||||
|
private String unionId;
|
||||||
|
private String mobile;
|
||||||
|
private String avatar;
|
||||||
|
private String nickName;
|
||||||
|
|
||||||
|
public AlipayLoginResult(String userId, String openId) {
|
||||||
|
this.userId = userId;
|
||||||
|
this.openId = openId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUserId() { return userId; }
|
||||||
|
public void setUserId(String userId) { this.userId = userId; }
|
||||||
|
public String getOpenId() { return openId; }
|
||||||
|
public void setOpenId(String openId) { this.openId = openId; }
|
||||||
|
public String getUnionId() { return unionId; }
|
||||||
|
public void setUnionId(String unionId) { this.unionId = unionId; }
|
||||||
|
public String getMobile() { return mobile; }
|
||||||
|
public void setMobile(String mobile) { this.mobile = mobile; }
|
||||||
|
public String getAvatar() { return avatar; }
|
||||||
|
public void setAvatar(String avatar) { this.avatar = avatar; }
|
||||||
|
public String getNickName() { return nickName; }
|
||||||
|
public void setNickName(String nickName) { this.nickName = nickName; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过小程序 auth_code 换取用户标识
|
||||||
|
*
|
||||||
|
* @param config 支付宝配置
|
||||||
|
* @param code 小程序 auth_code
|
||||||
|
* @return 登录结果(userId, openId, unionId)
|
||||||
|
*/
|
||||||
|
public AlipayLoginResult code2userId(AlipayConfig config, String code) {
|
||||||
|
AlipayClient client = clientFactory.createAlipayClient(config);
|
||||||
|
|
||||||
|
// 1. 用 auth_code 换取 access_token
|
||||||
|
AlipaySystemOauthTokenRequest tokenRequest = new AlipaySystemOauthTokenRequest();
|
||||||
|
tokenRequest.setCode(code);
|
||||||
|
tokenRequest.setGrantType("authorization_code");
|
||||||
|
|
||||||
|
AlipaySystemOauthTokenResponse tokenResponse;
|
||||||
|
try {
|
||||||
|
tokenResponse = client.execute(tokenRequest);
|
||||||
|
} catch (AlipayApiException e) {
|
||||||
|
log.error("支付宝获取 access_token 失败", e);
|
||||||
|
throw new RuntimeException("支付宝登录失败: " + e.getErrMsg(), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tokenResponse.isSuccess()) {
|
||||||
|
log.error("支付宝获取 access_token 失败, subCode: {}, subMsg: {}",
|
||||||
|
tokenResponse.getSubCode(), tokenResponse.getSubMsg());
|
||||||
|
throw new RuntimeException("支付宝登录失败: " + tokenResponse.getSubMsg());
|
||||||
|
}
|
||||||
|
|
||||||
|
String accessToken = tokenResponse.getAccessToken();
|
||||||
|
String userId = tokenResponse.getUserId();
|
||||||
|
String openId = tokenResponse.getOpenId();
|
||||||
|
|
||||||
|
log.info("支付宝登录成功, userId: {}, openId: {}", userId, openId);
|
||||||
|
|
||||||
|
AlipayLoginResult result = new AlipayLoginResult(userId, openId);
|
||||||
|
|
||||||
|
// 2. 获取用户信息(union_id / avatar / nickName)
|
||||||
|
// 使用 JSON 解析 response body,兼容不同 SDK 版本的 getter 差异
|
||||||
|
// 注意:alipay.user.info.share 不返回手机号,手机号需通过 decryptPhone 单独获取
|
||||||
|
try {
|
||||||
|
AlipayUserInfoShareRequest infoRequest = new AlipayUserInfoShareRequest();
|
||||||
|
AlipayUserInfoShareResponse infoResponse = client.execute(infoRequest, accessToken);
|
||||||
|
if (infoResponse.isSuccess()) {
|
||||||
|
String body = infoResponse.getBody();
|
||||||
|
JSONObject respJson = JSONObject.parseObject(body);
|
||||||
|
|
||||||
|
// 从响应 JSON 中提取 alipay_user_info_share_response 节点
|
||||||
|
JSONObject shareResp = respJson.getJSONObject("alipay_user_info_share_response");
|
||||||
|
if (shareResp != null && "10000".equals(shareResp.getString("code"))) {
|
||||||
|
result.setUnionId(shareResp.getString("union_id"));
|
||||||
|
result.setAvatar(shareResp.getString("avatar"));
|
||||||
|
result.setNickName(shareResp.getString("nick_name"));
|
||||||
|
log.info("支付宝用户信息获取成功, unionId: {}", result.getUnionId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("获取支付宝用户信息失败(不影响登录流程): {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解密支付宝小程序加密手机号
|
||||||
|
* <p>
|
||||||
|
* 前端 my.getPhoneNumber 回调返回 { response, sign },其中 response 是
|
||||||
|
* 一段已用商家 AES 密钥加密的密文(或一个外层 JSON 包裹该密文)。
|
||||||
|
* 支付宝官方对小程序手机号采用商家本地 AES 解密的方式(不存在
|
||||||
|
* alipay.user.phone.number.decrypt 这个开放接口),密钥即 AlipayConfig.encryptKey。
|
||||||
|
*
|
||||||
|
* @param config 支付宝配置(须设置 encryptKey)
|
||||||
|
* @param encryptedResponse my.getPhoneNumber 返回的 response 字段
|
||||||
|
* @return 明文手机号;解密失败返回 null
|
||||||
|
*/
|
||||||
|
public String decryptPhone(AlipayConfig config, String encryptedResponse) {
|
||||||
|
if (encryptedResponse == null || encryptedResponse.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (config == null || config.getEncryptKey() == null || config.getEncryptKey().isEmpty()) {
|
||||||
|
log.error("支付宝手机号解密失败:缺少 AES 加解密密钥(encryptKey)");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 兼容两种入参:完整外层 JSON 报文 或 已提取的内层密文
|
||||||
|
String cipherText = encryptedResponse.trim();
|
||||||
|
if (cipherText.startsWith("{")) {
|
||||||
|
try {
|
||||||
|
JSONObject outer = JSONObject.parseObject(cipherText);
|
||||||
|
String inner = outer.getString("response");
|
||||||
|
if (inner != null && !inner.isEmpty()) {
|
||||||
|
cipherText = inner;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("支付宝手机号解密:外层 JSON 解析失败,按密文直接解密,msg={}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String charset = (config.getCharset() == null || config.getCharset().isEmpty())
|
||||||
|
? "UTF-8" : config.getCharset();
|
||||||
|
|
||||||
|
try {
|
||||||
|
String plain = AlipayEncrypt.decryptContent(cipherText, "AES", config.getEncryptKey(), charset);
|
||||||
|
JSONObject decryptResp = JSONObject.parseObject(plain);
|
||||||
|
if (decryptResp == null || !"10000".equals(decryptResp.getString("code"))) {
|
||||||
|
log.error("支付宝手机号解密结果非成功, body: {}", plain);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return decryptResp.getString("mobile");
|
||||||
|
} catch (AlipayApiException e) {
|
||||||
|
log.error("支付宝手机号 AES 解密异常", e);
|
||||||
|
return null;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("解析支付宝手机号解密结果异常", e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+161
@@ -0,0 +1,161 @@
|
|||||||
|
package com.central.alipay.service;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.alipay.api.AlipayApiException;
|
||||||
|
import com.alipay.api.AlipayClient;
|
||||||
|
import com.alipay.api.request.AlipayTradeCloseRequest;
|
||||||
|
import com.alipay.api.request.AlipayTradeCreateRequest;
|
||||||
|
import com.alipay.api.request.AlipayTradeQueryRequest;
|
||||||
|
import com.alipay.api.response.AlipayTradeCloseResponse;
|
||||||
|
import com.alipay.api.response.AlipayTradeCreateResponse;
|
||||||
|
import com.alipay.api.response.AlipayTradeQueryResponse;
|
||||||
|
import com.central.alipay.config.AlipayClientFactory;
|
||||||
|
import com.central.alipay.entity.AlipayConfig;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 支付宝支付服务
|
||||||
|
* <p>
|
||||||
|
* 封装支付宝交易相关接口:
|
||||||
|
* - alipay.trade.create(小程序下单)
|
||||||
|
* - alipay.trade.query(订单查询)
|
||||||
|
* - alipay.trade.close(订单关闭)
|
||||||
|
*
|
||||||
|
* @author duzhichao
|
||||||
|
* @date 2026-05-12
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class AlipayPayService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private AlipayClientFactory clientFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一下单请求参数
|
||||||
|
*/
|
||||||
|
public static class AlipayPayRequest {
|
||||||
|
private String outTradeNo;
|
||||||
|
private String totalAmount;
|
||||||
|
private String subject;
|
||||||
|
private String buyerId;
|
||||||
|
private String body;
|
||||||
|
private String timeoutExpress;
|
||||||
|
private String subMerchantId; // ISV 模式
|
||||||
|
|
||||||
|
public String getOutTradeNo() { return outTradeNo; }
|
||||||
|
public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; }
|
||||||
|
public String getTotalAmount() { return totalAmount; }
|
||||||
|
public void setTotalAmount(String totalAmount) { this.totalAmount = totalAmount; }
|
||||||
|
public String getSubject() { return subject; }
|
||||||
|
public void setSubject(String subject) { this.subject = subject; }
|
||||||
|
public String getBuyerId() { return buyerId; }
|
||||||
|
public void setBuyerId(String buyerId) { this.buyerId = buyerId; }
|
||||||
|
public String getBody() { return body; }
|
||||||
|
public void setBody(String body) { this.body = body; }
|
||||||
|
public String getTimeoutExpress() { return timeoutExpress; }
|
||||||
|
public void setTimeoutExpress(String timeoutExpress) { this.timeoutExpress = timeoutExpress; }
|
||||||
|
public String getSubMerchantId() { return subMerchantId; }
|
||||||
|
public void setSubMerchantId(String subMerchantId) { this.subMerchantId = subMerchantId; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一下单(alipay.trade.create)
|
||||||
|
* <p>
|
||||||
|
* 支付宝小程序通过此接口获取 tradeNo,前端再调用 my.tradePay 完成支付
|
||||||
|
*/
|
||||||
|
public AlipayTradeCreateResponse create(AlipayConfig config, AlipayPayRequest req) {
|
||||||
|
AlipayClient client = clientFactory.createAlipayClient(config);
|
||||||
|
|
||||||
|
AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
|
||||||
|
|
||||||
|
JSONObject bizContent = new JSONObject();
|
||||||
|
bizContent.put("out_trade_no", req.getOutTradeNo());
|
||||||
|
bizContent.put("total_amount", req.getTotalAmount());
|
||||||
|
bizContent.put("subject", req.getSubject());
|
||||||
|
// 小程序内拉起 my.tradePay 的标准 product_code,缺失会导致部分场景下单失败
|
||||||
|
bizContent.put("product_code", "JSAPI_PAY");
|
||||||
|
if (req.getBuyerId() != null) {
|
||||||
|
bizContent.put("buyer_id", req.getBuyerId());
|
||||||
|
}
|
||||||
|
if (req.getBody() != null) {
|
||||||
|
bizContent.put("body", req.getBody());
|
||||||
|
}
|
||||||
|
if (req.getTimeoutExpress() != null) {
|
||||||
|
bizContent.put("timeout_express", req.getTimeoutExpress());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ISV 模式:设置子商户信息
|
||||||
|
if (Boolean.TRUE.equals(config.getIsServiceMode()) && req.getSubMerchantId() != null) {
|
||||||
|
JSONObject extendParams = new JSONObject();
|
||||||
|
extendParams.put("sub_merchant_id", req.getSubMerchantId());
|
||||||
|
bizContent.put("extend_params", extendParams);
|
||||||
|
}
|
||||||
|
|
||||||
|
request.setBizContent(bizContent.toJSONString());
|
||||||
|
|
||||||
|
// ISV 模式:设置 app_auth_token
|
||||||
|
if (Boolean.TRUE.equals(config.getIsServiceMode()) && config.getAuthToken() != null) {
|
||||||
|
request.putOtherTextParam("app_auth_token", config.getAuthToken());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config.getNotifyUrl() != null) {
|
||||||
|
request.setNotifyUrl(config.getNotifyUrl());
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
AlipayTradeCreateResponse response = client.execute(request);
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
log.info("支付宝下单成功, outTradeNo: {}, tradeNo: {}",
|
||||||
|
response.getOutTradeNo(), response.getTradeNo());
|
||||||
|
} else {
|
||||||
|
log.error("支付宝下单失败, subCode: {}, subMsg: {}",
|
||||||
|
response.getSubCode(), response.getSubMsg());
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
} catch (AlipayApiException e) {
|
||||||
|
log.error("支付宝下单异常", e);
|
||||||
|
throw new RuntimeException("支付宝下单失败: " + e.getErrMsg(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订单查询(alipay.trade.query)
|
||||||
|
*/
|
||||||
|
public AlipayTradeQueryResponse query(AlipayConfig config, String outTradeNo) {
|
||||||
|
AlipayClient client = clientFactory.createAlipayClient(config);
|
||||||
|
|
||||||
|
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
|
||||||
|
JSONObject bizContent = new JSONObject();
|
||||||
|
bizContent.put("out_trade_no", outTradeNo);
|
||||||
|
request.setBizContent(bizContent.toJSONString());
|
||||||
|
|
||||||
|
try {
|
||||||
|
return client.execute(request);
|
||||||
|
} catch (AlipayApiException e) {
|
||||||
|
log.error("支付宝订单查询异常", e);
|
||||||
|
throw new RuntimeException("支付宝订单查询失败: " + e.getErrMsg(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订单关闭(alipay.trade.close)
|
||||||
|
*/
|
||||||
|
public AlipayTradeCloseResponse close(AlipayConfig config, String outTradeNo) {
|
||||||
|
AlipayClient client = clientFactory.createAlipayClient(config);
|
||||||
|
|
||||||
|
AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
|
||||||
|
JSONObject bizContent = new JSONObject();
|
||||||
|
bizContent.put("out_trade_no", outTradeNo);
|
||||||
|
request.setBizContent(bizContent.toJSONString());
|
||||||
|
|
||||||
|
try {
|
||||||
|
return client.execute(request);
|
||||||
|
} catch (AlipayApiException e) {
|
||||||
|
log.error("支付宝订单关闭异常", e);
|
||||||
|
throw new RuntimeException("支付宝订单关闭失败: " + e.getErrMsg(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user