Files
api_health/utils/wechatpay.js
T
lik 983e55b672 fix(payment): 增加支付配置诊断并拦截取消中的订单
- isConfigured 拆出 getConfigDiagnostics,日志列出缺失项且不输出密钥
- 证书路径支持 WXPAY_PRIVATE_KEY_PATH / WXPAY_PUBLIC_KEY_PATH 覆盖
- 已申请取消或已取消的订单不再回刷 paid,也不允许发起支付
- 发起支付与查询退款未配置时输出诊断日志
2026-11-05 18:54:59 +08:00

572 lines
17 KiB
JavaScript

import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import crypto from "node:crypto";
import fetch from "node-fetch";
import config from "../config.js";
import logger from "./logger.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PROJECT_ROOT = path.resolve(__dirname, "..");
const API_BASE = "https://api.mch.weixin.qq.com";
const REQUEST_TIMEOUT = 5000;
const MAX_ERROR_MESSAGE = 500;
const DEFAULT_NOTIFY_BASE = "https://api.huashengtec.com/health";
/**
* 微信支付统一错误:错误详情用于落库与排障,接口层只返回通用提示。
*/
class WechatPayError extends Error {
constructor({ stage = "", code = "UNKNOWN", message = "", requestId = "", httpStatus = 0 } = {}) {
super(message || code || "wechat pay error");
this.name = "WechatPayError";
this.stage = stage;
this.code = String(code || "UNKNOWN");
this.requestId = requestId || "";
this.httpStatus = Number(httpStatus) || 0;
}
}
function truncate(text, max = MAX_ERROR_MESSAGE) {
return String(text || "").slice(0, max);
}
// 微信对 description(127) / reason(80) 的限制按字节计算,中文需按字节截断
function truncateBytes(text, maxBytes) {
let result = "";
let used = 0;
for (const char of String(text || "")) {
const size = Buffer.byteLength(char, "utf-8");
if (used + size > maxBytes) break;
result += char;
used += size;
}
return result;
}
function payConfig() {
return config.wechatpay || {};
}
function resolvePath(value) {
if (!value) return "";
return path.isAbsolute(value) ? value : path.resolve(PROJECT_ROOT, value);
}
// 证书路径允许用环境变量覆盖:仓库里的 conf.json 面向部署机(Linux 路径),
// 本地开发可用 .env 指向本机证书,避免为了本地调试改回仓库配置。
function privateKeyPathValue() {
return process.env.WXPAY_PRIVATE_KEY_PATH || payConfig().privateKeyPath || "";
}
function publicKeyPathValue() {
return process.env.WXPAY_PUBLIC_KEY_PATH || payConfig().publicKeyPath || "";
}
let cachedPrivateKey = null;
let cachedPublicKey = null;
function loadPrivateKey() {
const privatePath = privateKeyPathValue();
if (!cachedPrivateKey && privatePath) {
cachedPrivateKey = readFileSync(resolvePath(privatePath), "utf-8");
}
return cachedPrivateKey;
}
function loadPublicKey() {
const publicPath = publicKeyPathValue();
if (!cachedPublicKey && publicPath) {
cachedPublicKey = readFileSync(resolvePath(publicPath), "utf-8");
}
return cachedPublicKey;
}
function apiV3Key() {
const cfg = payConfig();
const key = process.env[cfg.apiv3KeyEnv || "WXPAY_APIV3_KEY"] || "";
if (key.length !== 32) {
throw new WechatPayError({
stage: "config",
code: "CONFIG_MISSING",
message: "APIv3 密钥缺失或长度不为 32",
});
}
return key;
}
/**
* 配置诊断:只返回缺失项名称,不输出密钥内容,便于线上日志定位
* @returns {string[]} 缺失/不可用项
*/
function getConfigDiagnostics() {
const cfg = payConfig();
const issues = [];
if (!cfg.mchid) issues.push("mchid 未配置");
if (!cfg.appid) issues.push("appid 未配置");
if (!cfg.merchantSerial) issues.push("merchantSerial 未配置");
if (!cfg.publicKeyId) issues.push("publicKeyId 未配置");
const privatePath = resolvePath(privateKeyPathValue());
if (!privatePath) {
issues.push("privateKeyPath 未配置");
} else {
try {
readFileSync(privatePath, "utf-8");
} catch (err) {
issues.push(`商户私钥不可读:${privatePath}`);
}
}
const publicPath = resolvePath(publicKeyPathValue());
if (!publicPath) {
issues.push("publicKeyPath 未配置");
} else {
try {
readFileSync(publicPath, "utf-8");
} catch (err) {
issues.push(`微信支付公钥不可读:${publicPath}`);
}
}
const envKey = process.env[cfg.apiv3KeyEnv || "WXPAY_APIV3_KEY"] || "";
if (envKey.length !== 32) {
issues.push(`环境变量 ${cfg.apiv3KeyEnv || "WXPAY_APIV3_KEY"} 缺失或长度不为 32`);
}
return issues;
}
/**
* 配置是否完整(商户参数 + 两把证书文件 + APIv3 密钥)
* 缺配置时支付接口降级为「未开放」,不影响下单、取消等其它链路。
*/
function isConfigured() {
return getConfigDiagnostics().length === 0;
}
function requireFullConfig() {
const cfg = payConfig();
if (!isConfigured()) {
throw new WechatPayError({
stage: "config",
code: "CONFIG_MISSING",
message: "微信支付未配置",
});
}
return cfg;
}
// ==================== 金额换算 ====================
/**
* 元 → 分:按小数点拆位,不经过浮点乘法
* @param {string|number} value
* @returns {number|null} 非负整数分;非法输入返回 null
*/
function yuanToFen(value) {
if (value === null || value === undefined || value === "") return null;
const text = String(value).trim();
if (!text) return null;
const matched = /^(\d+)(?:\.(\d{1,2}))?$/.exec(text);
if (!matched) return null;
const yuan = Number(matched[1]);
const cents = Number((matched[2] || "").padEnd(2, "0")) || 0;
const fen = yuan * 100 + cents;
return Number.isSafeInteger(fen) && fen >= 0 ? fen : null;
}
function fenToYuan(fen) {
const value = Number(fen);
if (!Number.isInteger(value)) return "";
return (value / 100).toFixed(2);
}
// ==================== 签名 / 验签 / 解密 ====================
function buildRequestSignature({ method, urlPath, timestamp, nonce, body = "", privateKey }) {
const message = `${String(method || "GET").toUpperCase()}\n${urlPath}\n${timestamp}\n${nonce}\n${body}\n`;
return crypto.createSign("RSA-SHA256").update(message).sign(privateKey, "base64");
}
function buildAuthHeader({ mchid, serialNo, signature, timestamp, nonce }) {
return `WECHATPAY2-SHA256-RSA2048 mchid="${mchid}",nonce_str="${nonce}",signature="${signature}",timestamp="${timestamp}",serial_no="${serialNo}"`;
}
function verifyMessageSignature({ message, signature, publicKeyPem }) {
try {
return crypto.createVerify("RSA-SHA256").update(message).verify(publicKeyPem, signature, "base64");
} catch (err) {
return false;
}
}
function decryptAesGcm({ ciphertext, nonce, associatedData, apiV3Key: keyValue }) {
const key = Buffer.from(keyValue, "utf-8");
if (key.length !== 32) throw new Error("APIv3 密钥长度必须为 32");
const raw = Buffer.from(ciphertext, "base64");
if (raw.length < 17) throw new Error("密文长度不正确");
const authTag = raw.subarray(raw.length - 16);
const payload = raw.subarray(0, raw.length - 16);
const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(nonce, "utf-8"));
decipher.setAuthTag(authTag);
if (associatedData) decipher.setAAD(Buffer.from(associatedData, "utf-8"));
return Buffer.concat([decipher.update(payload), decipher.final()]).toString("utf-8");
}
function formatTimeExpire(value) {
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) return "";
const shifted = new Date(date.getTime() + 8 * 60 * 60 * 1000);
const pad = (num) => String(num).padStart(2, "0");
return `${shifted.getUTCFullYear()}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}`
+ `T${pad(shifted.getUTCHours())}:${pad(shifted.getUTCMinutes())}:${pad(shifted.getUTCSeconds())}+08:00`;
}
/**
* 调起支付参数:paySign 与接口请求签名是两套签名串
*/
function buildPayParams({ prepayId, appId, privateKey }) {
const cfg = payConfig();
const useAppId = appId || cfg.appid;
const key = privateKey || loadPrivateKey();
const timeStamp = String(Math.floor(Date.now() / 1000));
const nonceStr = crypto.randomBytes(16).toString("hex");
const pkg = `prepay_id=${prepayId}`;
const message = `${useAppId}\n${timeStamp}\n${nonceStr}\n${pkg}\n`;
const paySign = crypto.createSign("RSA-SHA256").update(message).sign(key, "base64");
return { timeStamp, nonceStr, package: pkg, signType: "RSA", paySign };
}
// ==================== HTTP 调用 ====================
async function apiRequest({ stage, method = "GET", urlPath, body = "", orderNo = "" }) {
const cfg = requireFullConfig();
const privateKey = loadPrivateKey();
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = crypto.randomBytes(16).toString("hex");
const signature = buildRequestSignature({
method,
urlPath,
timestamp,
nonce,
body,
privateKey,
});
const authorization = buildAuthHeader({
mchid: cfg.mchid,
serialNo: cfg.merchantSerial,
signature,
timestamp,
nonce,
});
let response;
try {
response = await fetch(`${API_BASE}${urlPath}`, {
method,
headers: {
Authorization: authorization,
Accept: "application/json",
"Content-Type": "application/json",
"Accept-Language": "zh-CN",
"User-Agent": "ws-health/1.0",
},
body: body || undefined,
signal: AbortSignal.timeout(REQUEST_TIMEOUT),
});
} catch (err) {
logger.error(`[wechatpay] ${stage} 网络异常: ${err.message}`);
throw new WechatPayError({
stage,
code: "NETWORK_ERROR",
message: err.message,
httpStatus: 0,
});
}
const requestId = response.headers.get("request-id") || "";
const rawBody = await response.text();
let data = {};
try {
data = rawBody ? JSON.parse(rawBody) : {};
} catch (err) {
data = {};
}
if (!response.ok) {
const message = truncate(data.message || rawBody || `HTTP ${response.status}`);
logger.error(`[wechatpay] ${stage} 失败 orderNo=${orderNo} http=${response.status} requestId=${requestId} code=${data.code || ""} message=${message}`);
throw new WechatPayError({
stage,
code: data.code || `HTTP_${response.status}`,
message,
requestId,
httpStatus: response.status,
});
}
// 应答验签:有签名头时按微信支付公钥校验,避免中间人篡改应答
const responseSignature = response.headers.get("wechatpay-signature");
if (responseSignature) {
const responseTimestamp = response.headers.get("wechatpay-timestamp") || "";
const responseNonce = response.headers.get("wechatpay-nonce") || "";
const serial = response.headers.get("wechatpay-serial") || "";
if (cfg.publicKeyId && serial && serial !== cfg.publicKeyId) {
throw new WechatPayError({
stage,
code: "SERIAL_MISMATCH",
message: "微信支付应答公钥序列号不匹配",
requestId,
httpStatus: response.status,
});
}
const message = `${responseTimestamp}\n${responseNonce}\n${rawBody}\n`;
if (!verifyMessageSignature({ message, signature: responseSignature, publicKeyPem: loadPublicKey() })) {
throw new WechatPayError({
stage,
code: "SIGN_ERROR",
message: "微信支付应答验签失败",
requestId,
httpStatus: response.status,
});
}
}
logger.info(`[wechatpay] ${stage} ok orderNo=${orderNo} http=${response.status} requestId=${requestId}`);
return { data, requestId, httpStatus: response.status };
}
// ==================== 支付接口 ====================
async function createJsapiOrder({ outTradeNo, description, totalFee, openid, timeExpireAt, notifyUrl }) {
const cfg = requireFullConfig();
const payload = JSON.stringify({
appid: cfg.appid,
mchid: cfg.mchid,
description: truncateBytes(description || "陪诊服务", 127),
out_trade_no: outTradeNo,
time_expire: formatTimeExpire(timeExpireAt),
notify_url: notifyUrl,
amount: { total: Number(totalFee), currency: "CNY" },
payer: { openid },
});
const { data } = await apiRequest({
stage: "create",
method: "POST",
urlPath: "/v3/pay/transactions/jsapi",
body: payload,
orderNo: outTradeNo,
});
if (!data.prepay_id) {
throw new WechatPayError({
stage: "create",
code: "NO_PREPAY_ID",
message: "微信未返回 prepay_id",
httpStatus: 200,
});
}
return data;
}
async function queryOrder(outTradeNo) {
const cfg = requireFullConfig();
const urlPath = `/v3/pay/transactions/out-trade-no/${encodeURIComponent(outTradeNo)}?mchid=${encodeURIComponent(cfg.mchid)}`;
const { data, requestId, httpStatus } = await apiRequest({ stage: "query", urlPath, orderNo: outTradeNo });
return { ...data, requestId, httpStatus };
}
async function closeOrder(outTradeNo) {
const cfg = requireFullConfig();
const { data } = await apiRequest({
stage: "close",
method: "POST",
urlPath: `/v3/pay/transactions/out-trade-no/${encodeURIComponent(outTradeNo)}/close`,
body: JSON.stringify({ mchid: cfg.mchid }),
orderNo: outTradeNo,
});
return data;
}
async function createRefund({ outTradeNo, outRefundNo, reason, refundAmount, totalAmount, notifyUrl }) {
const reasonText = truncateBytes(reason || "", 80);
const payloadData = {
out_trade_no: outTradeNo,
out_refund_no: outRefundNo,
notify_url: notifyUrl,
amount: {
refund: Number(refundAmount),
total: Number(totalAmount),
currency: "CNY",
},
};
// reason 选填:没有值时不传空串
if (reasonText) payloadData.reason = reasonText;
const payload = JSON.stringify(payloadData);
const { data } = await apiRequest({
stage: "refund",
method: "POST",
urlPath: "/v3/refund/domestic/refunds",
body: payload,
orderNo: outRefundNo,
});
return data;
}
async function queryRefundResult(outRefundNo) {
const urlPath = `/v3/refund/domestic/refunds/${encodeURIComponent(outRefundNo)}`;
const { data, requestId, httpStatus } = await apiRequest({ stage: "refund_query", urlPath, orderNo: outRefundNo });
return { ...data, requestId, httpStatus };
}
function getNotifyUrls() {
const cfg = payConfig();
const base = String(cfg.notifyBase || DEFAULT_NOTIFY_BASE).replace(/\/+$/, "");
return {
payUrl: `${base}/pay/notify`,
refundUrl: `${base}/pay/refund-notify`,
};
}
/**
* 回调验签 + 解密
* @param {Object} options
* @param {Object} options.headers 请求头(小写键)
* @param {string} options.rawBody 原始报文
* @returns {{ eventType: string, resourceType: string, resource: Object, id: string }}
*/
function verifyNotify({ headers = {}, rawBody = "" }) {
const cfg = requireFullConfig();
const timestamp = String(headers["wechatpay-timestamp"] || "");
const nonce = String(headers["wechatpay-nonce"] || "");
const signature = String(headers["wechatpay-signature"] || "");
const serial = String(headers["wechatpay-serial"] || "");
if (!timestamp || !nonce || !signature || !serial) {
throw new WechatPayError({
stage: "notify",
code: "MISSING_SIGNATURE",
message: "回调缺少验签头",
httpStatus: 400,
});
}
// 微信签名探测流量:按失败应答,不当作攻击忽略
if (signature.startsWith("WECHATPAY/SIGNTEST/")) {
logger.warn("[wechatpay] 收到微信支付签名探测流量,按验签失败应答");
throw new WechatPayError({
stage: "notify",
code: "SIGNTEST",
message: "签名探测流量",
httpStatus: 400,
});
}
const nowSeconds = Math.floor(Date.now() / 1000);
if (Math.abs(nowSeconds - Number(timestamp)) > 300) {
throw new WechatPayError({
stage: "notify",
code: "TIMESTAMP_EXPIRED",
message: "回调时间戳超出允许范围",
httpStatus: 400,
});
}
if (cfg.publicKeyId && serial !== cfg.publicKeyId) {
throw new WechatPayError({
stage: "notify",
code: "SERIAL_MISMATCH",
message: "回调公钥序列号不匹配",
httpStatus: 400,
});
}
const message = `${timestamp}\n${nonce}\n${rawBody}\n`;
if (!verifyMessageSignature({ message, signature, publicKeyPem: loadPublicKey() })) {
throw new WechatPayError({
stage: "notify",
code: "SIGN_ERROR",
message: "回调验签失败",
httpStatus: 401,
});
}
let body;
try {
body = JSON.parse(rawBody);
} catch (err) {
throw new WechatPayError({
stage: "notify",
code: "INVALID_BODY",
message: "回调报文不是合法 JSON",
httpStatus: 400,
});
}
const resource = body.resource || {};
if (!resource.ciphertext || !resource.nonce) {
throw new WechatPayError({
stage: "notify",
code: "INVALID_RESOURCE",
message: "回调报文缺少加密资源",
httpStatus: 400,
});
}
let plaintext;
try {
plaintext = decryptAesGcm({
ciphertext: resource.ciphertext,
nonce: resource.nonce,
associatedData: resource.associated_data || "",
apiV3Key: apiV3Key(),
});
} catch (err) {
throw new WechatPayError({
stage: "notify",
code: "DECRYPT_ERROR",
message: err.message,
httpStatus: 400,
});
}
let decrypted;
try {
decrypted = JSON.parse(plaintext);
} catch (err) {
throw new WechatPayError({
stage: "notify",
code: "INVALID_RESOURCE",
message: "解密内容不是合法 JSON",
httpStatus: 400,
});
}
return {
id: body.id || "",
eventType: body.event_type || "",
resourceType: body.resource_type || "",
resource: decrypted,
};
}
export {
WechatPayError,
isConfigured,
getConfigDiagnostics,
yuanToFen,
fenToYuan,
formatTimeExpire,
buildRequestSignature,
buildAuthHeader,
verifyMessageSignature,
decryptAesGcm,
buildPayParams,
getNotifyUrls,
createJsapiOrder,
queryOrder,
closeOrder,
createRefund,
queryRefundResult,
verifyNotify,
};