feat:增加微信支付功能
This commit is contained in:
@@ -2,7 +2,6 @@
|
||||
/logs/
|
||||
/data/
|
||||
.env
|
||||
conf.json
|
||||
# 临时调试文件,正式测试请放 test/
|
||||
/tmp_*
|
||||
/tmp/
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
+158
-11
@@ -1,8 +1,10 @@
|
||||
import { DBModel } from "../models/index.js";
|
||||
import services from "../resource/services.js";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
import logger from "../utils/logger.js";
|
||||
import { isAdmin as isAdminUser, resolveEscortAdminRole } from "../utils/permissions.js";
|
||||
import { canTransition, STATUS_TRANSITIONS } from "../utils/record_state.js";
|
||||
import { HandlerPayment } from "./payment.js";
|
||||
|
||||
class HandlerEscortRecord {
|
||||
constructor() {
|
||||
@@ -25,8 +27,8 @@ class HandlerEscortRecord {
|
||||
"hospital.doctor", "hospital.medicalRecordNo", "schedule.date", "schedule.startTime",
|
||||
];
|
||||
static OWNER_EDITABLE_BY_STATUS = {
|
||||
pending: ["notes.patientNote", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||||
confirmed: ["notes.patientNote", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||||
pending: ["notes.patientNote", "payment.payChannel", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||||
confirmed: ["notes.patientNote", "payment.payChannel", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||||
in_progress: ["notes.patientNote"],
|
||||
};
|
||||
|
||||
@@ -37,6 +39,9 @@ class HandlerEscortRecord {
|
||||
// 支付方式为平台受控枚举(与 schema 一致),空串表示清除/未记录
|
||||
static PAYMENT_METHODS = ["", "online_wechat", "offline_cash", "offline_transfer"];
|
||||
|
||||
// 用户下单时可选择的支付渠道:线下支付不细分现金/转账,由平台收款时补记 method
|
||||
static PAY_CHANNELS = ["online_wechat", "offline"];
|
||||
|
||||
// 单页最大条数,避免 pageSize 传超大值一次拖库
|
||||
static MAX_PAGE_SIZE = 200;
|
||||
|
||||
@@ -86,6 +91,20 @@ class HandlerEscortRecord {
|
||||
&& 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 请求体
|
||||
@@ -219,7 +238,8 @@ class HandlerEscortRecord {
|
||||
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) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
@@ -263,7 +283,7 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.forbidden(ctx, "无权访问该订单");
|
||||
}
|
||||
|
||||
return ResponseUtil.success(ctx, { record }, "查询成功");
|
||||
return ResponseUtil.success(ctx, { record: HandlerEscortRecord.withPaymentWindow(record) }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
@@ -333,12 +353,29 @@ class HandlerEscortRecord {
|
||||
payload.schedule = scheduleResult.schedule;
|
||||
payload.shippingAddress = addressResult.shippingAddress;
|
||||
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 = {
|
||||
totalFee: Number(service.price) || 0,
|
||||
paidFee: 0,
|
||||
status: "unpaid",
|
||||
payChannel,
|
||||
};
|
||||
// 支付方式由平台在收款时补记:仅管理员代客下单时可指定,用户端提交一律丢弃
|
||||
// 实际收款方式由平台在收款时补记:仅管理员代客下单时可指定,用户端提交一律丢弃
|
||||
if (HandlerEscortRecord.isAdmin(ctx.state.user)
|
||||
&& HandlerEscortRecord.PAYMENT_METHODS.includes(body.payment?.method)) {
|
||||
payload.payment.method = body.payment.method;
|
||||
@@ -399,6 +436,60 @@ class HandlerEscortRecord {
|
||||
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 ((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) {
|
||||
@@ -468,6 +559,9 @@ class HandlerEscortRecord {
|
||||
const role = await resolveEscortAdminRole(user);
|
||||
const isOwner = String(existing.userId) === String(user?._id);
|
||||
const paymentStatus = existing.payment?.status || "unpaid";
|
||||
const cancelReason = String(reason || "").trim().slice(0, 200);
|
||||
let effectivePaymentStatus = paymentStatus;
|
||||
let effectivePayment = existing.payment || {};
|
||||
|
||||
let targetStatus = status;
|
||||
if (role !== "admin" && role !== "attendant") {
|
||||
@@ -476,7 +570,25 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.forbidden(ctx, "不支持的状态变更");
|
||||
}
|
||||
if (paymentStatus === "unpaid" && existing.status === "pending") {
|
||||
// 接入微信支付后:删除前必须先关单,否则旧 prepay 仍可支付一张已不存在的订单
|
||||
if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因");
|
||||
// 删除前必须先关单,否则旧 prepay 仍可支付一张已不存在的订单
|
||||
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
|
||||
if (closeResult.paid) {
|
||||
// 关单后发现钱已到账:不能删除,转待取消并等待确认后退款
|
||||
const updated = await DBModel.EscortRecord.updateRecordStatus(id, "pending", {
|
||||
status: "cancel_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);
|
||||
if (!deletedRecord) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
@@ -486,7 +598,17 @@ class HandlerEscortRecord {
|
||||
if (!["pending", "confirmed"].includes(existing.status)) {
|
||||
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
|
||||
}
|
||||
// 申请取消前先关闭未支付的 prepay,避免等待确认期间又被支付
|
||||
await HandlerPayment.closeOpenPayRecords(id);
|
||||
targetStatus = "cancel_requested";
|
||||
} else if (targetStatus === "cancelled" && paymentStatus === "unpaid") {
|
||||
// 平台直接取消待支付订单,同样先关单;关单后发现已支付则按已收款走退款
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
if (!canTransition(existing.status, targetStatus)) {
|
||||
@@ -494,10 +616,8 @@ class HandlerEscortRecord {
|
||||
}
|
||||
|
||||
const update = { status: targetStatus };
|
||||
const cancelReason = String(reason || "").trim().slice(0, 200);
|
||||
if (targetStatus === "cancel_requested") {
|
||||
if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因");
|
||||
// 接入微信支付后:此处应关闭未支付的 prepay,避免申请取消期间又被支付
|
||||
update.cancelReason = cancelReason;
|
||||
update.cancelRequestedAt = new Date();
|
||||
}
|
||||
@@ -506,8 +626,8 @@ class HandlerEscortRecord {
|
||||
if (cancelReason) update.cancelReason = cancelReason;
|
||||
else if (role === "admin" && !existing.cancelReason) update.cancelReason = "平台取消";
|
||||
update.cancelledAt = new Date();
|
||||
// 客服协助支付没有线上自动退款能力:已收款订单先进入退款中,退款完成再由平台核销。
|
||||
if (["partial", "paid"].includes(paymentStatus)) {
|
||||
// 已收款订单先进入退款中;线上支付随后自动原路退款,线下由平台人工核销
|
||||
if (["partial", "paid"].includes(effectivePaymentStatus)) {
|
||||
update["payment.status"] = "refunding";
|
||||
}
|
||||
}
|
||||
@@ -517,6 +637,17 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
|
||||
}
|
||||
|
||||
// 已支付的线上订单:状态落库后再发起原路全额退款
|
||||
if (targetStatus === "cancelled"
|
||||
&& 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 }, "状态更新成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
@@ -542,7 +673,16 @@ class HandlerEscortRecord {
|
||||
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() };
|
||||
if (["partial", "paid"].includes(paymentStatus)) {
|
||||
update.status = "cancelled";
|
||||
@@ -554,6 +694,13 @@ class HandlerEscortRecord {
|
||||
if (!softDeleted) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
}
|
||||
if (update.status === "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 }, "删除成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
|
||||
+1005
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,7 @@
|
||||
import 'dotenv/config';
|
||||
import { APP } from './app.js'
|
||||
import WebSocketServerManager from './websocket.js'
|
||||
import { startPaymentPatrol } from './handler/payment.js'
|
||||
|
||||
// HTTP server
|
||||
const koaApp = new APP();
|
||||
@@ -9,3 +10,6 @@ koaApp.start(parseInt(process.env.PORT || "9004"));
|
||||
// WebSocket server
|
||||
const wsServer = new WebSocketServerManager(parseInt(process.env.WS_PORT || "9005"));
|
||||
wsServer.start();
|
||||
|
||||
// 后台支付巡检查单:默认运行,回调丢失时由此收敛
|
||||
startPaymentPatrol();
|
||||
|
||||
@@ -8,6 +8,8 @@ import { HospitalSchema } from "./schema/hospital.js"
|
||||
import { EmployeeSchema } from "./schema/employee.js"
|
||||
import { EmployeeReviewSchema } from "./schema/employee_review.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 logger from '../utils/logger.js';
|
||||
|
||||
@@ -22,6 +24,8 @@ class MongoDBSchema {
|
||||
this.HealthProfile = null;
|
||||
this.EmployeeReview = null;
|
||||
this.TrainingApplication = null;
|
||||
this.PaymentRecord = null;
|
||||
this.RefundRecord = null;
|
||||
}
|
||||
|
||||
init() {
|
||||
@@ -54,6 +58,8 @@ class MongoDBSchema {
|
||||
this.Employee = this.dbConnection.model('employee', EmployeeSchema)
|
||||
this.EmployeeReview = this.dbConnection.model('employee_review', EmployeeReviewSchema)
|
||||
this.TrainingApplication = this.dbConnection.model('training_application', TrainingApplicationSchema)
|
||||
this.PaymentRecord = this.dbConnection.model('payment_record', PaymentRecordSchema)
|
||||
this.RefundRecord = this.dbConnection.model('refund_record', RefundRecordSchema)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -123,7 +123,19 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
type: String,
|
||||
enum: ["", "online_wechat", "offline_cash", "offline_transfer"],
|
||||
default: "",
|
||||
comment: "支付方式:线上微信、线下现金、线下转账",
|
||||
comment: "实际收款方式:线上微信、线下现金、线下转账",
|
||||
},
|
||||
// 用户选择的支付渠道;历史订单缺失该字段时展示层按 offline 解释
|
||||
payChannel: {
|
||||
type: String,
|
||||
enum: ["online_wechat", "offline"],
|
||||
comment: "用户选择的支付渠道",
|
||||
},
|
||||
// 当前有效支付流水;历史流水保留在 payment_record 中审计
|
||||
paymentRecordId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
default: null,
|
||||
comment: "当前有效支付流水",
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
|
||||
@@ -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 };
|
||||
@@ -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 };
|
||||
@@ -1,5 +1,6 @@
|
||||
import Router from "koa-router";
|
||||
import { HandlerEscortRecord } from "../handler/escort_record.js";
|
||||
import { HandlerPayment } from "../handler/payment.js";
|
||||
import { HandlerHealthProfile } from "../handler/health_profile.js";
|
||||
import { HandlerResource } from "../handler/resource.js";
|
||||
import { HandlerEmployee } from "../handler/employee.js";
|
||||
@@ -75,6 +76,7 @@ function registerRoutes(app) {
|
||||
const router = new Router({ prefix: '/health' });
|
||||
|
||||
const handlerEscortRecord = new HandlerEscortRecord();
|
||||
const handlerPayment = new HandlerPayment();
|
||||
const handlerHealthProfile = new HandlerHealthProfile();
|
||||
const handlerResource = new HandlerResource();
|
||||
const handlerEmployee = new HandlerEmployee();
|
||||
@@ -82,11 +84,22 @@ function registerRoutes(app) {
|
||||
const handlerTrainingApplication = new HandlerTrainingApplication();
|
||||
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/attendant", requireAuth, handlerEscortRecord.getAttendantRecords.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.post("/escort-record", requireAuth, createLimit, handlerEscortRecord.createRecord.bind(handlerEscortRecord));
|
||||
router.put("/escort-record/:id", requireAuth, updateLimit, handlerEscortRecord.updateRecord.bind(handlerEscortRecord));
|
||||
|
||||
@@ -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,
|
||||
}));
|
||||
});
|
||||
@@ -0,0 +1,531 @@
|
||||
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);
|
||||
}
|
||||
|
||||
let cachedPrivateKey = null;
|
||||
let cachedPublicKey = null;
|
||||
|
||||
function loadPrivateKey() {
|
||||
const cfg = payConfig();
|
||||
if (!cachedPrivateKey && cfg.privateKeyPath) {
|
||||
cachedPrivateKey = readFileSync(resolvePath(cfg.privateKeyPath), "utf-8");
|
||||
}
|
||||
return cachedPrivateKey;
|
||||
}
|
||||
|
||||
function loadPublicKey() {
|
||||
const cfg = payConfig();
|
||||
if (!cachedPublicKey && cfg.publicKeyPath) {
|
||||
cachedPublicKey = readFileSync(resolvePath(cfg.publicKeyPath), "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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置是否完整(商户参数 + 两把证书文件 + APIv3 密钥)
|
||||
* 缺配置时支付接口降级为「未开放」,不影响下单、取消等其它链路。
|
||||
*/
|
||||
function isConfigured() {
|
||||
const cfg = payConfig();
|
||||
if (!cfg.mchid || !cfg.appid || !cfg.merchantSerial || !cfg.publicKeyId) return false;
|
||||
const privatePath = resolvePath(cfg.privateKeyPath);
|
||||
const publicPath = resolvePath(cfg.publicKeyPath);
|
||||
if (!privatePath || !publicPath) return false;
|
||||
try {
|
||||
readFileSync(privatePath, "utf-8");
|
||||
readFileSync(publicPath, "utf-8");
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
const envKey = process.env[cfg.apiv3KeyEnv || "WXPAY_APIV3_KEY"] || "";
|
||||
return envKey.length === 32;
|
||||
}
|
||||
|
||||
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,
|
||||
yuanToFen,
|
||||
fenToYuan,
|
||||
formatTimeExpire,
|
||||
buildRequestSignature,
|
||||
buildAuthHeader,
|
||||
verifyMessageSignature,
|
||||
decryptAesGcm,
|
||||
buildPayParams,
|
||||
getNotifyUrls,
|
||||
createJsapiOrder,
|
||||
queryOrder,
|
||||
closeOrder,
|
||||
createRefund,
|
||||
queryRefundResult,
|
||||
verifyNotify,
|
||||
};
|
||||
Reference in New Issue
Block a user