From 23b9de16a6f10b1b4c485143e40f1b94a8d86b9f Mon Sep 17 00:00:00 2001 From: lik Date: Thu, 5 Nov 2026 16:31:51 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E5=A2=9E=E5=8A=A0=E5=BE=AE=E4=BF=A1?= =?UTF-8?q?=E6=94=AF=E4=BB=98=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 - conf.json | 91 +++ handler/escort_record.js | 169 +++++- handler/payment.js | 1005 +++++++++++++++++++++++++++++++ index.js | 4 + models/index.js | 6 + models/schema/escort_record.js | 14 +- models/schema/payment_record.js | 112 ++++ models/schema/refund_record.js | 91 +++ routes/index.js | 13 + test/payment.test.js | 102 ++++ utils/wechatpay.js | 531 ++++++++++++++++ 12 files changed, 2126 insertions(+), 13 deletions(-) create mode 100644 conf.json create mode 100644 handler/payment.js create mode 100644 models/schema/payment_record.js create mode 100644 models/schema/refund_record.js create mode 100644 test/payment.test.js create mode 100644 utils/wechatpay.js diff --git a/.gitignore b/.gitignore index 755e8cc..53efbb5 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ /logs/ /data/ .env -conf.json # 临时调试文件,正式测试请放 test/ /tmp_* /tmp/ diff --git a/conf.json b/conf.json new file mode 100644 index 0000000..8be1cf3 --- /dev/null +++ b/conf.json @@ -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 + } +} \ No newline at end of file diff --git a/handler/escort_record.js b/handler/escort_record.js index 0579c55..1f35b5b 100644 --- a/handler/escort_record.js +++ b/handler/escort_record.js @@ -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); diff --git a/handler/payment.js b/handler/payment.js new file mode 100644 index 0000000..28aa7d6 --- /dev/null +++ b/handler/payment.js @@ -0,0 +1,1005 @@ +import mongoose from "mongoose"; + +import { DBModel } from "../models/index.js"; +import config from "../config.js"; +import logger from "../utils/logger.js"; +import ResponseUtil from "../utils/responseUtil.js"; +import { isAdmin } from "../utils/permissions.js"; +import * as wxpay from "../utils/wechatpay.js"; + +const { WechatPayError } = wxpay; + +const PAYABLE_ORDER_STATUS = ["pending", "confirmed"]; +const ACTIVE_PAYMENT_STATUS = ["created", "closed_unconfirmed"]; +const DEFAULT_REFUND_REASON = "订单取消"; + +// 同一订单的 createPayment 串行执行,防止并发产生多条在途流水 +const payLocks = new Map(); + +function withPayLock(key, fn) { + const previous = payLocks.get(key) || Promise.resolve(); + const current = previous.then(fn, fn); + payLocks.set(key, current.finally(() => { + if (payLocks.get(key) === current) payLocks.delete(key); + })); + return current; +} + +function isValidObjectId(value) { + return mongoose.Types.ObjectId.isValid(value); +} + +function nowMs() { + return Date.now(); +} + +function toDate(value) { + if (!value) return null; + const date = value instanceof Date ? value : new Date(value); + return Number.isNaN(date.getTime()) ? null : date; +} + +function replySuccess(ctx) { + // 官方约定:验签通过应答 200/204,无需返回应答报文 + ctx.status = 200; + ctx.type = "application/json"; + ctx.body = ""; +} + +function replyFail(ctx, httpStatus, message) { + ctx.status = httpStatus >= 400 && httpStatus < 600 ? httpStatus : 500; + ctx.type = "application/json"; + ctx.body = JSON.stringify({ code: "FAIL", message: String(message || "处理失败").slice(0, 200) }); +} + +class HandlerPayment { + /** + * 支付窗口终点:订单创建时间 + payWindowHours,且不晚于服务开始当天 23:59:59(+08:00) + * 窗口起点固定为下单时间,重复发起支付不延长。 + * @param {Object} record escort_record 文档或 plain object + * @returns {Date|null} + */ + static getPayWindowEnd(record) { + const meta = record?.meta || {}; + const created = toDate(meta.createtime || meta.updatetime); + if (!created) return null; + + const cfg = config.wechatpay || {}; + const hours = Number(cfg.payWindowHours); + const windowHours = Number.isFinite(hours) && hours > 0 ? hours : 24; + let end = created.getTime() + windowHours * 60 * 60 * 1000; + + const scheduleDate = toDate(record?.schedule?.date); + if (scheduleDate) { + // schedule.date 以 UTC 零点保存;服务开始当天 23:59:59.999(+08:00)= 同日 15:59:59.999 UTC + const dayEnd = Date.UTC( + scheduleDate.getUTCFullYear(), + scheduleDate.getUTCMonth(), + scheduleDate.getUTCDate(), + 15, 59, 59, 999 + ); + if (dayEnd < end) end = dayEnd; + } + return new Date(end); + } + + static isPayWindowExpired(record, now = new Date()) { + const end = HandlerPayment.getPayWindowEnd(record); + if (!end) return false; + return now.getTime() > end.getTime(); + } + + /** + * 订单访问权:本人、管理员、该单陪诊师 + */ + static canAccess(user, record) { + if (!record) return false; + if (isAdmin(user)) return true; + if (String(record.userId) === String(user?._id)) return true; + return Boolean(record.attendant?.id) && String(record.attendant.id) === String(user?._id); + } + + static mapTransaction(source = {}) { + return { + transactionId: source.transaction_id || "", + payerTotal: Number(source.amount?.payer_total ?? source.amount?.total ?? 0), + bankType: source.bank_type || "", + successTime: toDate(source.success_time), + }; + } + + /** + * 查单结果入账前核对:商户号 / appid / 金额必须与本地流水一致, + * 验签只证明报文来自微信,不证明这笔钱属于这笔订单。 + */ + static verifyTrade(trade = {}, payment) { + const cfg = config.wechatpay || {}; + const mismatch = (code, message) => new WechatPayError({ + stage: "query", + code, + message, + requestId: trade.requestId || "", + httpStatus: trade.httpStatus || 200, + }); + + if (trade.mchid && String(trade.mchid) !== String(cfg.mchid || "")) { + throw mismatch("MCHID_MISMATCH", "查单商户号与本地配置不一致"); + } + if (trade.appid && String(trade.appid) !== String(cfg.appid || "")) { + throw mismatch("APPID_MISMATCH", "查单 appid 与本地配置不一致"); + } + if (String(trade.amount?.currency || "") !== "CNY" + || Number(trade.amount?.total) !== Number(payment.totalFee)) { + throw mismatch("AMOUNT_MISMATCH", "查单金额与本地流水不一致"); + } + return true; + } + + static async markPaymentError(paymentId, err, stage) { + if (!paymentId) return; + const detail = { + stage: err?.stage || stage || "", + code: err?.code || "UNKNOWN", + message: err?.message || String(err || ""), + requestId: err?.requestId || "", + httpStatus: err?.httpStatus || 0, + at: new Date(), + }; + try { + await DBModel.PaymentRecord.markError(paymentId, detail); + } catch (updateErr) { + logger.error( + `[payment] 写支付错误信息失败 paymentId=${paymentId} code=${detail.code} requestId=${detail.requestId}: ${updateErr.message}` + ); + } + } + + static async markRefundError(refundId, err, stage) { + if (!refundId) return; + const detail = { + stage: err?.stage || stage || "", + code: err?.code || "UNKNOWN", + message: err?.message || String(err || ""), + requestId: err?.requestId || "", + httpStatus: err?.httpStatus || 0, + at: new Date(), + }; + try { + await DBModel.RefundRecord.markError(refundId, detail); + } catch (updateErr) { + logger.error( + `[payment] 写退款错误信息失败 refundId=${refundId} code=${detail.code} requestId=${detail.requestId}: ${updateErr.message}` + ); + } + } + + static async setPaymentStatus(paymentId, status, extra = {}) { + await DBModel.PaymentRecord.updateOne( + { _id: paymentId }, + { $set: { ...extra, status, "meta.updatetime": nowMs() } } + ); + } + + /** + * 支付成功收敛:流水 → pay_success,订单快照 → paid + * 订单已取消时不刷 paid,返回 cancelled 由调用方发起退款。 + * @returns {{ payment: Object, record: Object|null, cancelled: boolean }} + */ + static async applyPaymentSuccess(paymentRecord, transaction = {}) { + const setFields = { + status: "pay_success", + payerTotal: Number(transaction.payerTotal) || Number(paymentRecord.totalFee) || 0, + bankType: transaction.bankType || paymentRecord.bankType || "", + successTime: transaction.successTime || paymentRecord.successTime || new Date(), + paidAt: new Date(), + "meta.updatetime": nowMs(), + }; + // 稀疏唯一索引:没有真实交易号时不要写入空串,否则第二条流水会撞唯一索引 + const transactionId = transaction.transactionId || paymentRecord.transactionId; + if (transactionId) setFields.transactionId = transactionId; + + const updated = await DBModel.PaymentRecord.findOneAndUpdate( + { _id: paymentRecord._id, status: { $in: ACTIVE_PAYMENT_STATUS } }, + { $set: setFields }, + { new: true } + ); + const payment = updated || await DBModel.PaymentRecord.findById(paymentRecord._id) || paymentRecord; + + const record = await DBModel.EscortRecord.findById(payment.recordId); + if (!record || record.deletedAt) { + return { payment, record: null, cancelled: true }; + } + if (record.status === "cancelled") { + return { payment, record, cancelled: true }; + } + // 已进入退款阶段的流水不再回刷 paid,避免快照倒退 + if (!["refunding", "refunded"].includes(payment.status)) { + await DBModel.EscortRecord.updateRecord(payment.recordId, { + "payment.status": "paid", + "payment.method": "online_wechat", + "payment.paidFee": Number(record.payment?.totalFee) || 0, + "payment.paymentRecordId": payment._id, + }); + } + return { payment, record, cancelled: false }; + } + + /** + * 关闭该单所有在途流水(切换线下 / 取消 / 删除 / 支付窗口到期的前置动作) + * 关单失败必须当场查单:已支付则收敛为 pay_success,否则标记 closed_unconfirmed 放行。 + * @returns {{ closed: number, paid: number, unconfirmed: number }} + */ + static async closeOpenPayRecords(recordId) { + const result = { closed: 0, paid: 0, unconfirmed: 0 }; + if (!isValidObjectId(recordId)) return result; + + const payments = await DBModel.PaymentRecord.find({ + recordId, + status: { $in: ACTIVE_PAYMENT_STATUS }, + }); + + for (const payment of payments) { + if (!wxpay.isConfigured()) { + // 未配置时无法关单,按「结果不确定」留痕,避免误以为已关 + await HandlerPayment.setPaymentStatus(payment._id, "closed_unconfirmed", { + closeUnconfirmed: true, + }); + result.unconfirmed += 1; + continue; + } + + try { + await wxpay.closeOrder(payment.outTradeNo); + await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() }); + result.closed += 1; + continue; + } catch (err) { + await HandlerPayment.markPaymentError(payment._id, err, "close"); + if (err instanceof WechatPayError && err.code === "ORDER_CLOSED") { + await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() }); + result.closed += 1; + continue; + } + } + + // 关单失败:立即查单确认,不等巡检 + try { + const trade = await wxpay.queryOrder(payment.outTradeNo); + if (trade.trade_state === "SUCCESS") { + HandlerPayment.verifyTrade(trade, payment); + await HandlerPayment.applyPaymentSuccess(payment, HandlerPayment.mapTransaction(trade)); + result.paid += 1; + } else { + await HandlerPayment.setPaymentStatus(payment._id, "closed_unconfirmed", { + closeUnconfirmed: true, + }); + result.unconfirmed += 1; + } + } catch (queryErr) { + await HandlerPayment.markPaymentError(payment._id, queryErr, "query"); + await HandlerPayment.setPaymentStatus(payment._id, "closed_unconfirmed", { + closeUnconfirmed: true, + }); + result.unconfirmed += 1; + } + } + return result; + } + + static async applyRefundResult(refundRecord, result = {}) { + // 退款回调字段为 refund_status,退款申请/查询接口字段为 status + const rawStatus = String(result.refund_status || result.status || ""); + const statusMap = { + SUCCESS: "success", + ABNORMAL: "abnormal", + CLOSED: "closed", + PROCESSING: "processing", + }; + const status = statusMap[rawStatus] || refundRecord.status; + const setFields = { + status, + userReceivedAccount: result.user_received_account || refundRecord.userReceivedAccount || "", + successTime: toDate(result.success_time) || refundRecord.successTime || null, + lastQueriedAt: new Date(), + "meta.updatetime": nowMs(), + }; + // 同 transactionId:refundId 为稀疏唯一索引,无值时不能写空串 + const refundId = result.refund_id || refundRecord.refundId; + if (refundId) setFields.refundId = refundId; + + await DBModel.RefundRecord.updateOne( + { _id: refundRecord._id }, + { $set: setFields } + ); + + if (status === "success") { + await DBModel.PaymentRecord.updateOne( + { _id: refundRecord.paymentId }, + { $set: { status: "refunded", "meta.updatetime": nowMs() } } + ); + await DBModel.EscortRecord.updateOne( + { _id: refundRecord.recordId }, + { $set: { "payment.status": "refunded", "meta.updatetime": nowMs() } } + ); + } else { + await DBModel.PaymentRecord.updateOne( + { _id: refundRecord.paymentId }, + { $set: { status: "refunding", "meta.updatetime": nowMs() } } + ); + await DBModel.EscortRecord.updateOne( + { _id: refundRecord.recordId }, + { $set: { "payment.status": "refunding", "meta.updatetime": nowMs() } } + ); + } + return status; + } + + /** + * 取消已支付订单的自动原路退款(一单一笔全额退款,outRefundNo 固定 -R1) + * 先落 refund_record(processing) 再调接口;超时/系统异常先查退款,未受理则原单号重试一次。 + */ + static async createRefundForRecord(record, { reason } = {}) { + const recordId = record?._id ? String(record._id) : ""; + if (!isValidObjectId(recordId)) return { skipped: true }; + + const payment = await DBModel.PaymentRecord.findOne({ + recordId, + status: { $in: ["pay_success", "refunding"] }, + }).sort({ paidAt: -1, createdAt: -1 }); + if (!payment) return { skipped: true }; + + const outRefundNo = `${recordId}-R1`; + const existing = await DBModel.RefundRecord.findOne({ outRefundNo }); + if (existing) { + if (existing.status === "success") { + await HandlerPayment.applyRefundResult(existing, { + status: "SUCCESS", + refund_id: existing.refundId, + user_received_account: existing.userReceivedAccount, + success_time: existing.successTime, + }); + return existing; + } + // processing 不重复调接口;abnormal/closed 转人工 + return existing; + } + + if (!wxpay.isConfigured()) { + logger.warn(`[payment] 退款未执行:微信支付未配置 recordId=${recordId}`); + return { skipped: true }; + } + + const refundReason = String(reason || record?.cancelReason || DEFAULT_REFUND_REASON).slice(0, 120); + let refundRecord; + try { + refundRecord = await DBModel.RefundRecord.create({ + paymentId: payment._id, + recordId: payment.recordId, + outTradeNo: payment.outTradeNo, + outRefundNo, + refundAmount: Number(payment.totalFee) || 0, + totalAmount: Number(payment.totalFee) || 0, + reason: refundReason, + status: "processing", + createdAt: new Date(), + }); + } catch (err) { + if (err?.code === 11000) { + return await DBModel.RefundRecord.findOne({ outRefundNo }); + } + throw err; + } + + // 先落库再调外部接口,并先把订单快照置为退款中 + await DBModel.EscortRecord.updateOne( + { _id: payment.recordId, "payment.status": { $ne: "refunded" } }, + { $set: { "payment.status": "refunding", "meta.updatetime": nowMs() } } + ); + + const refundParams = { + outTradeNo: payment.outTradeNo, + outRefundNo, + reason: refundReason, + refundAmount: Number(payment.totalFee) || 0, + totalAmount: Number(payment.totalFee) || 0, + notifyUrl: wxpay.getNotifyUrls().refundUrl, + }; + + try { + const result = await wxpay.createRefund(refundParams); + await HandlerPayment.applyRefundResult(refundRecord, result); + return await DBModel.RefundRecord.findById(refundRecord._id); + } catch (err) { + await HandlerPayment.markRefundError(refundRecord._id, err, "refund"); + const uncertain = err instanceof WechatPayError + && (err.code === "NETWORK_ERROR" || err.httpStatus >= 500 || err.httpStatus === 0); + + if (!uncertain) { + // 明确业务错误(余额不足等)转人工,保持 processing + logger.error(`[payment] 退款业务失败 recordId=${recordId} code=${err?.code || ""} requestId=${err?.requestId || ""}`); + return await DBModel.RefundRecord.findById(refundRecord._id); + } + + // 结果不确定:先查退款确认是否已受理 + try { + const queried = await wxpay.queryRefundResult(outRefundNo); + await HandlerPayment.applyRefundResult(refundRecord, queried); + return await DBModel.RefundRecord.findById(refundRecord._id); + } catch (queryErr) { + await HandlerPayment.markRefundError(refundRecord._id, queryErr, "refund_query"); + } + + // 未查到受理记录:同一 outRefundNo 原参数重试一次 + try { + const retried = await wxpay.createRefund(refundParams); + await HandlerPayment.applyRefundResult(refundRecord, retried); + } catch (retryErr) { + await HandlerPayment.markRefundError(refundRecord._id, retryErr, "refund"); + logger.error(`[payment] 退款重试仍失败 recordId=${recordId} code=${retryErr?.code || ""} requestId=${retryErr?.requestId || ""}`); + } + return await DBModel.RefundRecord.findById(refundRecord._id); + } + } + + // ==================== HTTP 入口 ==================== + + /** + * POST /escort-record/:id/pay + */ + async createPayment(ctx) { + const id = ctx.params.id; + const user = ctx.state.user; + if (!isValidObjectId(id)) return ResponseUtil.badRequest(ctx, "缺少记录ID"); + + return withPayLock(String(id), async () => { + try { + const record = await DBModel.EscortRecord.findById(id); + if (!record || record.deletedAt) return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404); + if (String(record.userId) !== String(user?._id)) { + return ResponseUtil.forbidden(ctx, "只能支付自己的订单"); + } + + const payChannel = record.payment?.payChannel || "offline"; + if (payChannel !== "online_wechat") { + return ResponseUtil.badRequest(ctx, "请先切换为微信支付"); + } + if (!PAYABLE_ORDER_STATUS.includes(record.status)) { + return ResponseUtil.badRequest(ctx, "当前订单状态不支持支付"); + } + if ((record.payment?.status || "unpaid") !== "unpaid") { + return ResponseUtil.badRequest(ctx, "订单已支付,请勿重复支付"); + } + if (!wxpay.isConfigured()) { + return ResponseUtil.error(ctx, "支付功能暂未开放,请选择线下支付", null, 503); + } + + const totalFeeFen = wxpay.yuanToFen(record.payment?.totalFee); + if (!totalFeeFen || totalFeeFen <= 0) { + return ResponseUtil.badRequest(ctx, "订单金额不正确,暂不能线上支付"); + } + + const windowEnd = HandlerPayment.getPayWindowEnd(record); + if (!windowEnd) return ResponseUtil.badRequest(ctx, "订单时间信息异常,暂不能支付"); + const now = new Date(); + if (HandlerPayment.isPayWindowExpired(record, now)) { + return ResponseUtil.badRequest(ctx, "支付已超时,请选择线下支付或取消订单"); + } + // time_expire 必须落在 now + 1 分钟 ~ now + 15 天;超出微信上限时按上限内收 + const minExpire = now.getTime() + 60 * 1000; + if (windowEnd.getTime() < minExpire) { + return ResponseUtil.badRequest(ctx, "支付已超时,请选择线下支付或取消订单"); + } + const maxExpire = now.getTime() + 15 * 24 * 60 * 60 * 1000; + const timeExpireAt = windowEnd.getTime() > maxExpire ? new Date(maxExpire - 1000) : windowEnd; + + const openid = String(user?.app?.["wxapp-escort"]?.wxopenid || ""); + if (!openid) return ResponseUtil.badRequest(ctx, "请先登录小程序"); + + let payment = null; + const currentId = record.payment?.paymentRecordId; + if (currentId) { + payment = await DBModel.PaymentRecord.findOne({ _id: currentId, status: "created" }); + } + + // 关单结果不确定的流水先查单确认,避免在可能已支付的单上继续创建新流水 + if (!payment) { + const unconfirmed = await DBModel.PaymentRecord.findOne({ + recordId: record._id, + status: "closed_unconfirmed", + }).sort({ createdAt: -1 }); + if (unconfirmed) { + try { + const trade = await wxpay.queryOrder(unconfirmed.outTradeNo); + if (trade.trade_state === "SUCCESS") { + HandlerPayment.verifyTrade(trade, unconfirmed); + await HandlerPayment.applyPaymentSuccess( + unconfirmed, + HandlerPayment.mapTransaction(trade) + ); + return ResponseUtil.badRequest(ctx, "订单已支付,请勿重复支付"); + } + } catch (err) { + await HandlerPayment.markPaymentError(unconfirmed._id, err, "query"); + } + } + } + + if (!payment) { + payment = await DBModel.PaymentRecord.findOne({ + recordId: record._id, + status: "created", + }).sort({ createdAt: -1 }); + } + + // 已有在途流水但金额与当前订单不一致(如被绕过改价):先关单再换新号 + if (payment && Number(payment.totalFee) !== totalFeeFen) { + try { + await wxpay.closeOrder(payment.outTradeNo); + await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() }); + } catch (err) { + await HandlerPayment.markPaymentError(payment._id, err, "close"); + } + payment = null; + } + + if (!payment) { + const attemptNo = (await DBModel.PaymentRecord.countDocuments({ recordId: record._id })) + 1; + const outTradeNo = `${record._id}-${attemptNo}`; + payment = await DBModel.PaymentRecord.create({ + bizType: "escort", + recordId: record._id, + userId: record.userId, + outTradeNo, + attemptNo, + totalFee: totalFeeFen, + timeExpireAt, + appid: config.wechatpay?.appid || "", + mchid: config.wechatpay?.mchid || "", + tradeType: "JSAPI", + status: "created", + createdAt: new Date(), + }); + } + + const prepayUsable = payment.prepayId + && payment.prepayExpiresAt + && new Date(payment.prepayExpiresAt).getTime() > nowMs(); + + if (!prepayUsable) { + const result = await wxpay.createJsapiOrder({ + outTradeNo: payment.outTradeNo, + description: `陪诊服务-${record.escort?.serviceName || "陪诊服务"}`, + totalFee: Number(payment.totalFee), + openid, + timeExpireAt: payment.timeExpireAt || timeExpireAt, + notifyUrl: wxpay.getNotifyUrls().payUrl, + }); + const prepayExpiresAt = new Date(nowMs() + 2 * 60 * 60 * 1000); + payment = await DBModel.PaymentRecord.findOneAndUpdate( + { _id: payment._id }, + { + $set: { + prepayId: result.prepay_id, + prepayedAt: new Date(), + prepayExpiresAt, + lastAttemptAt: new Date(), + "meta.updatetime": nowMs(), + }, + }, + { new: true } + ); + } else { + await DBModel.PaymentRecord.updateOne( + { _id: payment._id }, + { $set: { lastAttemptAt: new Date(), "meta.updatetime": nowMs() } } + ); + } + + await DBModel.EscortRecord.updateRecord(record._id, { + "payment.paymentRecordId": payment._id, + }); + + const payParams = wxpay.buildPayParams({ prepayId: payment.prepayId }); + return ResponseUtil.success(ctx, { + payParams, + payment: { + outTradeNo: payment.outTradeNo, + attemptNo: payment.attemptNo, + timeExpireAt: payment.timeExpireAt, + }, + }, "下单成功"); + } catch (err) { + if (err instanceof WechatPayError) { + logger.error( + `[payment] 发起支付失败 recordId=${id} stage=${err.stage} code=${err.code} requestId=${err.requestId} message=${err.message}` + ); + } else { + logger.error(`[payment] 发起支付异常 recordId=${id}: ${err?.stack || err?.message || err}`); + } + const latest = await DBModel.PaymentRecord.findOne({ + recordId: id, + status: { $in: ACTIVE_PAYMENT_STATUS }, + }).sort({ createdAt: -1 }).catch(() => null); + if (latest) await HandlerPayment.markPaymentError(latest._id, err, "create"); + return ResponseUtil.error(ctx, "支付发起失败,请稍后重试;如持续失败可改用线下支付", null, 500); + } + }); + } + + /** + * GET /escort-record/:id/pay/status + */ + async queryPayment(ctx) { + try { + const id = ctx.params.id; + if (!isValidObjectId(id)) return ResponseUtil.badRequest(ctx, "缺少记录ID"); + const record = await DBModel.EscortRecord.findById(id); + if (!record || record.deletedAt) return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404); + if (!HandlerPayment.canAccess(ctx.state.user, record)) { + return ResponseUtil.forbidden(ctx, "无权访问该订单"); + } + + let tradeState = null; + let payment = null; + const currentId = record.payment?.paymentRecordId; + if (currentId) { + payment = await DBModel.PaymentRecord.findById(currentId); + } + if (!payment) { + payment = await DBModel.PaymentRecord.findOne({ recordId: record._id }).sort({ createdAt: -1 }); + } + + if (payment && payment.status === "pay_success") { + // 快照刷新失败时,查单/回页面入口也负责把订单补成 paid(幂等) + const applied = await HandlerPayment.applyPaymentSuccess(payment, {}); + if (applied.cancelled) { + setImmediate(() => { + HandlerPayment.createRefundForRecord(applied.record || { _id: payment.recordId }, { + reason: DEFAULT_REFUND_REASON, + }).catch((refundErr) => { + logger.error(`[payment] 已取消订单自动退款失败 recordId=${payment.recordId}: ${refundErr?.message || refundErr}`); + }); + }); + } + payment = await DBModel.PaymentRecord.findById(payment._id) || payment; + } + + if (payment && ACTIVE_PAYMENT_STATUS.includes(payment.status) && wxpay.isConfigured()) { + try { + const trade = await wxpay.queryOrder(payment.outTradeNo); + tradeState = trade.trade_state || null; + if (trade.trade_state === "SUCCESS") { + HandlerPayment.verifyTrade(trade, payment); + const applied = await HandlerPayment.applyPaymentSuccess( + payment, + HandlerPayment.mapTransaction(trade) + ); + if (applied.cancelled) { + setImmediate(() => { + HandlerPayment.createRefundForRecord(applied.record || { _id: payment.recordId }, { + reason: DEFAULT_REFUND_REASON, + }).catch((refundErr) => { + logger.error(`[payment] 已取消订单自动退款失败 recordId=${payment.recordId}: ${refundErr?.message || refundErr}`); + }); + }); + } + } else { + const expireAt = toDate(payment.timeExpireAt); + if (payment.status === "created" && trade.trade_state === "NOTPAY" + && expireAt && nowMs() > expireAt.getTime()) { + await HandlerPayment.closeExpiredPayment(payment); + } else if (payment.status === "closed_unconfirmed") { + await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() }); + } + } + } catch (err) { + await HandlerPayment.markPaymentError(payment._id, err, "query"); + } + payment = await DBModel.PaymentRecord.findById(payment._id) || payment; + } + + const fresh = await DBModel.EscortRecord.findById(id) || record; + return ResponseUtil.success(ctx, { + paymentStatus: fresh.payment?.status || "unpaid", + orderStatus: fresh.status, + payChannel: fresh.payment?.payChannel || "offline", + expired: HandlerPayment.isPayWindowExpired(fresh), + tradeState, + payment: payment + ? { + outTradeNo: payment.outTradeNo, + attemptNo: payment.attemptNo, + status: payment.status, + prepayExpiresAt: payment.prepayExpiresAt || null, + timeExpireAt: payment.timeExpireAt || null, + } + : null, + }, "查询成功"); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + + static async closeExpiredPayment(payment) { + try { + await wxpay.closeOrder(payment.outTradeNo); + await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() }); + return; + } catch (err) { + await HandlerPayment.markPaymentError(payment._id, err, "close"); + } + try { + const trade = await wxpay.queryOrder(payment.outTradeNo); + if (trade.trade_state === "SUCCESS") { + HandlerPayment.verifyTrade(trade, payment); + await HandlerPayment.applyPaymentSuccess(payment, HandlerPayment.mapTransaction(trade)); + } else { + await HandlerPayment.setPaymentStatus(payment._id, "closed_unconfirmed", { + closeUnconfirmed: true, + }); + } + } catch (queryErr) { + await HandlerPayment.markPaymentError(payment._id, queryErr, "query"); + await HandlerPayment.setPaymentStatus(payment._id, "closed_unconfirmed", { + closeUnconfirmed: true, + }); + } + } + + /** + * POST /pay/notify (微信服务器直调,无鉴权,靠验签) + */ + async paymentNotify(ctx) { + const rawBody = ctx.request.rawBody || JSON.stringify(ctx.request.body || {}); + let payload; + try { + payload = wxpay.verifyNotify({ headers: ctx.headers, rawBody }); + } catch (err) { + logger.warn( + `[payment] 支付回调验签失败 code=${err?.code || ""} requestId=${err?.requestId || ""} message=${err?.message || ""}` + ); + return replyFail(ctx, err?.httpStatus || 400, err?.code || "VERIFY_FAILED"); + } + + try { + if (payload.eventType !== "TRANSACTION.SUCCESS") { + return replySuccess(ctx); + } + + const tx = payload.resource || {}; + if (tx.trade_state && tx.trade_state !== "SUCCESS") { + logger.error(`[payment] 支付回调交易状态异常 outTradeNo=${tx.out_trade_no || ""} state=${tx.trade_state}`); + return replySuccess(ctx); + } + const cfg = config.wechatpay || {}; + if (String(tx.mchid || "") !== String(cfg.mchid || "") + || String(tx.appid || "") !== String(cfg.appid || "")) { + logger.error(`[payment] 支付回调商户/应用不匹配 outTradeNo=${tx.out_trade_no || ""}`); + return replyFail(ctx, 500, "FIELD_MISMATCH"); + } + + const payment = await DBModel.PaymentRecord.findOne({ outTradeNo: tx.out_trade_no }); + if (!payment) { + logger.error(`[payment] 支付回调找不到流水 outTradeNo=${tx.out_trade_no || ""}`); + return replySuccess(ctx); + } + + if (String(tx.amount?.currency || "") !== "CNY" + || Number(tx.amount?.total) !== Number(payment.totalFee)) { + logger.error( + `[payment] 支付回调金额不匹配 outTradeNo=${payment.outTradeNo} local=${payment.totalFee} remote=${tx.amount?.total} currency=${tx.amount?.currency}` + ); + return replyFail(ctx, 500, "AMOUNT_MISMATCH"); + } + + if (["refunding", "refunded"].includes(payment.status)) { + return replySuccess(ctx); + } + + const applied = await HandlerPayment.applyPaymentSuccess( + payment, + HandlerPayment.mapTransaction(tx) + ); + replySuccess(ctx); + + if (applied.cancelled) { + // 钱已到账但订单已取消:应答之后再异步原路退款,不占用 5 秒应答窗口 + setImmediate(() => { + HandlerPayment.createRefundForRecord(applied.record || { _id: payment.recordId }, { + reason: DEFAULT_REFUND_REASON, + }).catch((err) => { + logger.error(`[payment] 已取消订单自动退款失败 recordId=${payment.recordId}: ${err?.message || err}`); + }); + }); + } + return undefined; + } catch (err) { + logger.error(`[payment] 支付回调处理异常: ${err?.stack || err?.message || err}`); + return replyFail(ctx, 500, "FAIL"); + } + } + + /** + * POST /pay/refund-notify + */ + async refundNotify(ctx) { + const rawBody = ctx.request.rawBody || JSON.stringify(ctx.request.body || {}); + let payload; + try { + payload = wxpay.verifyNotify({ headers: ctx.headers, rawBody }); + } catch (err) { + logger.warn( + `[payment] 退款回调验签失败 code=${err?.code || ""} requestId=${err?.requestId || ""} message=${err?.message || ""}` + ); + return replyFail(ctx, err?.httpStatus || 400, err?.code || "VERIFY_FAILED"); + } + + try { + const resource = payload.resource || {}; + const cfg = config.wechatpay || {}; + if (resource.mchid && String(resource.mchid) !== String(cfg.mchid || "")) { + logger.error(`[payment] 退款回调商户不匹配 outRefundNo=${resource.out_refund_no || ""}`); + return replyFail(ctx, 500, "FIELD_MISMATCH"); + } + + const refundRecord = await DBModel.RefundRecord.findOne({ outRefundNo: resource.out_refund_no }); + if (!refundRecord) { + logger.error(`[payment] 退款回调找不到流水 outRefundNo=${resource.out_refund_no || ""}`); + return replySuccess(ctx); + } + + // 金额必须与本地退款流水一致,避免跨单报文混入 + if (Number(resource.amount?.refund) !== Number(refundRecord.refundAmount) + || Number(resource.amount?.total) !== Number(refundRecord.totalAmount)) { + logger.error( + `[payment] 退款回调金额不匹配 outRefundNo=${refundRecord.outRefundNo} localRefund=${refundRecord.refundAmount} remoteRefund=${resource.amount?.refund}` + ); + return replyFail(ctx, 500, "AMOUNT_MISMATCH"); + } + + await HandlerPayment.applyRefundResult(refundRecord, resource); + return replySuccess(ctx); + } catch (err) { + logger.error(`[payment] 退款回调处理异常: ${err?.stack || err?.message || err}`); + return replyFail(ctx, 500, "FAIL"); + } + } + + /** + * POST /escort-record/:id/refund/query (管理端兜底) + */ + async queryRefundResult(ctx) { + try { + const id = ctx.params.id; + if (!isValidObjectId(id)) return ResponseUtil.badRequest(ctx, "缺少记录ID"); + const record = await DBModel.EscortRecord.findById(id); + if (!record) return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404); + + const refundRecord = await DBModel.RefundRecord.findOne({ recordId: record._id }) + .sort({ createdAt: -1 }); + if (!refundRecord) return ResponseUtil.error(ctx, "无退款记录", null, 404); + if (!wxpay.isConfigured()) { + return ResponseUtil.error(ctx, "支付功能暂未开放,请选择线下支付", null, 503); + } + + const result = await wxpay.queryRefundResult(refundRecord.outRefundNo); + const status = await HandlerPayment.applyRefundResult(refundRecord, result); + const freshRecord = await DBModel.EscortRecord.findById(id); + return ResponseUtil.success(ctx, { + refund: { ...refundRecord.toObject(), status }, + paymentStatus: freshRecord?.payment?.status || "unpaid", + }, "查询成功"); + } catch (err) { + logger.error( + `[payment] 查询退款结果失败 recordId=${ctx.params.id} code=${err?.code || ""} requestId=${err?.requestId || ""} message=${err?.message || ""}` + ); + return ResponseUtil.error(ctx, "查询退款结果失败,请稍后重试", null, 500); + } + } +} + +// ==================== 后台巡检查单 ==================== + +let patrolTimer = null; +let patrolRunning = false; +let patrolConfigWarned = false; + +async function sweepPayment(payment) { + try { + const trade = await wxpay.queryOrder(payment.outTradeNo); + const state = trade.trade_state || ""; + + if (state === "SUCCESS") { + HandlerPayment.verifyTrade(trade, payment); + const applied = await HandlerPayment.applyPaymentSuccess( + payment, + HandlerPayment.mapTransaction(trade) + ); + if (applied.cancelled) { + await HandlerPayment.createRefundForRecord(applied.record || { _id: payment.recordId }, { + reason: DEFAULT_REFUND_REASON, + }); + } + return; + } + + if (payment.status === "closed_unconfirmed") { + await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() }); + return; + } + + if (["CLOSED", "PAYERROR", "REFUND", "REVOKED"].includes(state)) { + await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() }); + return; + } + + if (state === "NOTPAY" && payment.timeExpireAt + && nowMs() > new Date(payment.timeExpireAt).getTime()) { + await HandlerPayment.closeExpiredPayment(payment); + } + } catch (err) { + if (err instanceof WechatPayError) { + await HandlerPayment.markPaymentError(payment._id, err, "query"); + } else { + logger.error(`[payment] 巡检查单异常 outTradeNo=${payment.outTradeNo}: ${err?.message || err}`); + } + } +} + +async function runPaymentPatrolOnce() { + if (patrolRunning) return; + if (!wxpay.isConfigured()) { + if (!patrolConfigWarned) { + logger.warn("[payment] 微信支付未配置,支付巡检暂不执行"); + patrolConfigWarned = true; + } + return; + } + patrolConfigWarned = false; + patrolRunning = true; + try { + const since = new Date(nowMs() - 7 * 24 * 60 * 60 * 1000); + const payments = await DBModel.PaymentRecord.find({ + status: { $in: ACTIVE_PAYMENT_STATUS }, + createdAt: { $gte: since }, + }).sort({ createdAt: 1 }).limit(100); + + for (const payment of payments) { + await sweepPayment(payment); + } + + // 退款回调丢失同样由后台收敛:主动查询处理中/异常的退款单 + const refunds = await DBModel.RefundRecord.find({ + status: { $in: ["processing", "abnormal"] }, + createdAt: { $gte: since }, + }).sort({ createdAt: 1 }).limit(50); + for (const refund of refunds) { + try { + const result = await wxpay.queryRefundResult(refund.outRefundNo); + await HandlerPayment.applyRefundResult(refund, result); + } catch (err) { + await HandlerPayment.markRefundError(refund._id, err, "refund_query"); + } + } + } catch (err) { + logger.error(`[payment] 支付巡检异常: ${err?.stack || err?.message || err}`); + } finally { + patrolRunning = false; + } +} + +/** + * 服务启动时注册单一定时器;默认运行,每 10 分钟一轮 + */ +function startPaymentPatrol({ intervalMs = 10 * 60 * 1000 } = {}) { + if (patrolTimer) return patrolTimer; + patrolTimer = setInterval(() => { + runPaymentPatrolOnce().catch((err) => { + logger.error(`[payment] 支付巡检失败: ${err?.message || err}`); + }); + }, intervalMs); + if (typeof patrolTimer.unref === "function") patrolTimer.unref(); + return patrolTimer; +} + +export { HandlerPayment, startPaymentPatrol, runPaymentPatrolOnce }; diff --git a/index.js b/index.js index a6a6a63..99ee570 100644 --- a/index.js +++ b/index.js @@ -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(); diff --git a/models/index.js b/models/index.js index 3e4a7aa..b428933 100644 --- a/models/index.js +++ b/models/index.js @@ -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) } } diff --git a/models/schema/escort_record.js b/models/schema/escort_record.js index 6b25156..303fe69 100644 --- a/models/schema/escort_record.js +++ b/models/schema/escort_record.js @@ -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, diff --git a/models/schema/payment_record.js b/models/schema/payment_record.js new file mode 100644 index 0000000..ebdd9ba --- /dev/null +++ b/models/schema/payment_record.js @@ -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 }; diff --git a/models/schema/refund_record.js b/models/schema/refund_record.js new file mode 100644 index 0000000..f728a1b --- /dev/null +++ b/models/schema/refund_record.js @@ -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 }; diff --git a/routes/index.js b/routes/index.js index b58f239..047c6ee 100644 --- a/routes/index.js +++ b/routes/index.js @@ -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)); diff --git a/test/payment.test.js b/test/payment.test.js new file mode 100644 index 0000000..cab0a37 --- /dev/null +++ b/test/payment.test.js @@ -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, + })); +}); diff --git a/utils/wechatpay.js b/utils/wechatpay.js new file mode 100644 index 0000000..44c7e04 --- /dev/null +++ b/utils/wechatpay.js @@ -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, +};