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 * 订单已取消(cancelStatus 非 none)时不刷 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 }; } // 取消与 status 解耦:已申请取消或已取消的订单都不再回刷 paid(兼容旧数据 status=cancelled) if ((record.cancelStatus || "none") !== "none" || 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 ((record.cancelStatus || "none") !== "none" || record.status === "cancelled") { 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()) { logger.warn(`[payment] 微信支付未配置,拒绝发起支付 recordId=${id}:${wxpay.getConfigDiagnostics().join(";")}`); 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()) { logger.warn(`[payment] 微信支付未配置,拒绝查询退款 recordId=${id}:${wxpay.getConfigDiagnostics().join(";")}`); 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 };