Compare commits

...
3 Commits
Author SHA1 Message Date
lik 983e55b672 fix(payment): 增加支付配置诊断并拦截取消中的订单
- isConfigured 拆出 getConfigDiagnostics,日志列出缺失项且不输出密钥
- 证书路径支持 WXPAY_PRIVATE_KEY_PATH / WXPAY_PUBLIC_KEY_PATH 覆盖
- 已申请取消或已取消的订单不再回刷 paid,也不允许发起支付
- 发起支付与查询退款未配置时输出诊断日志
2026-11-05 18:54:59 +08:00
lik fb1210106e refactor(escort): 取消状态与 status 解耦
- 新增 cancelStatus(none/requested/cancelled),status 只描述服务生命周期
- record_state 拆分 canCancelTransition 与 CANCEL_TRANSITIONS
- 管理端 Agent 工具、查询工具与接口层统一走取消状态机
- 列表默认隐藏已取消订单,支持 cancelStatus / includeCancelled 筛选
2026-11-05 18:54:52 +08:00
lik 23b9de16a6 feat:增加微信支付功能 2026-11-05 16:31:51 +08:00
18 changed files with 2444 additions and 73 deletions
-1
View File
@@ -2,7 +2,6 @@
/logs/ /logs/
/data/ /data/
.env .env
conf.json
# 临时调试文件,正式测试请放 test/ # 临时调试文件,正式测试请放 test/
/tmp_* /tmp_*
/tmp/ /tmp/
+1 -1
View File
@@ -55,7 +55,7 @@ class EscortAdminPrompts {
1. 先判定是查询、修改还是问规则;缺关键信息(订单或患者、要改成什么、时间范围)先用一句话确认,不猜。 1. 先判定是查询、修改还是问规则;缺关键信息(订单或患者、要改成什么、时间范围)先用一句话确认,不猜。
2. 修改前先用查询定位记录,只用 escort_record_set 改用户明确要求的字段,其余字段不动。 2. 修改前先用查询定位记录,只用 escort_record_set 改用户明确要求的字段,其余字段不动。
3. 取消、改期、改金额、退款等不可逆或影响结算的操作,先复述"要改什么"并等确认。 3. 取消、改期、改金额、退款等不可逆或影响结算的操作,先复述"要改什么"并等确认。
4. 状态只能按规则流转:pending→confirmed→in_progress→completed;pending/confirmed 可转 cancelled;completed、cancelled 为终态不可再改。被拒绝时如实说明当前状态和可选状态,不绕过、不空转重试。 4. 服务状态只能按规则流转:pending→confirmed→in_progress→completed,completed 为终态不可再改。取消与状态解耦,用 cancelStatus 单独表达:none→requested→cancelled;已申请取消或已取消的订单不再推进服务状态。被拒绝时如实说明当前状态和可选状态,不绕过、不空转重试。
5. 结果回报:改完一句说清"改了什么、当前状态";失败说清原因和下一步。 5. 结果回报:改完一句说清"改了什么、当前状态";失败说清原因和下一步。
6. 无工具支持的数据(结算汇总、财务报表、线下沟通记录)不推断、不估算,明确说明查不到并指向对应页面或同事。 6. 无工具支持的数据(结算汇总、财务报表、线下沟通记录)不推断、不估算,明确说明查不到并指向对应页面或同事。
@@ -2,10 +2,15 @@ import { tool } from "@langchain/core/tools";
import { z } from "zod"; import { z } from "zod";
import mongoose from "mongoose"; import mongoose from "mongoose";
import { DBModel } from "../../../../../models/index.js"; import { DBModel } from "../../../../../models/index.js";
import { canTransition, STATUS_TRANSITIONS } from "../../../../../utils/record_state.js"; import {
canTransition,
canCancelTransition,
STATUS_TRANSITIONS,
CANCEL_STATUS_VALUES,
} from "../../../../../utils/record_state.js";
const escortRecordSetTool = tool( const escortRecordSetTool = tool(
async ({ orderId, status, notes, payment }) => { async ({ orderId, status, cancelStatus, notes, payment }) => {
try { try {
if (!orderId) { if (!orderId) {
return { return {
@@ -32,8 +37,37 @@ const escortRecordSetTool = tool(
// 状态迁移必须与接口层同一套规则:否则 Agent 能把已完成订单改回进行中, // 状态迁移必须与接口层同一套规则:否则 Agent 能把已完成订单改回进行中,
// 绕过状态机并造成费用/服务记录不一致 // 绕过状态机并造成费用/服务记录不一致
const update = {}; const update = {};
// 兼容旧数据:取消曾存放在 status 中
const currentCancel = record.status === "cancelled"
? "cancelled"
: (record.cancelStatus || "none");
// 取消与 status 解耦,单独走取消状态机
if (cancelStatus !== undefined && cancelStatus !== currentCancel) {
if (!canCancelTransition(currentCancel, cancelStatus)) {
return {
success: false,
error: `Illegal cancel status transition: ${currentCancel} -> ${cancelStatus}`,
};
}
update.cancelStatus = cancelStatus;
if (cancelStatus === "requested") update.cancelRequestedAt = new Date();
if (cancelStatus === "cancelled") update.cancelledAt = new Date();
}
if (status !== undefined && status !== record.status) { if (status !== undefined && status !== record.status) {
if (currentCancel !== "none") {
return {
success: false,
error: "Order is cancelling or cancelled; service status cannot change.",
};
}
if (update.cancelStatus) {
return {
success: false,
error: "Do not update service status and cancel status in the same request.",
};
}
if (!canTransition(record.status, status)) { if (!canTransition(record.status, status)) {
const allowed = STATUS_TRANSITIONS[record.status] || []; const allowed = STATUS_TRANSITIONS[record.status] || [];
return { return {
@@ -75,6 +109,11 @@ const escortRecordSetTool = tool(
// 以读取时的状态作为更新条件,避免并发下跳过中间状态;同时排除已软删除的订单 // 以读取时的状态作为更新条件,避免并发下跳过中间状态;同时排除已软删除的订单
const filter = { _id: record._id, deletedAt: null }; const filter = { _id: record._id, deletedAt: null };
if (status !== undefined && status !== record.status) filter.status = record.status; if (status !== undefined && status !== record.status) filter.status = record.status;
if (cancelStatus !== undefined && cancelStatus !== currentCancel) {
filter.cancelStatus = currentCancel === "none"
? { $in: ["none", null] }
: currentCancel;
}
const updatedRecord = await DBModel.EscortRecord.findOneAndUpdate( const updatedRecord = await DBModel.EscortRecord.findOneAndUpdate(
filter, filter,
@@ -103,16 +142,22 @@ const escortRecordSetTool = tool(
{ {
name: "escort_record_set", name: "escort_record_set",
description: description:
"Update escort record fields by record ID (_id). Supports updating status, notes (patientNote, escortNote, medicalSummary), and payment (totalFee, paidFee, status). Only provided fields will be updated.", "Update escort record fields by record ID (_id). Supports updating service status, cancel status (none/requested/cancelled), notes (patientNote, escortNote, medicalSummary), and payment (totalFee, paidFee, status). Only provided fields will be updated.",
schema: z.object({ schema: z.object({
orderId: z orderId: z
.string() .string()
.describe("Record ID (_id) used as the lookup key"), .describe("Record ID (_id) used as the lookup key"),
status: z status: z
.enum(["pending", "confirmed", "in_progress", "completed", "cancelled"]) .enum(["pending", "confirmed", "in_progress", "completed"])
.optional() .optional()
.describe( .describe(
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)" "Service status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成). Cancellation is controlled by cancelStatus."
),
cancelStatus: z
.enum(CANCEL_STATUS_VALUES)
.optional()
.describe(
"Cancel status: none (未取消), requested (待取消), cancelled (已取消)"
), ),
notes: z notes: z
.object({ .object({
@@ -59,13 +59,17 @@ function buildAttendantEscortRecordSetTool({ attendantId = null } = {}) {
}; };
} }
if ((record.cancelStatus || "none") !== "none" || record.status === "cancelled") {
return {
success: false,
error: "订单已取消或正在取消,不能修改。",
};
}
if (!EDITABLE_RECORD_STATUS.includes(record.status)) { if (!EDITABLE_RECORD_STATUS.includes(record.status)) {
return { return {
success: false, success: false,
error: error: "订单还未确认或已结束,不能操作。",
record.status === "pending"
? "订单还未确认,不能操作,请联系管理员确认。"
: "订单已取消,不能修改。",
}; };
} }
@@ -3,9 +3,12 @@ import { z } from "zod";
import { DBModel } from "../../../../../models/index.js"; import { DBModel } from "../../../../../models/index.js";
import { escapeRegex, parseObjectId } from "../utils.js"; import { escapeRegex, parseObjectId } from "../utils.js";
const STATUS_VALUES = ["pending", "confirmed", "in_progress", "completed", "cancelled"]; const STATUS_VALUES = ["pending", "confirmed", "in_progress", "completed"];
const STATUS_DESC = const STATUS_DESC =
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)"; "Service status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成). Cancellation is a separate cancelStatus.";
const CANCEL_STATUS_VALUES = ["none", "requested", "cancelled"];
const CANCEL_STATUS_DESC =
"Cancel status: none (未取消), requested (待取消), cancelled (已取消)";
/** /**
* 严格解析 YYYY-MM-DD(东八区零点) * 严格解析 YYYY-MM-DD(东八区零点)
@@ -41,6 +44,7 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false, boundA
const shape = { const shape = {
patientName: z.string().optional().describe("Patient name for fuzzy search"), patientName: z.string().optional().describe("Patient name for fuzzy search"),
status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC), status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC),
cancelStatus: z.enum(CANCEL_STATUS_VALUES).optional().describe(CANCEL_STATUS_DESC),
page: z.number().int().min(1).optional().describe("Page number, starting from 1"), page: z.number().int().min(1).optional().describe("Page number, starting from 1"),
pageSize: z pageSize: z
.number() .number()
@@ -71,7 +75,7 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false, boundA
} }
return tool( return tool(
async ({ patientName, mobile, attendantId, dateFrom, dateTo, status, page = 1, pageSize = 20 }) => { async ({ patientName, mobile, attendantId, dateFrom, dateTo, status, cancelStatus, page = 1, pageSize = 20 }) => {
try { try {
if (!userId && !allowMobile && !attendantScope) { if (!userId && !allowMobile && !attendantScope) {
return { success: false, error: "用户未登录,无法查询陪诊记录" }; return { success: false, error: "用户未登录,无法查询陪诊记录" };
@@ -124,6 +128,16 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false, boundA
filter.status = status; filter.status = status;
} }
if (cancelStatus === "cancelled") {
// 兼容旧数据:取消曾存放在 status 中
filter.$or = [{ cancelStatus: "cancelled" }, { status: "cancelled" }];
} else if (cancelStatus) {
filter.cancelStatus = cancelStatus;
} else if (!status) {
// 与列表口径一致:未显式查询时隐藏旧数据里的 status=cancelled
filter.status = { $ne: "cancelled" };
}
// 用户端按订单归属过滤;不能用手机号作为隔离键(手机号可由用户自行修改) // 用户端按订单归属过滤;不能用手机号作为隔离键(手机号可由用户自行修改)
if (userId) { if (userId) {
filter.userId = userId; filter.userId = userId;
+91
View File
@@ -0,0 +1,91 @@
{
"app": {
"wxapp-escort": {
},
"wxapp-escort-admin": {
}
},
"wechatpay": {
"mchid": "1002880022",
"appid": "wxf73c79e16837af07",
"merchantSerial": "5C1D85FFF3C30820F4A8B71D0B3BFF153AE0A704",
"privateKeyPath": "/data/wechatpay_cert/cert/apiclient_key.pem",
"apiv3KeyEnv": "WXPAY_APIV3_KEY",
"publicKeyId": "PUB_KEY_ID_0111195467732026110200182082000003",
"publicKeyPath": "/data/wechatpay_cert/pub_key.pem",
"notifyBase": "https://api.huashengtec.com/health",
"payWindowHours": 24
},
"agent": {
"maxHistoryChars": 40000,
"dataDir": "./data",
"model": "deepseek",
"media": {
"audio": {
"rate": 16000,
"channels": 1
},
"asr": {
"provider": "dashscope",
"endpoint": "wss://dashscope.aliyuncs.com/api-ws/v1/inference",
"model": "fun-asr-realtime",
"apiKeyEnv": "ASR_KEY"
},
"image": {
"mimes": [
"image/jpeg",
"image/png",
"image/webp"
]
},
"ocr": {
"provider": "qwen",
"baseUrl": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model": "qwen-vl-ocr",
"profile": "transcribe",
"apiKeyEnv": "ASR_KEY",
"requestTimeoutMs": 60000,
"disclaimer": "本内容为图像文字识别结果,不构成诊断意见,请以医生诊断与医院报告为准。"
},
"limits": {
"maxAudioBytes": 10485760,
"maxImageBytes": 8388608
}
},
"jev": {
"apiKey": "apikey_22315d7adb1e0d0644a08e61d1046575ed87_d222aad34de06613a4c28a9a537b75b8da58b4a6a920dda7a37ea46f514827fd"
},
"deepseek": {
"apiKey": "sk-a58ccd82b7ba4ce3ac176a88c9381095",
"flashModel": "deepseek-flash",
"proModel": "deepseek-v4-pro"
},
"glm": {
"apiKey": "ed5f2ec42cb9413f87402d38321553f8.u0FalmfLdXxmst69",
"flashModel": "glm-5.3-flash",
"proModel": "glm-5.3"
},
"tavily": {
"apiKey": "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"
},
"baiduMap": {
"authToken": "sk-ap-9xcqwNJ3FyJGUoAoQoCgWLqPd5o2tJKCA1xaSMRaZT0zDo0PCFm7rczL4anUuXf5"
}
},
"mongodb": {
"str": "mongodb://ehason:Ehason_dbuser_2026@huashengtec.com:6000/?authSource=admin&appName=ws-health&retryWrites=true&w=majority",
"host": "huashengtec.com",
"option": {
"dbName": "eiot_health",
"autoIndex": true,
"maxPoolSize": 50,
"minPoolSize": 5,
"maxIdleTimeMS": 60000,
"connectTimeoutMS": 10000,
"serverSelectionTimeoutMS": 30000,
"socketTimeoutMS": 45000,
"compressors": "zlib"
},
"debug": false
}
}
+248 -34
View File
@@ -1,8 +1,15 @@
import { DBModel } from "../models/index.js"; import { DBModel } from "../models/index.js";
import services from "../resource/services.js"; import services from "../resource/services.js";
import ResponseUtil from "../utils/responseUtil.js"; import ResponseUtil from "../utils/responseUtil.js";
import logger from "../utils/logger.js";
import { isAdmin as isAdminUser, resolveEscortAdminRole } from "../utils/permissions.js"; import { isAdmin as isAdminUser, resolveEscortAdminRole } from "../utils/permissions.js";
import { canTransition, STATUS_TRANSITIONS } from "../utils/record_state.js"; import {
canTransition,
canCancelTransition,
STATUS_TRANSITIONS,
CANCEL_STATUS_VALUES,
} from "../utils/record_state.js";
import { HandlerPayment } from "./payment.js";
class HandlerEscortRecord { class HandlerEscortRecord {
constructor() { constructor() {
@@ -25,18 +32,22 @@ class HandlerEscortRecord {
"hospital.doctor", "hospital.medicalRecordNo", "schedule.date", "schedule.startTime", "hospital.doctor", "hospital.medicalRecordNo", "schedule.date", "schedule.startTime",
]; ];
static OWNER_EDITABLE_BY_STATUS = { static OWNER_EDITABLE_BY_STATUS = {
pending: ["notes.patientNote", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS], pending: ["notes.patientNote", "payment.payChannel", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
confirmed: ["notes.patientNote", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS], confirmed: ["notes.patientNote", "payment.payChannel", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
in_progress: ["notes.patientNote"], in_progress: ["notes.patientNote"],
}; };
// 用户端只能发起取消,服务完成由平台确认,避免用户端重复写入终态。 // 用户端只能发起取消,服务完成由平台确认,避免用户端重复写入终态。
// 「未确认且未收款」取消即物理删除;其余先进 cancel_requested,等陪诊师/管理员确认。 // 取消与 status 解耦:cancelStatus 为 requested 表示待确认,cancelled 表示已取消。
// 「未确认且未收款」取消即物理删除;其余先置 requested,等陪诊师/管理员确认。
// 迁移规则集中在 utils/record_state.js,与管理端 Agent 工具共用 // 迁移规则集中在 utils/record_state.js,与管理端 Agent 工具共用
// 支付方式为平台受控枚举(与 schema 一致),空串表示清除/未记录 // 支付方式为平台受控枚举(与 schema 一致),空串表示清除/未记录
static PAYMENT_METHODS = ["", "online_wechat", "offline_cash", "offline_transfer"]; static PAYMENT_METHODS = ["", "online_wechat", "offline_cash", "offline_transfer"];
// 用户下单时可选择的支付渠道:线下支付不细分现金/转账,由平台收款时补记 method
static PAY_CHANNELS = ["online_wechat", "offline"];
// 单页最大条数,避免 pageSize 传超大值一次拖库 // 单页最大条数,避免 pageSize 传超大值一次拖库
static MAX_PAGE_SIZE = 200; static MAX_PAGE_SIZE = 200;
@@ -86,6 +97,20 @@ class HandlerEscortRecord {
&& String(record.attendant.id) === String(user?._id); && String(record.attendant.id) === String(user?._id);
} }
/**
* 输出给前端的订单视图:追加支付窗口终点,供列表/详情判断「支付已超时」。
* 只派生展示字段,不写库。
* @param {Object} record mongoose 文档
* @returns {Object}
*/
static withPaymentWindow(record) {
if (!record) return record;
const plain = record.toObject ? record.toObject() : { ...record };
const end = HandlerPayment.getPayWindowEnd(plain);
plain.paymentWindowEnd = end ? end.toISOString() : null;
return plain;
}
/** /**
* 从入参中挑出白名单字段 * 从入参中挑出白名单字段
* @param {Object} body 请求体 * @param {Object} body 请求体
@@ -196,7 +221,7 @@ class HandlerEscortRecord {
async _listRecords(ctx, forceSelf) { async _listRecords(ctx, forceSelf) {
try { try {
const { status, userId, appointmentDate, healthProfileId } = ctx.request.query; const { status, userId, appointmentDate, healthProfileId, cancelStatus, includeCancelled } = ctx.request.query;
const { page, pageSize } = HandlerEscortRecord.parsePaging(ctx.request.query); const { page, pageSize } = HandlerEscortRecord.parsePaging(ctx.request.query);
const effectiveUserId = forceSelf ? ctx.state.user?._id : userId; const effectiveUserId = forceSelf ? ctx.state.user?._id : userId;
@@ -210,16 +235,28 @@ class HandlerEscortRecord {
return ResponseUtil.badRequest(ctx, "订单状态筛选值不正确"); return ResponseUtil.badRequest(ctx, "订单状态筛选值不正确");
} }
// 取消状态筛选:none / requested / cancelled
let cancelStatusArray = null;
if (cancelStatus && String(cancelStatus).length > 0) {
cancelStatusArray = String(cancelStatus).split(',').filter(Boolean);
if (cancelStatusArray.some((item) => !CANCEL_STATUS_VALUES.includes(item))) {
return ResponseUtil.badRequest(ctx, "订单取消状态筛选值不正确");
}
}
const result = await DBModel.EscortRecord.findRecordPage({ const result = await DBModel.EscortRecord.findRecordPage({
page, page,
pageSize, pageSize,
status: statusArray, status: statusArray,
cancelStatus: cancelStatusArray,
includeCancelled: ["1", "true"].includes(String(includeCancelled)),
userId: effectiveUserId, userId: effectiveUserId,
appointmentDate, appointmentDate,
healthProfileId, healthProfileId,
}); });
return ResponseUtil.success(ctx, { ...result, page, pageSize }, "查询成功"); const records = result.records.map((record) => HandlerEscortRecord.withPaymentWindow(record));
return ResponseUtil.success(ctx, { ...result, records, page, pageSize }, "查询成功");
} catch (err) { } catch (err) {
return ResponseUtil.internalError(ctx, err); return ResponseUtil.internalError(ctx, err);
} }
@@ -263,7 +300,7 @@ class HandlerEscortRecord {
return ResponseUtil.forbidden(ctx, "无权访问该订单"); return ResponseUtil.forbidden(ctx, "无权访问该订单");
} }
return ResponseUtil.success(ctx, { record }, "查询成功"); return ResponseUtil.success(ctx, { record: HandlerEscortRecord.withPaymentWindow(record) }, "查询成功");
} catch (err) { } catch (err) {
return ResponseUtil.internalError(ctx, err); return ResponseUtil.internalError(ctx, err);
} }
@@ -333,12 +370,29 @@ class HandlerEscortRecord {
payload.schedule = scheduleResult.schedule; payload.schedule = scheduleResult.schedule;
payload.shippingAddress = addressResult.shippingAddress; payload.shippingAddress = addressResult.shippingAddress;
if (idempotencyKey) payload.idempotencyKey = idempotencyKey; if (idempotencyKey) payload.idempotencyKey = idempotencyKey;
// 支付渠道:用户端只可选微信支付 / 线下支付;管理员代下单可按 method 推导
const requestedChannel = body.payment?.payChannel;
if (requestedChannel !== undefined
&& !HandlerEscortRecord.PAY_CHANNELS.includes(requestedChannel)) {
return ResponseUtil.badRequest(ctx, "支付方式不正确");
}
let payChannel;
if (HandlerEscortRecord.isAdmin(ctx.state.user)) {
payChannel = HandlerEscortRecord.PAY_CHANNELS.includes(requestedChannel)
? requestedChannel
: (body.payment?.method === "online_wechat" ? "online_wechat" : "offline");
} else {
payChannel = requestedChannel || "online_wechat";
}
payload.payment = { payload.payment = {
totalFee: Number(service.price) || 0, totalFee: Number(service.price) || 0,
paidFee: 0, paidFee: 0,
status: "unpaid", status: "unpaid",
payChannel,
}; };
// 支付方式由平台在收款时补记:仅管理员代客下单时可指定,用户端提交一律丢弃 // 实际收款方式由平台在收款时补记:仅管理员代客下单时可指定,用户端提交一律丢弃
if (HandlerEscortRecord.isAdmin(ctx.state.user) if (HandlerEscortRecord.isAdmin(ctx.state.user)
&& HandlerEscortRecord.PAYMENT_METHODS.includes(body.payment?.method)) { && HandlerEscortRecord.PAYMENT_METHODS.includes(body.payment?.method)) {
payload.payment.method = body.payment.method; payload.payment.method = body.payment.method;
@@ -378,9 +432,16 @@ class HandlerEscortRecord {
} }
const isAdmin = HandlerEscortRecord.isAdmin(ctx.state.user); const isAdmin = HandlerEscortRecord.isAdmin(ctx.state.user);
// 非管理员的可改字段随订单状态收敛:终态无可改字段,进行中只剩就诊人备注 // 兼容旧数据:取消曾存放在 status 中
const cancelStatus = existing.status === "cancelled"
? "cancelled"
: (existing.cancelStatus || "none");
// 非管理员的可改字段随订单状态收敛:终态无可改字段,进行中只剩就诊人备注;
// 已申请取消或已取消的订单一律冻结,等待平台处理
const allowFields = isAdmin const allowFields = isAdmin
? HandlerEscortRecord.RECORD_FIELDS ? HandlerEscortRecord.RECORD_FIELDS
: cancelStatus !== "none"
? []
: HandlerEscortRecord.ownerEditableFields(existing.status); : HandlerEscortRecord.ownerEditableFields(existing.status);
if (allowFields.length === 0) { if (allowFields.length === 0) {
return ResponseUtil.forbidden(ctx, "已结束的订单不可修改"); return ResponseUtil.forbidden(ctx, "已结束的订单不可修改");
@@ -399,6 +460,63 @@ class HandlerEscortRecord {
return ResponseUtil.badRequest(ctx, "支付方式不正确"); return ResponseUtil.badRequest(ctx, "支付方式不正确");
} }
// 支付渠道:用户端仅在待支付期间可切换;切到线下前必须先关单
const requestedChannel = update["payment.payChannel"] ?? update.payment?.payChannel;
if (requestedChannel !== undefined) {
if (!HandlerEscortRecord.PAY_CHANNELS.includes(requestedChannel)) {
return ResponseUtil.badRequest(ctx, "支付方式不正确");
}
if (cancelStatus !== "none") {
return ResponseUtil.badRequest(ctx, "已申请取消的订单不可修改支付方式");
}
if ((existing.payment?.status || "unpaid") !== "unpaid") {
return ResponseUtil.forbidden(ctx, "已收款订单不可修改支付方式");
}
if (!["pending", "confirmed"].includes(existing.status)) {
return ResponseUtil.badRequest(ctx, "当前订单状态不允许修改支付方式");
}
if (requestedChannel === "offline") {
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
if (closeResult.paid) {
const fresh = await DBModel.EscortRecord.findById(id);
HandlerPayment.createRefundForRecord(fresh || existing, {
reason: "用户切换支付方式",
}).catch((err) => {
logger.error(`[escort] 切换支付方式后自动退款失败 recordId=${id}: ${err?.message || err}`);
});
return ResponseUtil.error(ctx, "订单已支付,已为您发起退款", null, 409);
}
payload["payment.paymentRecordId"] = null;
}
// 避免管理端提交嵌套 payment 对象时整体覆盖:统一写成点路径
if (payload["payment.payChannel"] === undefined) {
payload["payment.payChannel"] = requestedChannel;
if (payload.payment) {
const nested = { ...payload.payment };
delete nested.payChannel;
if (Object.keys(nested).length === 0) delete payload.payment;
else payload.payment = nested;
}
}
}
// 存在未支付流水时禁止改价:微信侧金额与本地流水错位会对账不上
const nextTotalFee = update["payment.totalFee"] ?? update.payment?.totalFee;
const touchesTotalFee = payload["payment.totalFee"] !== undefined
|| (payload.payment && payload.payment.totalFee !== undefined);
if (nextTotalFee !== undefined && touchesTotalFee) {
const currentTotalFee = Number(existing.payment?.totalFee) || 0;
if (Number(nextTotalFee) !== currentTotalFee) {
const openPayment = await DBModel.PaymentRecord.findOne({
recordId: id,
status: "created",
});
if (openPayment) {
return ResponseUtil.badRequest(ctx, "订单存在未支付流水,请先关闭或取消后再修改金额");
}
}
}
// 档案归属校验:档案必须属于订单所属用户,避免把订单挂到他人档案上; // 档案归属校验:档案必须属于订单所属用户,避免把订单挂到他人档案上;
// 通过后同步刷新订单里的就诊人快照 // 通过后同步刷新订单里的就诊人快照
if (payload.healthProfileId) { if (payload.healthProfileId) {
@@ -468,55 +586,135 @@ class HandlerEscortRecord {
const role = await resolveEscortAdminRole(user); const role = await resolveEscortAdminRole(user);
const isOwner = String(existing.userId) === String(user?._id); const isOwner = String(existing.userId) === String(user?._id);
const paymentStatus = existing.payment?.status || "unpaid"; const paymentStatus = existing.payment?.status || "unpaid";
const cancelReason = String(reason || "").trim().slice(0, 200);
let effectivePaymentStatus = paymentStatus;
let effectivePayment = existing.payment || {};
// 兼容旧数据:取消曾存放在 status 中
const cancelStatus = existing.status === "cancelled"
? "cancelled"
: (existing.cancelStatus || "none");
if (cancelStatus === "cancelled") {
return ResponseUtil.badRequest(ctx, "订单已取消,不能再次操作");
}
let targetStatus = status;
if (role !== "admin" && role !== "attendant") { if (role !== "admin" && role !== "attendant") {
// 用户端只能取消:未确认且未收款直接物理删除;已确认或已收款先进取消申请 // 用户端只能取消:未确认且未收款直接物理删除;其余提交取消申请
if (status !== "cancelled" || !isOwner) { if (status !== "cancelled" || !isOwner) {
return ResponseUtil.forbidden(ctx, "不支持的状态变更"); return ResponseUtil.forbidden(ctx, "不支持的状态变更");
} }
if (cancelStatus === "requested") {
return ResponseUtil.badRequest(ctx, "取消申请已提交,请等待确认");
}
if (!["pending", "confirmed"].includes(existing.status)) {
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
}
if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因");
if (paymentStatus === "unpaid" && existing.status === "pending") { if (paymentStatus === "unpaid" && existing.status === "pending") {
// 接入微信支付后:删除前必须先关单,否则旧 prepay 仍可支付一张已不存在的订单 // 删除前必须先关单,否则旧 prepay 仍可支付一张已不存在的订单
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
if (closeResult.paid) {
// 关单后发现钱已到账:不能删除,转待取消并等待确认后退款
const updated = await DBModel.EscortRecord.updateRecordCancel(id, cancelStatus, {
cancelStatus: "requested",
cancelReason,
cancelRequestedAt: new Date(),
});
if (!updated) {
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
}
return ResponseUtil.success(
ctx,
{ record: HandlerEscortRecord.withPaymentWindow(updated), deleted: false },
"订单已支付,取消申请已提交"
);
}
const deletedRecord = await DBModel.EscortRecord.deleteRecord(id); const deletedRecord = await DBModel.EscortRecord.deleteRecord(id);
if (!deletedRecord) { if (!deletedRecord) {
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404); return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
} }
return ResponseUtil.success(ctx, { record: deletedRecord, deleted: true }, "订单已取消"); return ResponseUtil.success(ctx, { record: deletedRecord, deleted: true }, "订单已取消");
} }
if (!["pending", "confirmed"].includes(existing.status)) {
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作"); // 申请取消前先关闭未支付的 prepay,避免等待确认期间又被支付
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
if (closeResult.paid) {
const fresh = await DBModel.EscortRecord.findById(id);
effectivePaymentStatus = fresh?.payment?.status || "paid";
effectivePayment = fresh?.payment || effectivePayment;
} }
targetStatus = "cancel_requested"; if (!canCancelTransition(cancelStatus, "requested")) {
return ResponseUtil.badRequest(ctx, "当前订单不允许取消");
}
const updatedRecord = await DBModel.EscortRecord.updateRecordCancel(id, cancelStatus, {
cancelStatus: "requested",
cancelReason,
cancelRequestedAt: new Date(),
});
if (!updatedRecord) {
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
}
return ResponseUtil.success(
ctx,
{ record: HandlerEscortRecord.withPaymentWindow(updatedRecord) },
"取消申请已提交"
);
} }
if (!canTransition(existing.status, targetStatus)) { // 管理端/陪诊师:普通状态推进,或确认取消申请 / 直接取消
if (status !== "cancelled") {
if (cancelStatus === "requested") {
return ResponseUtil.badRequest(ctx, "用户已申请取消,请先处理取消申请");
}
if (!canTransition(existing.status, status)) {
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作"); return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
} }
const updatedRecord = await DBModel.EscortRecord.updateRecordStatus(id, existing.status, { status });
const update = { status: targetStatus }; if (!updatedRecord) {
const cancelReason = String(reason || "").trim().slice(0, 200); return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
if (targetStatus === "cancel_requested") {
if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因");
// 接入微信支付后:此处应关闭未支付的 prepay,避免申请取消期间又被支付
update.cancelReason = cancelReason;
update.cancelRequestedAt = new Date();
} }
if (status === "cancelled") { return ResponseUtil.success(ctx, { record: updatedRecord }, "状态更新成功");
}
if (!canCancelTransition(cancelStatus, "cancelled")) {
return ResponseUtil.badRequest(ctx, "当前订单不允许取消");
}
// 取消前先关单:未支付订单可能仍有旧 prepay 在途,关单后发现已支付则按已收款走退款
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
if (closeResult.paid) {
const fresh = await DBModel.EscortRecord.findById(id);
effectivePaymentStatus = fresh?.payment?.status || "paid";
effectivePayment = fresh?.payment || effectivePayment;
}
const update = {
cancelStatus: "cancelled",
cancelledAt: new Date(),
// 已收款订单先进入退款中;线上支付随后自动原路退款,线下由平台人工核销
...(["partial", "paid"].includes(effectivePaymentStatus) ? { "payment.status": "refunding" } : {}),
};
// 正式取消:保留申请原因;平台直接取消时补默认原因 // 正式取消:保留申请原因;平台直接取消时补默认原因
if (cancelReason) update.cancelReason = cancelReason; if (cancelReason) update.cancelReason = cancelReason;
else if (role === "admin" && !existing.cancelReason) update.cancelReason = "平台取消"; else if (role === "admin" && !existing.cancelReason) update.cancelReason = "平台取消";
update.cancelledAt = new Date();
// 客服协助支付没有线上自动退款能力:已收款订单先进入退款中,退款完成再由平台核销。
if (["partial", "paid"].includes(paymentStatus)) {
update["payment.status"] = "refunding";
}
}
const updatedRecord = await DBModel.EscortRecord.updateRecordStatus(id, existing.status, update); const updatedRecord = await DBModel.EscortRecord.updateRecordCancel(id, cancelStatus, update);
if (!updatedRecord) { if (!updatedRecord) {
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409); return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
} }
// 已支付的线上订单:取消落库后再发起原路全额退款
if (effectivePayment?.method === "online_wechat"
&& ["partial", "paid"].includes(effectivePaymentStatus)) {
HandlerPayment.createRefundForRecord(updatedRecord, {
reason: updatedRecord.cancelReason || cancelReason || "订单取消",
}).catch((err) => {
logger.error(`[escort] 取消订单自动退款失败 recordId=${id}: ${err?.message || err}`);
});
}
return ResponseUtil.success(ctx, { record: updatedRecord }, "状态更新成功"); return ResponseUtil.success(ctx, { record: updatedRecord }, "状态更新成功");
} catch (err) { } catch (err) {
return ResponseUtil.internalError(ctx, err); return ResponseUtil.internalError(ctx, err);
@@ -542,10 +740,19 @@ class HandlerEscortRecord {
return ResponseUtil.forbidden(ctx, "无权删除该订单"); return ResponseUtil.forbidden(ctx, "无权删除该订单");
} }
const paymentStatus = existing.payment?.status || "unpaid"; let paymentStatus = existing.payment?.status || "unpaid";
let paymentMethod = existing.payment?.method || "";
// 软删除前先关单:否则已软删除的订单仍可能被旧 prepay 支付
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
if (closeResult.paid) {
const fresh = await DBModel.EscortRecord.findById(id);
paymentStatus = fresh?.payment?.status || "paid";
paymentMethod = fresh?.payment?.method || "online_wechat";
}
const update = { deletedAt: new Date() }; const update = { deletedAt: new Date() };
if (["partial", "paid"].includes(paymentStatus)) { if (["partial", "paid"].includes(paymentStatus)) {
update.status = "cancelled"; update.cancelStatus = "cancelled";
update.cancelReason = existing.cancelReason || "平台删除"; update.cancelReason = existing.cancelReason || "平台删除";
update.cancelledAt = update.deletedAt; update.cancelledAt = update.deletedAt;
update["payment.status"] = "refunding"; update["payment.status"] = "refunding";
@@ -554,6 +761,13 @@ class HandlerEscortRecord {
if (!softDeleted) { if (!softDeleted) {
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404); return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
} }
if (update.cancelStatus === "cancelled" && paymentMethod === "online_wechat") {
HandlerPayment.createRefundForRecord(softDeleted, {
reason: softDeleted.cancelReason || "平台删除",
}).catch((err) => {
logger.error(`[escort] 删除订单自动退款失败 recordId=${id}: ${err?.message || err}`);
});
}
return ResponseUtil.success(ctx, { record: softDeleted }, "删除成功"); return ResponseUtil.success(ctx, { record: softDeleted }, "删除成功");
} catch (err) { } catch (err) {
return ResponseUtil.internalError(ctx, err); return ResponseUtil.internalError(ctx, err);
+1011
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -1,6 +1,7 @@
import 'dotenv/config'; import 'dotenv/config';
import { APP } from './app.js' import { APP } from './app.js'
import WebSocketServerManager from './websocket.js' import WebSocketServerManager from './websocket.js'
import { startPaymentPatrol } from './handler/payment.js'
// HTTP server // HTTP server
const koaApp = new APP(); const koaApp = new APP();
@@ -9,3 +10,6 @@ koaApp.start(parseInt(process.env.PORT || "9004"));
// WebSocket server // WebSocket server
const wsServer = new WebSocketServerManager(parseInt(process.env.WS_PORT || "9005")); const wsServer = new WebSocketServerManager(parseInt(process.env.WS_PORT || "9005"));
wsServer.start(); wsServer.start();
// 后台支付巡检查单:默认运行,回调丢失时由此收敛
startPaymentPatrol();
+6
View File
@@ -8,6 +8,8 @@ import { HospitalSchema } from "./schema/hospital.js"
import { EmployeeSchema } from "./schema/employee.js" import { EmployeeSchema } from "./schema/employee.js"
import { EmployeeReviewSchema } from "./schema/employee_review.js" import { EmployeeReviewSchema } from "./schema/employee_review.js"
import { TrainingApplicationSchema } from "./schema/training_application.js" import { TrainingApplicationSchema } from "./schema/training_application.js"
import { PaymentRecordSchema } from "./schema/payment_record.js"
import { RefundRecordSchema } from "./schema/refund_record.js"
import config from '../config.js'; import config from '../config.js';
import logger from '../utils/logger.js'; import logger from '../utils/logger.js';
@@ -22,6 +24,8 @@ class MongoDBSchema {
this.HealthProfile = null; this.HealthProfile = null;
this.EmployeeReview = null; this.EmployeeReview = null;
this.TrainingApplication = null; this.TrainingApplication = null;
this.PaymentRecord = null;
this.RefundRecord = null;
} }
init() { init() {
@@ -54,6 +58,8 @@ class MongoDBSchema {
this.Employee = this.dbConnection.model('employee', EmployeeSchema) this.Employee = this.dbConnection.model('employee', EmployeeSchema)
this.EmployeeReview = this.dbConnection.model('employee_review', EmployeeReviewSchema) this.EmployeeReview = this.dbConnection.model('employee_review', EmployeeReviewSchema)
this.TrainingApplication = this.dbConnection.model('training_application', TrainingApplicationSchema) this.TrainingApplication = this.dbConnection.model('training_application', TrainingApplicationSchema)
this.PaymentRecord = this.dbConnection.model('payment_record', PaymentRecordSchema)
this.RefundRecord = this.dbConnection.model('refund_record', RefundRecordSchema)
} }
} }
+67 -8
View File
@@ -123,7 +123,19 @@ const EscortRecordSchema = mongoose.Schema(
type: String, type: String,
enum: ["", "online_wechat", "offline_cash", "offline_transfer"], enum: ["", "online_wechat", "offline_cash", "offline_transfer"],
default: "", default: "",
comment: "支付方式:线上微信、线下现金、线下转账", comment: "实际收款方式:线上微信、线下现金、线下转账",
},
// 用户选择的支付渠道;历史订单缺失该字段时展示层按 offline 解释
payChannel: {
type: String,
enum: ["online_wechat", "offline"],
comment: "用户选择的支付渠道",
},
// 当前有效支付流水;历史流水保留在 payment_record 中审计
paymentRecordId: {
type: mongoose.Schema.Types.ObjectId,
default: null,
comment: "当前有效支付流水",
}, },
status: { status: {
type: String, type: String,
@@ -143,19 +155,33 @@ const EscortRecordSchema = mongoose.Schema(
}, },
/** /**
* 陪诊状态 * 陪诊状态(只描述服务生命周期,不含取消)
* - pending: 待确认 - 订单已创建,等待确认 * - pending: 待确认 - 订单已创建,等待确认
* - confirmed: 已确认 - 订单已确认,等待服务 * - confirmed: 已确认 - 订单已确认,等待服务
* - cancel_requested: 待取消 - 用户已申请取消,等待陪诊师或管理员确认
* - in_progress: 进行中 - 陪诊服务正在进行 * - in_progress: 进行中 - 陪诊服务正在进行
* - completed: 已完成 - 陪诊服务已完成 * - completed: 已完成 - 陪诊服务已完成
* - cancelled: 已取消 - 订单已取消 *
* 取消单独用 cancelStatus 表达,取消后 status 保留取消前的服务状态。
*/ */
status: { status: {
type: String, type: String,
enum: ["pending", "confirmed", "cancel_requested", "in_progress", "completed", "cancelled"], enum: ["pending", "confirmed", "in_progress", "completed"],
default: "pending", default: "pending",
comment: "陪诊状态:待确认、已确认、待取消、进行中、已完成、已取消", comment: "陪诊状态:待确认、已确认、进行中、已完成",
},
/**
* 取消状态(与 status 解耦)
* - none: 未取消
* - requested: 用户已申请取消,等待陪诊师/管理员确认
* - cancelled: 已取消
*/
cancelStatus: {
type: String,
enum: ["none", "requested", "cancelled"],
default: "none",
index: true,
comment: "取消状态:无、待取消、已取消",
}, },
cancelReason: { type: String, default: "", comment: "订单取消原因" }, cancelReason: { type: String, default: "", comment: "订单取消原因" },
@@ -197,7 +223,10 @@ const EscortRecordSchema = mongoose.Schema(
* @returns {Promise<Array>} 陪诊记录列表(按预约日期倒序) * @returns {Promise<Array>} 陪诊记录列表(按预约日期倒序)
*/ */
EscortRecordSchema.statics.buildRecordFilter = function (options = {}) { EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
const { status, userId, appointmentDate, healthProfileId, includeDeleted = false } = options; const {
status, cancelStatus, userId, appointmentDate, healthProfileId,
includeDeleted = false, includeCancelled = false,
} = options;
const filter = {}; const filter = {};
// 软删除的订单默认不进入列表:数据库里保留审计,界面上视为已删除 // 软删除的订单默认不进入列表:数据库里保留审计,界面上视为已删除
@@ -206,6 +235,19 @@ EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
if (status && Array.isArray(status) && status.length > 0) { if (status && Array.isArray(status) && status.length > 0) {
filter.status = { $in: status }; filter.status = { $in: status };
} }
// 取消状态与 status 解耦:默认隐藏已取消订单,显式指定 cancelStatus 或 includeCancelled 时放开
if (cancelStatus && Array.isArray(cancelStatus) && cancelStatus.length > 0) {
if (cancelStatus.length === 1 && cancelStatus[0] === "cancelled") {
// 兼容旧数据:取消曾存放在 status 中
filter.$or = [{ cancelStatus: "cancelled" }, { status: "cancelled" }];
} else {
filter.cancelStatus = { $in: cancelStatus };
}
} else if (!includeCancelled) {
// 历史数据没有 cancelStatus 字段,按未取消处理;旧数据仍可能把 cancelled 存在 status 里
filter.cancelStatus = { $ne: "cancelled" };
if (!filter.status) filter.status = { $ne: "cancelled" };
}
if (userId) filter.userId = userId; if (userId) filter.userId = userId;
if (healthProfileId) filter.healthProfileId = healthProfileId; if (healthProfileId) filter.healthProfileId = healthProfileId;
if (appointmentDate) { if (appointmentDate) {
@@ -239,7 +281,11 @@ EscortRecordSchema.statics.findRecordPage = async function (options = {}) {
this.find(filter).sort({ "schedule.date": -1 }).skip(skip).limit(pageSize).exec(), this.find(filter).sort({ "schedule.date": -1 }).skip(skip).limit(pageSize).exec(),
this.countDocuments(filter).exec(), this.countDocuments(filter).exec(),
this.countDocuments(baseFilter).exec(), this.countDocuments(baseFilter).exec(),
this.countDocuments({ ...baseFilter, status: { $in: ["pending", "confirmed", "in_progress"] } }).exec(), this.countDocuments({
...baseFilter,
status: { $in: ["pending", "confirmed", "in_progress"] },
cancelStatus: { $ne: "cancelled" },
}).exec(),
]); ]);
return { records, total, counts: { all, ongoing } }; return { records, total, counts: { all, ongoing } };
}; };
@@ -317,6 +363,19 @@ EscortRecordSchema.statics.updateRecordStatus = async function (id, fromStatus,
); );
}; };
// 取消状态迁移以读取时的 cancelStatus 为条件;历史数据缺字段时按 none 处理。
EscortRecordSchema.statics.updateRecordCancel = async function (id, fromCancelStatus, update) {
const from = fromCancelStatus || "none";
const cancelFilter = from === "none"
? { cancelStatus: { $in: ["none", null] } }
: { cancelStatus: from };
return await this.findOneAndUpdate(
{ _id: id, deletedAt: null, ...cancelFilter },
{ $set: { ...update, "meta.updatetime": Date.now() } },
{ new: true, runValidators: true }
);
};
EscortRecordSchema.statics.findByIdempotencyKey = async function (userId, idempotencyKey) { EscortRecordSchema.statics.findByIdempotencyKey = async function (userId, idempotencyKey) {
return await this.findOne({ userId, idempotencyKey, deletedAt: null }).exec(); return await this.findOne({ userId, idempotencyKey, deletedAt: null }).exec();
}; };
+112
View File
@@ -0,0 +1,112 @@
"use strict";
import mongoose from "mongoose";
/**
* 支付流水(支付事实源)
*
* 一次支付尝试一条文档,订单上的 payment 只是汇总快照。
* 金额全链路用「分」,与微信账单口径一致。
*/
const PaymentRecordSchema = mongoose.Schema(
{
bizType: { type: String, default: "escort", comment: "业务类型" },
recordId: {
type: mongoose.Schema.Types.ObjectId,
comment: "关联业务单据ID( escort_record._id )",
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
comment: "付款用户",
},
// 微信侧标识(对账核心字段)
outTradeNo: { type: String, required: true, comment: "商户订单号,永不重用" },
attemptNo: { type: Number, default: 1, comment: "第几次支付尝试(从 1 起)" },
transactionId: { type: String, comment: "微信支付订单号(稀疏唯一,支付成功后回填)" },
prepayId: { type: String, default: "", comment: "预支付会话标识" },
prepayExpiresAt: { type: Date, default: null, comment: "prepay_id 过期时间(2小时)" },
timeExpireAt: { type: Date, default: null, comment: "下单传入的 time_expire(支付窗口终点)" },
appid: { type: String, default: "", comment: "下单 appid" },
mchid: { type: String, default: "", comment: "商户号" },
tradeType: { type: String, default: "JSAPI", comment: "交易类型" },
totalFee: { type: Number, default: 0, comment: "应付金额(分)" },
payerTotal: { type: Number, default: 0, comment: "用户实付(分,回调回填)" },
/**
* created → pay_success / closed
* created → closed_unconfirmed(关单失败且查单未确认)
* pay_success → refunding → refunded
*/
status: {
type: String,
enum: ["created", "pay_success", "closed", "closed_unconfirmed", "refunding", "refunded"],
default: "created",
comment: "支付流水状态",
},
closeUnconfirmed: { type: Boolean, default: false, comment: "关单结果不确定,待人工核对" },
createdAt: { type: Date, default: Date.now, comment: "流水创建时间" },
prepayedAt: { type: Date, default: null, comment: "最近一次预下单时间" },
paidAt: { type: Date, default: null, comment: "支付成功时间" },
closedAt: { type: Date, default: null, comment: "关单时间" },
bankType: { type: String, default: "", comment: "支付方式(如 OTHERS/CMB_CREDIT)" },
successTime: { type: Date, default: null, comment: "微信侧支付完成时间" },
lastError: {
stage: { type: String, default: "" },
code: { type: String, default: "" },
message: { type: String, default: "" },
requestId: { type: String, default: "" },
httpStatus: { type: Number, default: 0 },
at: { type: Date, default: null },
},
errorCount: { type: Number, default: 0, comment: "累计失败次数" },
lastAttemptAt: { type: Date, default: null, comment: "最近一次调用时间" },
meta: {
createtime: { type: Date, default: Date.now },
updatetime: { type: Date, default: Date.now },
},
},
{
minimize: false,
strict: false,
collection: "payment_record",
timestamps: false,
}
);
// 异常留档:message 截断 500,避免超长文本撑库;写库失败由调用方 logger.error 兜底
PaymentRecordSchema.statics.markError = async function (id, detail = {}) {
return await this.updateOne(
{ _id: id },
{
$set: {
lastError: {
stage: String(detail.stage || ""),
code: String(detail.code || "UNKNOWN"),
message: String(detail.message || "").slice(0, 500),
requestId: String(detail.requestId || ""),
httpStatus: Number(detail.httpStatus) || 0,
at: detail.at || new Date(),
},
lastAttemptAt: new Date(),
"meta.updatetime": Date.now(),
},
$inc: { errorCount: 1 },
}
);
};
PaymentRecordSchema.index({ outTradeNo: 1 }, { unique: true });
PaymentRecordSchema.index({ transactionId: 1 }, { unique: true, sparse: true });
PaymentRecordSchema.index({ recordId: 1 });
PaymentRecordSchema.index({ userId: 1, createdAt: -1 });
PaymentRecordSchema.index({ status: 1, createdAt: 1 });
export { PaymentRecordSchema };
+91
View File
@@ -0,0 +1,91 @@
"use strict";
import mongoose from "mongoose";
/**
* 退款流水
*
* 本期一笔支付只发起一次全额退款:outRefundNo = 订单_id + "-R1"。
* 重试必须沿用同一 outRefundNo(微信对同号退款幂等返回原退款单)。
*/
const RefundRecordSchema = mongoose.Schema(
{
paymentId: {
type: mongoose.Schema.Types.ObjectId,
comment: "关联 payment_record._id",
},
recordId: {
type: mongoose.Schema.Types.ObjectId,
comment: "冗余关联业务单据ID",
},
outTradeNo: { type: String, default: "", comment: "原商户订单号(冗余)" },
outRefundNo: { type: String, required: true, comment: "商户退款单号" },
refundId: { type: String, comment: "微信退款单号(稀疏唯一,受理成功后回填)" },
refundAmount: { type: Number, default: 0, comment: "退款金额(分)" },
totalAmount: { type: Number, default: 0, comment: "原订单金额(分)" },
reason: { type: String, default: "", comment: "退款原因" },
status: {
type: String,
enum: ["processing", "success", "abnormal", "closed"],
default: "processing",
comment: "退款状态",
},
userReceivedAccount: { type: String, default: "", comment: "退款入账账户" },
successTime: { type: Date, default: null, comment: "退款成功时间" },
lastQueriedAt: { type: Date, default: null, comment: "最近一次主动查询退款时间" },
createdAt: { type: Date, default: Date.now, comment: "退款流水创建时间" },
lastError: {
stage: { type: String, default: "" },
code: { type: String, default: "" },
message: { type: String, default: "" },
requestId: { type: String, default: "" },
httpStatus: { type: Number, default: 0 },
at: { type: Date, default: null },
},
errorCount: { type: Number, default: 0, comment: "累计失败次数" },
lastAttemptAt: { type: Date, default: null, comment: "最近一次调用时间" },
meta: {
createtime: { type: Date, default: Date.now },
updatetime: { type: Date, default: Date.now },
},
},
{
minimize: false,
strict: false,
collection: "refund_record",
timestamps: false,
}
);
RefundRecordSchema.statics.markError = async function (id, detail = {}) {
return await this.updateOne(
{ _id: id },
{
$set: {
lastError: {
stage: String(detail.stage || ""),
code: String(detail.code || "UNKNOWN"),
message: String(detail.message || "").slice(0, 500),
requestId: String(detail.requestId || ""),
httpStatus: Number(detail.httpStatus) || 0,
at: detail.at || new Date(),
},
lastAttemptAt: new Date(),
"meta.updatetime": Date.now(),
},
$inc: { errorCount: 1 },
}
);
};
RefundRecordSchema.index({ outRefundNo: 1 }, { unique: true });
RefundRecordSchema.index({ refundId: 1 }, { unique: true, sparse: true });
RefundRecordSchema.index({ recordId: 1 });
RefundRecordSchema.index({ paymentId: 1 });
RefundRecordSchema.index({ status: 1, createdAt: 1 });
export { RefundRecordSchema };
+13
View File
@@ -1,5 +1,6 @@
import Router from "koa-router"; import Router from "koa-router";
import { HandlerEscortRecord } from "../handler/escort_record.js"; import { HandlerEscortRecord } from "../handler/escort_record.js";
import { HandlerPayment } from "../handler/payment.js";
import { HandlerHealthProfile } from "../handler/health_profile.js"; import { HandlerHealthProfile } from "../handler/health_profile.js";
import { HandlerResource } from "../handler/resource.js"; import { HandlerResource } from "../handler/resource.js";
import { HandlerEmployee } from "../handler/employee.js"; import { HandlerEmployee } from "../handler/employee.js";
@@ -75,6 +76,7 @@ function registerRoutes(app) {
const router = new Router({ prefix: '/health' }); const router = new Router({ prefix: '/health' });
const handlerEscortRecord = new HandlerEscortRecord(); const handlerEscortRecord = new HandlerEscortRecord();
const handlerPayment = new HandlerPayment();
const handlerHealthProfile = new HandlerHealthProfile(); const handlerHealthProfile = new HandlerHealthProfile();
const handlerResource = new HandlerResource(); const handlerResource = new HandlerResource();
const handlerEmployee = new HandlerEmployee(); const handlerEmployee = new HandlerEmployee();
@@ -82,11 +84,22 @@ function registerRoutes(app) {
const handlerTrainingApplication = new HandlerTrainingApplication(); const handlerTrainingApplication = new HandlerTrainingApplication();
const handlerHospital = new HandlerHospital(); const handlerHospital = new HandlerHospital();
// 微信支付回调:微信服务器直调,无鉴权,靠验签保安全;
// 必须注册在 /escort-record/:id 之前,避免被通用路由抢占
router.post("/pay/notify", handlerPayment.paymentNotify.bind(handlerPayment));
router.post("/pay/refund-notify", handlerPayment.refundNotify.bind(handlerPayment));
// 敏感数据路由需要登录后访问 // 敏感数据路由需要登录后访问
router.get("/escort-record/my", requireAuth, handlerEscortRecord.getMyRecords.bind(handlerEscortRecord)); router.get("/escort-record/my", requireAuth, handlerEscortRecord.getMyRecords.bind(handlerEscortRecord));
router.get("/escort-record/attendant", requireAuth, handlerEscortRecord.getAttendantRecords.bind(handlerEscortRecord)); router.get("/escort-record/attendant", requireAuth, handlerEscortRecord.getAttendantRecords.bind(handlerEscortRecord));
// 全量查询属管理端能力,必须管理员 // 全量查询属管理端能力,必须管理员
router.get("/escort-record", requireAuth, requireAdmin, handlerEscortRecord.getRecords.bind(handlerEscortRecord)); router.get("/escort-record", requireAuth, requireAdmin, handlerEscortRecord.getRecords.bind(handlerEscortRecord));
// 支付相关:发起支付 / 查单确认 / 管理端退款查单兜底
router.post("/escort-record/:id/pay", requireAuth, createLimit, handlerPayment.createPayment.bind(handlerPayment));
router.get("/escort-record/:id/pay/status", requireAuth, handlerPayment.queryPayment.bind(handlerPayment));
router.post("/escort-record/:id/refund/query", requireAuth, requireAdmin, handlerPayment.queryRefundResult.bind(handlerPayment));
router.get("/escort-record/:id", requireAuth, handlerEscortRecord.getRecordById.bind(handlerEscortRecord)); router.get("/escort-record/:id", requireAuth, handlerEscortRecord.getRecordById.bind(handlerEscortRecord));
router.post("/escort-record", requireAuth, createLimit, handlerEscortRecord.createRecord.bind(handlerEscortRecord)); router.post("/escort-record", requireAuth, createLimit, handlerEscortRecord.createRecord.bind(handlerEscortRecord));
router.put("/escort-record/:id", requireAuth, updateLimit, handlerEscortRecord.updateRecord.bind(handlerEscortRecord)); router.put("/escort-record/:id", requireAuth, updateLimit, handlerEscortRecord.updateRecord.bind(handlerEscortRecord));
+18 -4
View File
@@ -1,7 +1,7 @@
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { canTransition, STATUS_TRANSITIONS } from "../utils/record_state.js"; import { canTransition, canCancelTransition, STATUS_TRANSITIONS, CANCEL_TRANSITIONS } from "../utils/record_state.js";
import { isAdmin } from "../utils/permissions.js"; import { isAdmin } from "../utils/permissions.js";
import { escapeRegex } from "../agent/infra/tools/db/utils.js"; import { escapeRegex } from "../agent/infra/tools/db/utils.js";
import { import {
@@ -18,16 +18,26 @@ test("订单状态机只允许正向流转", () => {
assert.equal(canTransition("pending", "confirmed"), true); assert.equal(canTransition("pending", "confirmed"), true);
assert.equal(canTransition("confirmed", "in_progress"), true); assert.equal(canTransition("confirmed", "in_progress"), true);
assert.equal(canTransition("in_progress", "completed"), true); assert.equal(canTransition("in_progress", "completed"), true);
assert.equal(canTransition("pending", "cancelled"), true); // 取消已从 status 拆出,不再作为状态迁移
assert.equal(canTransition("pending", "cancelled"), false);
// 终态不可回退,也不能跳步 // 终态不可回退,也不能跳步
assert.equal(canTransition("completed", "in_progress"), false); assert.equal(canTransition("completed", "in_progress"), false);
assert.equal(canTransition("cancelled", "pending"), false);
assert.equal(canTransition("pending", "completed"), false); assert.equal(canTransition("pending", "completed"), false);
// 未知状态一律拒绝 // 未知状态一律拒绝
assert.equal(canTransition("unknown", "pending"), false); assert.equal(canTransition("unknown", "pending"), false);
}); });
test("取消状态机独立于服务状态", () => {
assert.equal(canCancelTransition("none", "requested"), true);
assert.equal(canCancelTransition("none", "cancelled"), true);
assert.equal(canCancelTransition("requested", "cancelled"), true);
// 已取消不可回退,也不能再次申请
assert.equal(canCancelTransition("cancelled", "none"), false);
assert.equal(canCancelTransition("cancelled", "requested"), false);
assert.equal(canCancelTransition("requested", "none"), false);
});
test("管理端身份要求显式 role=admin", () => { test("管理端身份要求显式 role=admin", () => {
assert.equal(isAdmin(null), false); assert.equal(isAdmin(null), false);
assert.equal(isAdmin({}), false); assert.equal(isAdmin({}), false);
@@ -145,6 +155,10 @@ test("百度地图请求自动注入鉴权且不影响其他域名", () => {
test("状态机表覆盖全部订单状态", () => { test("状态机表覆盖全部订单状态", () => {
assert.deepEqual( assert.deepEqual(
Object.keys(STATUS_TRANSITIONS).sort(), Object.keys(STATUS_TRANSITIONS).sort(),
["cancel_requested", "cancelled", "completed", "confirmed", "in_progress", "pending"] ["completed", "confirmed", "in_progress", "pending"]
);
assert.deepEqual(
Object.keys(CANCEL_TRANSITIONS).sort(),
["cancelled", "none", "requested"]
); );
}); });
+102
View File
@@ -0,0 +1,102 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import crypto from "node:crypto";
import {
yuanToFen,
fenToYuan,
formatTimeExpire,
buildRequestSignature,
buildAuthHeader,
verifyMessageSignature,
decryptAesGcm,
} from "../utils/wechatpay.js";
test("元转分按小数点拆位,不经过浮点", () => {
assert.equal(yuanToFen("500.00"), 50000);
assert.equal(yuanToFen("500.5"), 50050);
assert.equal(yuanToFen(500), 50000);
assert.equal(yuanToFen("0.01"), 1);
assert.equal(yuanToFen("0.00"), 0);
// 超过两位小数、非数字、负数一律非法
assert.equal(yuanToFen("500.001"), null);
assert.equal(yuanToFen("abc"), null);
assert.equal(yuanToFen("-1"), null);
assert.equal(yuanToFen(""), null);
});
test("分转元固定两位小数", () => {
assert.equal(fenToYuan(50000), "500.00");
assert.equal(fenToYuan(1), "0.01");
assert.equal(fenToYuan(1.5), "");
});
test("time_expire 输出 RFC3339 北京时间", () => {
assert.equal(formatTimeExpire(new Date("2026-11-06T02:00:00.000Z")), "2026-11-06T10:00:00+08:00");
assert.equal(formatTimeExpire("invalid"), "");
});
test("请求签名可被同名公钥验证", () => {
const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
const privatePem = privateKey.export({ type: "pkcs8", format: "pem" });
const publicPem = publicKey.export({ type: "spki", format: "pem" });
const method = "POST";
const urlPath = "/v3/pay/transactions/jsapi";
const timestamp = "1700000000";
const nonce = "abc123";
const body = '{"appid":"wx-test"}';
const signature = buildRequestSignature({ method, urlPath, timestamp, nonce, body, privateKey: privatePem });
const message = `${method}\n${urlPath}\n${timestamp}\n${nonce}\n${body}\n`;
assert.equal(verifyMessageSignature({ message, signature, publicKeyPem: publicPem }), true);
// 报文被篡改后验签失败
const tampered = `${method}\n${urlPath}\n${timestamp}\n${nonce}\n${body.replace("wx-test", "wx-evil")}\n`;
assert.equal(verifyMessageSignature({ message: tampered, signature, publicKeyPem: publicPem }), false);
});
test("Authorization 头使用 WECHATPAY2-SHA256-RSA2048 格式", () => {
const header = buildAuthHeader({
mchid: "1900000109",
serialNo: "SERIAL",
signature: "SIG",
timestamp: "1700000000",
nonce: "abc123",
});
assert.equal(
header,
'WECHATPAY2-SHA256-RSA2048 mchid="1900000109",nonce_str="abc123",signature="SIG",timestamp="1700000000",serial_no="SERIAL"'
);
});
test("AES-256-GCM 解密与 authTag 校验", () => {
const key = crypto.randomBytes(32);
const nonce = "abcdefghijkl";
const associatedData = "transaction";
const plaintext = JSON.stringify({ out_trade_no: "order-1", amount: { total: 1 } });
const cipher = crypto.createCipheriv("aes-256-gcm", key, Buffer.from(nonce, "utf-8"));
cipher.setAAD(Buffer.from(associatedData, "utf-8"));
const encrypted = Buffer.concat([cipher.update(plaintext, "utf-8"), cipher.final()]);
const authTag = cipher.getAuthTag();
const ciphertext = Buffer.concat([encrypted, authTag]).toString("base64");
const decrypted = decryptAesGcm({
ciphertext,
nonce,
associatedData,
apiV3Key: key,
});
assert.equal(decrypted, plaintext);
// 篡改密文 / 错误 authTag 必须抛错
const broken = Buffer.from(ciphertext, "base64");
broken[broken.length - 1] ^= 0xff;
assert.throws(() => decryptAesGcm({
ciphertext: broken.toString("base64"),
nonce,
associatedData,
apiV3Key: key,
}));
});
+28 -7
View File
@@ -3,21 +3,32 @@
* *
* 之前 Agent 的 escort_record_set 直接改 status,绕过了接口层的迁移校验, * 之前 Agent 的 escort_record_set 直接改 status,绕过了接口层的迁移校验,
* 可以把已完成订单改回进行中。规则集中在这里,任何入口都必须走 canTransition。 * 可以把已完成订单改回进行中。规则集中在这里,任何入口都必须走 canTransition。
*
* status 只描述服务生命周期;取消由独立的 cancelStatus 表达:
* - none → requested:用户对已确认/已收款订单提交取消申请,等陪诊师或管理员确认
* - none / requested → cancelled:正式取消
*/ */
// 允许的状态迁移;终态不可再变 // 允许的服务状态迁移;completed 不可再变
// cancel_requested:用户对已确认/已收款订单提交的取消申请,等陪诊师或管理员确认
const STATUS_TRANSITIONS = { const STATUS_TRANSITIONS = {
pending: ["confirmed", "cancel_requested", "cancelled"], pending: ["confirmed"],
confirmed: ["in_progress", "cancel_requested", "cancelled"], confirmed: ["in_progress"],
cancel_requested: ["cancelled"],
in_progress: ["completed"], in_progress: ["completed"],
completed: [], completed: [],
};
// 取消状态迁移;cancelled 不可再变
const CANCEL_TRANSITIONS = {
none: ["requested", "cancelled"],
requested: ["cancelled"],
cancelled: [], cancelled: [],
}; };
// 取消状态枚举,供接口参数校验复用
const CANCEL_STATUS_VALUES = Object.keys(CANCEL_TRANSITIONS);
/** /**
* 判断状态迁移是否允许 * 判断服务状态迁移是否允许
* @param {string} from 当前状态 * @param {string} from 当前状态
* @param {string} to 目标状态 * @param {string} to 目标状态
* @returns {boolean} * @returns {boolean}
@@ -26,4 +37,14 @@ function canTransition(from, to) {
return (STATUS_TRANSITIONS[from] || []).includes(to); return (STATUS_TRANSITIONS[from] || []).includes(to);
} }
export { STATUS_TRANSITIONS, canTransition }; /**
* 判断取消状态迁移是否允许
* @param {string} from 当前取消状态
* @param {string} to 目标取消状态
* @returns {boolean}
*/
function canCancelTransition(from, to) {
return (CANCEL_TRANSITIONS[from] || []).includes(to);
}
export { STATUS_TRANSITIONS, CANCEL_TRANSITIONS, CANCEL_STATUS_VALUES, canTransition, canCancelTransition };
+571
View File
@@ -0,0 +1,571 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import crypto from "node:crypto";
import fetch from "node-fetch";
import config from "../config.js";
import logger from "./logger.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PROJECT_ROOT = path.resolve(__dirname, "..");
const API_BASE = "https://api.mch.weixin.qq.com";
const REQUEST_TIMEOUT = 5000;
const MAX_ERROR_MESSAGE = 500;
const DEFAULT_NOTIFY_BASE = "https://api.huashengtec.com/health";
/**
* 微信支付统一错误:错误详情用于落库与排障,接口层只返回通用提示。
*/
class WechatPayError extends Error {
constructor({ stage = "", code = "UNKNOWN", message = "", requestId = "", httpStatus = 0 } = {}) {
super(message || code || "wechat pay error");
this.name = "WechatPayError";
this.stage = stage;
this.code = String(code || "UNKNOWN");
this.requestId = requestId || "";
this.httpStatus = Number(httpStatus) || 0;
}
}
function truncate(text, max = MAX_ERROR_MESSAGE) {
return String(text || "").slice(0, max);
}
// 微信对 description(127) / reason(80) 的限制按字节计算,中文需按字节截断
function truncateBytes(text, maxBytes) {
let result = "";
let used = 0;
for (const char of String(text || "")) {
const size = Buffer.byteLength(char, "utf-8");
if (used + size > maxBytes) break;
result += char;
used += size;
}
return result;
}
function payConfig() {
return config.wechatpay || {};
}
function resolvePath(value) {
if (!value) return "";
return path.isAbsolute(value) ? value : path.resolve(PROJECT_ROOT, value);
}
// 证书路径允许用环境变量覆盖:仓库里的 conf.json 面向部署机(Linux 路径),
// 本地开发可用 .env 指向本机证书,避免为了本地调试改回仓库配置。
function privateKeyPathValue() {
return process.env.WXPAY_PRIVATE_KEY_PATH || payConfig().privateKeyPath || "";
}
function publicKeyPathValue() {
return process.env.WXPAY_PUBLIC_KEY_PATH || payConfig().publicKeyPath || "";
}
let cachedPrivateKey = null;
let cachedPublicKey = null;
function loadPrivateKey() {
const privatePath = privateKeyPathValue();
if (!cachedPrivateKey && privatePath) {
cachedPrivateKey = readFileSync(resolvePath(privatePath), "utf-8");
}
return cachedPrivateKey;
}
function loadPublicKey() {
const publicPath = publicKeyPathValue();
if (!cachedPublicKey && publicPath) {
cachedPublicKey = readFileSync(resolvePath(publicPath), "utf-8");
}
return cachedPublicKey;
}
function apiV3Key() {
const cfg = payConfig();
const key = process.env[cfg.apiv3KeyEnv || "WXPAY_APIV3_KEY"] || "";
if (key.length !== 32) {
throw new WechatPayError({
stage: "config",
code: "CONFIG_MISSING",
message: "APIv3 密钥缺失或长度不为 32",
});
}
return key;
}
/**
* 配置诊断:只返回缺失项名称,不输出密钥内容,便于线上日志定位
* @returns {string[]} 缺失/不可用项
*/
function getConfigDiagnostics() {
const cfg = payConfig();
const issues = [];
if (!cfg.mchid) issues.push("mchid 未配置");
if (!cfg.appid) issues.push("appid 未配置");
if (!cfg.merchantSerial) issues.push("merchantSerial 未配置");
if (!cfg.publicKeyId) issues.push("publicKeyId 未配置");
const privatePath = resolvePath(privateKeyPathValue());
if (!privatePath) {
issues.push("privateKeyPath 未配置");
} else {
try {
readFileSync(privatePath, "utf-8");
} catch (err) {
issues.push(`商户私钥不可读:${privatePath}`);
}
}
const publicPath = resolvePath(publicKeyPathValue());
if (!publicPath) {
issues.push("publicKeyPath 未配置");
} else {
try {
readFileSync(publicPath, "utf-8");
} catch (err) {
issues.push(`微信支付公钥不可读:${publicPath}`);
}
}
const envKey = process.env[cfg.apiv3KeyEnv || "WXPAY_APIV3_KEY"] || "";
if (envKey.length !== 32) {
issues.push(`环境变量 ${cfg.apiv3KeyEnv || "WXPAY_APIV3_KEY"} 缺失或长度不为 32`);
}
return issues;
}
/**
* 配置是否完整(商户参数 + 两把证书文件 + APIv3 密钥)
* 缺配置时支付接口降级为「未开放」,不影响下单、取消等其它链路。
*/
function isConfigured() {
return getConfigDiagnostics().length === 0;
}
function requireFullConfig() {
const cfg = payConfig();
if (!isConfigured()) {
throw new WechatPayError({
stage: "config",
code: "CONFIG_MISSING",
message: "微信支付未配置",
});
}
return cfg;
}
// ==================== 金额换算 ====================
/**
* 元 → 分:按小数点拆位,不经过浮点乘法
* @param {string|number} value
* @returns {number|null} 非负整数分;非法输入返回 null
*/
function yuanToFen(value) {
if (value === null || value === undefined || value === "") return null;
const text = String(value).trim();
if (!text) return null;
const matched = /^(\d+)(?:\.(\d{1,2}))?$/.exec(text);
if (!matched) return null;
const yuan = Number(matched[1]);
const cents = Number((matched[2] || "").padEnd(2, "0")) || 0;
const fen = yuan * 100 + cents;
return Number.isSafeInteger(fen) && fen >= 0 ? fen : null;
}
function fenToYuan(fen) {
const value = Number(fen);
if (!Number.isInteger(value)) return "";
return (value / 100).toFixed(2);
}
// ==================== 签名 / 验签 / 解密 ====================
function buildRequestSignature({ method, urlPath, timestamp, nonce, body = "", privateKey }) {
const message = `${String(method || "GET").toUpperCase()}\n${urlPath}\n${timestamp}\n${nonce}\n${body}\n`;
return crypto.createSign("RSA-SHA256").update(message).sign(privateKey, "base64");
}
function buildAuthHeader({ mchid, serialNo, signature, timestamp, nonce }) {
return `WECHATPAY2-SHA256-RSA2048 mchid="${mchid}",nonce_str="${nonce}",signature="${signature}",timestamp="${timestamp}",serial_no="${serialNo}"`;
}
function verifyMessageSignature({ message, signature, publicKeyPem }) {
try {
return crypto.createVerify("RSA-SHA256").update(message).verify(publicKeyPem, signature, "base64");
} catch (err) {
return false;
}
}
function decryptAesGcm({ ciphertext, nonce, associatedData, apiV3Key: keyValue }) {
const key = Buffer.from(keyValue, "utf-8");
if (key.length !== 32) throw new Error("APIv3 密钥长度必须为 32");
const raw = Buffer.from(ciphertext, "base64");
if (raw.length < 17) throw new Error("密文长度不正确");
const authTag = raw.subarray(raw.length - 16);
const payload = raw.subarray(0, raw.length - 16);
const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(nonce, "utf-8"));
decipher.setAuthTag(authTag);
if (associatedData) decipher.setAAD(Buffer.from(associatedData, "utf-8"));
return Buffer.concat([decipher.update(payload), decipher.final()]).toString("utf-8");
}
function formatTimeExpire(value) {
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) return "";
const shifted = new Date(date.getTime() + 8 * 60 * 60 * 1000);
const pad = (num) => String(num).padStart(2, "0");
return `${shifted.getUTCFullYear()}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}`
+ `T${pad(shifted.getUTCHours())}:${pad(shifted.getUTCMinutes())}:${pad(shifted.getUTCSeconds())}+08:00`;
}
/**
* 调起支付参数:paySign 与接口请求签名是两套签名串
*/
function buildPayParams({ prepayId, appId, privateKey }) {
const cfg = payConfig();
const useAppId = appId || cfg.appid;
const key = privateKey || loadPrivateKey();
const timeStamp = String(Math.floor(Date.now() / 1000));
const nonceStr = crypto.randomBytes(16).toString("hex");
const pkg = `prepay_id=${prepayId}`;
const message = `${useAppId}\n${timeStamp}\n${nonceStr}\n${pkg}\n`;
const paySign = crypto.createSign("RSA-SHA256").update(message).sign(key, "base64");
return { timeStamp, nonceStr, package: pkg, signType: "RSA", paySign };
}
// ==================== HTTP 调用 ====================
async function apiRequest({ stage, method = "GET", urlPath, body = "", orderNo = "" }) {
const cfg = requireFullConfig();
const privateKey = loadPrivateKey();
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = crypto.randomBytes(16).toString("hex");
const signature = buildRequestSignature({
method,
urlPath,
timestamp,
nonce,
body,
privateKey,
});
const authorization = buildAuthHeader({
mchid: cfg.mchid,
serialNo: cfg.merchantSerial,
signature,
timestamp,
nonce,
});
let response;
try {
response = await fetch(`${API_BASE}${urlPath}`, {
method,
headers: {
Authorization: authorization,
Accept: "application/json",
"Content-Type": "application/json",
"Accept-Language": "zh-CN",
"User-Agent": "ws-health/1.0",
},
body: body || undefined,
signal: AbortSignal.timeout(REQUEST_TIMEOUT),
});
} catch (err) {
logger.error(`[wechatpay] ${stage} 网络异常: ${err.message}`);
throw new WechatPayError({
stage,
code: "NETWORK_ERROR",
message: err.message,
httpStatus: 0,
});
}
const requestId = response.headers.get("request-id") || "";
const rawBody = await response.text();
let data = {};
try {
data = rawBody ? JSON.parse(rawBody) : {};
} catch (err) {
data = {};
}
if (!response.ok) {
const message = truncate(data.message || rawBody || `HTTP ${response.status}`);
logger.error(`[wechatpay] ${stage} 失败 orderNo=${orderNo} http=${response.status} requestId=${requestId} code=${data.code || ""} message=${message}`);
throw new WechatPayError({
stage,
code: data.code || `HTTP_${response.status}`,
message,
requestId,
httpStatus: response.status,
});
}
// 应答验签:有签名头时按微信支付公钥校验,避免中间人篡改应答
const responseSignature = response.headers.get("wechatpay-signature");
if (responseSignature) {
const responseTimestamp = response.headers.get("wechatpay-timestamp") || "";
const responseNonce = response.headers.get("wechatpay-nonce") || "";
const serial = response.headers.get("wechatpay-serial") || "";
if (cfg.publicKeyId && serial && serial !== cfg.publicKeyId) {
throw new WechatPayError({
stage,
code: "SERIAL_MISMATCH",
message: "微信支付应答公钥序列号不匹配",
requestId,
httpStatus: response.status,
});
}
const message = `${responseTimestamp}\n${responseNonce}\n${rawBody}\n`;
if (!verifyMessageSignature({ message, signature: responseSignature, publicKeyPem: loadPublicKey() })) {
throw new WechatPayError({
stage,
code: "SIGN_ERROR",
message: "微信支付应答验签失败",
requestId,
httpStatus: response.status,
});
}
}
logger.info(`[wechatpay] ${stage} ok orderNo=${orderNo} http=${response.status} requestId=${requestId}`);
return { data, requestId, httpStatus: response.status };
}
// ==================== 支付接口 ====================
async function createJsapiOrder({ outTradeNo, description, totalFee, openid, timeExpireAt, notifyUrl }) {
const cfg = requireFullConfig();
const payload = JSON.stringify({
appid: cfg.appid,
mchid: cfg.mchid,
description: truncateBytes(description || "陪诊服务", 127),
out_trade_no: outTradeNo,
time_expire: formatTimeExpire(timeExpireAt),
notify_url: notifyUrl,
amount: { total: Number(totalFee), currency: "CNY" },
payer: { openid },
});
const { data } = await apiRequest({
stage: "create",
method: "POST",
urlPath: "/v3/pay/transactions/jsapi",
body: payload,
orderNo: outTradeNo,
});
if (!data.prepay_id) {
throw new WechatPayError({
stage: "create",
code: "NO_PREPAY_ID",
message: "微信未返回 prepay_id",
httpStatus: 200,
});
}
return data;
}
async function queryOrder(outTradeNo) {
const cfg = requireFullConfig();
const urlPath = `/v3/pay/transactions/out-trade-no/${encodeURIComponent(outTradeNo)}?mchid=${encodeURIComponent(cfg.mchid)}`;
const { data, requestId, httpStatus } = await apiRequest({ stage: "query", urlPath, orderNo: outTradeNo });
return { ...data, requestId, httpStatus };
}
async function closeOrder(outTradeNo) {
const cfg = requireFullConfig();
const { data } = await apiRequest({
stage: "close",
method: "POST",
urlPath: `/v3/pay/transactions/out-trade-no/${encodeURIComponent(outTradeNo)}/close`,
body: JSON.stringify({ mchid: cfg.mchid }),
orderNo: outTradeNo,
});
return data;
}
async function createRefund({ outTradeNo, outRefundNo, reason, refundAmount, totalAmount, notifyUrl }) {
const reasonText = truncateBytes(reason || "", 80);
const payloadData = {
out_trade_no: outTradeNo,
out_refund_no: outRefundNo,
notify_url: notifyUrl,
amount: {
refund: Number(refundAmount),
total: Number(totalAmount),
currency: "CNY",
},
};
// reason 选填:没有值时不传空串
if (reasonText) payloadData.reason = reasonText;
const payload = JSON.stringify(payloadData);
const { data } = await apiRequest({
stage: "refund",
method: "POST",
urlPath: "/v3/refund/domestic/refunds",
body: payload,
orderNo: outRefundNo,
});
return data;
}
async function queryRefundResult(outRefundNo) {
const urlPath = `/v3/refund/domestic/refunds/${encodeURIComponent(outRefundNo)}`;
const { data, requestId, httpStatus } = await apiRequest({ stage: "refund_query", urlPath, orderNo: outRefundNo });
return { ...data, requestId, httpStatus };
}
function getNotifyUrls() {
const cfg = payConfig();
const base = String(cfg.notifyBase || DEFAULT_NOTIFY_BASE).replace(/\/+$/, "");
return {
payUrl: `${base}/pay/notify`,
refundUrl: `${base}/pay/refund-notify`,
};
}
/**
* 回调验签 + 解密
* @param {Object} options
* @param {Object} options.headers 请求头(小写键)
* @param {string} options.rawBody 原始报文
* @returns {{ eventType: string, resourceType: string, resource: Object, id: string }}
*/
function verifyNotify({ headers = {}, rawBody = "" }) {
const cfg = requireFullConfig();
const timestamp = String(headers["wechatpay-timestamp"] || "");
const nonce = String(headers["wechatpay-nonce"] || "");
const signature = String(headers["wechatpay-signature"] || "");
const serial = String(headers["wechatpay-serial"] || "");
if (!timestamp || !nonce || !signature || !serial) {
throw new WechatPayError({
stage: "notify",
code: "MISSING_SIGNATURE",
message: "回调缺少验签头",
httpStatus: 400,
});
}
// 微信签名探测流量:按失败应答,不当作攻击忽略
if (signature.startsWith("WECHATPAY/SIGNTEST/")) {
logger.warn("[wechatpay] 收到微信支付签名探测流量,按验签失败应答");
throw new WechatPayError({
stage: "notify",
code: "SIGNTEST",
message: "签名探测流量",
httpStatus: 400,
});
}
const nowSeconds = Math.floor(Date.now() / 1000);
if (Math.abs(nowSeconds - Number(timestamp)) > 300) {
throw new WechatPayError({
stage: "notify",
code: "TIMESTAMP_EXPIRED",
message: "回调时间戳超出允许范围",
httpStatus: 400,
});
}
if (cfg.publicKeyId && serial !== cfg.publicKeyId) {
throw new WechatPayError({
stage: "notify",
code: "SERIAL_MISMATCH",
message: "回调公钥序列号不匹配",
httpStatus: 400,
});
}
const message = `${timestamp}\n${nonce}\n${rawBody}\n`;
if (!verifyMessageSignature({ message, signature, publicKeyPem: loadPublicKey() })) {
throw new WechatPayError({
stage: "notify",
code: "SIGN_ERROR",
message: "回调验签失败",
httpStatus: 401,
});
}
let body;
try {
body = JSON.parse(rawBody);
} catch (err) {
throw new WechatPayError({
stage: "notify",
code: "INVALID_BODY",
message: "回调报文不是合法 JSON",
httpStatus: 400,
});
}
const resource = body.resource || {};
if (!resource.ciphertext || !resource.nonce) {
throw new WechatPayError({
stage: "notify",
code: "INVALID_RESOURCE",
message: "回调报文缺少加密资源",
httpStatus: 400,
});
}
let plaintext;
try {
plaintext = decryptAesGcm({
ciphertext: resource.ciphertext,
nonce: resource.nonce,
associatedData: resource.associated_data || "",
apiV3Key: apiV3Key(),
});
} catch (err) {
throw new WechatPayError({
stage: "notify",
code: "DECRYPT_ERROR",
message: err.message,
httpStatus: 400,
});
}
let decrypted;
try {
decrypted = JSON.parse(plaintext);
} catch (err) {
throw new WechatPayError({
stage: "notify",
code: "INVALID_RESOURCE",
message: "解密内容不是合法 JSON",
httpStatus: 400,
});
}
return {
id: body.id || "",
eventType: body.event_type || "",
resourceType: body.resource_type || "",
resource: decrypted,
};
}
export {
WechatPayError,
isConfigured,
getConfigDiagnostics,
yuanToFen,
fenToYuan,
formatTimeExpire,
buildRequestSignature,
buildAuthHeader,
verifyMessageSignature,
decryptAesGcm,
buildPayParams,
getNotifyUrls,
createJsapiOrder,
queryOrder,
closeOrder,
createRefund,
queryRefundResult,
verifyNotify,
};