支付通路
This commit is contained in:
1 parent
c7f43e30a9
commit
85b0e70907
26 files changed
+1324
-74
No files matched your search
@@ -5,6 +5,19 @@ import { AppError } from '../../common/errors';
|
||||
|
||||
const XPAY_BASE = 'https://api.weixin.qq.com';
|
||||
|
||||
/** query_order 返回的订单状态。 */
|
||||
const XPAY_STATUS: Record<number, string> = {
|
||||
0: '初始化',
|
||||
1: '创建成功未支付',
|
||||
2: '已支付待发货',
|
||||
3: '发货中',
|
||||
4: '已发货',
|
||||
5: '已退款',
|
||||
6: '已关闭',
|
||||
7: '退款失败',
|
||||
8: '用户退款完成',
|
||||
};
|
||||
|
||||
/**
|
||||
* 微信小程序虚拟支付客户端。
|
||||
*
|
||||
@@ -21,6 +34,9 @@ const XPAY_BASE = 'https://api.weixin.qq.com';
|
||||
export class WxPayService {
|
||||
private readonly logger = new Logger(WxPayService.name);
|
||||
|
||||
/** access_token 缓存。有效期 7200 秒,提前 5 分钟换新的。 */
|
||||
private tokenCache: { value: string; expiresAt: number } | null = null;
|
||||
|
||||
constructor(@Inject(APP_CONFIG) private readonly cfg: AppConfig) {}
|
||||
|
||||
/** 当前支付环境:0 现网 / 1 沙箱。 */
|
||||
@@ -51,6 +67,46 @@ export class WxPayService {
|
||||
return createHmac('sha256', sessionKey).update(postBody).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 小程序 access_token。
|
||||
*
|
||||
* 这些 /xpay/* 服务端接口要求 URL 上同时带 access_token 和 pay_sig:
|
||||
* https://api.weixin.qq.com/xpay/query_order?access_token=xxx&pay_sig=xxx
|
||||
* 只带 pay_sig 会返回 41001 access_token missing——查单和退款都会静默失败。
|
||||
*/
|
||||
private async accessToken(): Promise<string> {
|
||||
const now = Date.now();
|
||||
if (this.tokenCache && this.tokenCache.expiresAt > now) return this.tokenCache.value;
|
||||
|
||||
const url =
|
||||
`${XPAY_BASE}/cgi-bin/token?grant_type=client_credential` +
|
||||
`&appid=${encodeURIComponent(this.cfg.WX_APPID)}` +
|
||||
`&secret=${encodeURIComponent(this.cfg.WX_APPSECRET)}`;
|
||||
const res = await fetch(url);
|
||||
const json = (await res.json()) as {
|
||||
access_token?: string;
|
||||
expires_in?: number;
|
||||
errcode?: number;
|
||||
errmsg?: string;
|
||||
};
|
||||
if (!json.access_token) {
|
||||
throw new AppError(
|
||||
4002,
|
||||
`获取 access_token 失败:${json.errcode ?? '-'} ${json.errmsg ?? ''}`.trim(),
|
||||
502,
|
||||
);
|
||||
}
|
||||
const ttl = Math.max((json.expires_in ?? 7200) - 300, 60);
|
||||
this.tokenCache = { value: json.access_token, expiresAt: now + ttl * 1000 };
|
||||
return json.access_token;
|
||||
}
|
||||
|
||||
/** 拼出带 access_token 与 pay_sig 的接口地址。 */
|
||||
private async signedUrl(uri: string, postBody: string): Promise<string> {
|
||||
const token = await this.accessToken();
|
||||
return `${XPAY_BASE}${uri}?access_token=${encodeURIComponent(token)}&pay_sig=${this.calcPaySig(uri, postBody)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查单。用于发货推送丢失时兜底补发。
|
||||
* 参数名是 order_id(传自己的 outTradeNo),不是 out_trade_no。
|
||||
@@ -58,9 +114,8 @@ export class WxPayService {
|
||||
async queryOrder(outTradeNo: string, openid: string): Promise<XpayQueryResult> {
|
||||
const uri = '/xpay/query_order';
|
||||
const body = JSON.stringify({ openid, env: this.env, order_id: outTradeNo });
|
||||
const paySig = this.calcPaySig(uri, body);
|
||||
|
||||
const res = await fetch(`${XPAY_BASE}${uri}?pay_sig=${paySig}`, {
|
||||
const res = await fetch(await this.signedUrl(uri, body), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body,
|
||||
@@ -82,28 +137,67 @@ export class WxPayService {
|
||||
outTradeNo: string;
|
||||
openid: string;
|
||||
refundOrderId: string;
|
||||
refundAmountFen: number;
|
||||
reason: string;
|
||||
refundFeeFen: number;
|
||||
/** 0-5,微信只认这几个枚举值 */
|
||||
reasonCode: string;
|
||||
/** 商家自定义数据,必填,退款原因的文字记在这里,query_order 可原样查回 */
|
||||
bizMeta: string;
|
||||
}): Promise<Record<string, unknown>> {
|
||||
if (!this.enabled) throw new AppError(4002, '虚拟支付未配置', 503);
|
||||
|
||||
// left_fee 是「当前单剩余可退金额」,接口必填,只能先查单拿到。
|
||||
// 千万不要拿订单金额兜底——那等于编一个数发给微信,会被 268490016 打回来,
|
||||
// 而且把「这单根本不能退」这个真实原因盖掉了。
|
||||
const queried = await this.queryOrder(input.outTradeNo, input.openid);
|
||||
const status = queried.order?.status;
|
||||
const statusText = status === undefined ? '未知' : XPAY_STATUS[status] ?? String(status);
|
||||
const leftFee = queried.order?.left_fee;
|
||||
|
||||
if (leftFee === undefined || leftFee === null) {
|
||||
throw new AppError(
|
||||
4002,
|
||||
`微信侧订单状态是「${statusText}」,没有可退金额,无法退款`,
|
||||
409,
|
||||
);
|
||||
}
|
||||
if (leftFee <= 0) {
|
||||
throw new AppError(4002, `该订单可退金额为 0(微信侧状态:${statusText}),无法退款`, 409);
|
||||
}
|
||||
if (input.refundFeeFen > leftFee) {
|
||||
throw new AppError(
|
||||
4002,
|
||||
`退款金额 ${input.refundFeeFen} 分超过可退金额 ${leftFee} 分,无法退款`,
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
const uri = '/xpay/refund_order';
|
||||
// 字段名和取值都必须严格照文档,少一个必填字段整笔退款就被拒
|
||||
const body = JSON.stringify({
|
||||
openid: input.openid,
|
||||
env: this.env,
|
||||
order_id: input.outTradeNo,
|
||||
refund_order_id: input.refundOrderId,
|
||||
refund_amount: input.refundAmountFen,
|
||||
refund_reason: input.reason,
|
||||
left_fee: leftFee,
|
||||
refund_fee: input.refundFeeFen,
|
||||
biz_meta: input.bizMeta.slice(0, 1024),
|
||||
refund_reason: input.reasonCode,
|
||||
/** 1-人工客服退款:后台管理员发起的都属于这一类 */
|
||||
req_from: '1',
|
||||
env: this.env,
|
||||
});
|
||||
const paySig = this.calcPaySig(uri, body);
|
||||
|
||||
const res = await fetch(`${XPAY_BASE}${uri}?pay_sig=${paySig}`, {
|
||||
const res = await fetch(await this.signedUrl(uri, body), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body,
|
||||
});
|
||||
return (await res.json()) as Record<string, unknown>;
|
||||
const json = (await res.json()) as { errcode?: number; errmsg?: string };
|
||||
|
||||
// 以前不看返回码,微信拒了也照样告诉后台「已提交」,退款就这么静默消失了
|
||||
if (json.errcode && json.errcode !== 0) {
|
||||
throw new AppError(4002, `微信退款接口拒绝:${json.errcode} ${json.errmsg ?? ''}`.trim(), 502);
|
||||
}
|
||||
return json as Record<string, unknown>;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,6 +209,8 @@ export interface XpayQueryResult {
|
||||
wx_order_id?: string;
|
||||
status?: number;
|
||||
paid_time?: number;
|
||||
/** 当前单剩余可退金额,单位分 */
|
||||
left_fee?: number;
|
||||
};
|
||||
status?: number;
|
||||
wx_order_id?: string;
|
||||
|
||||
Reference in new issue
Block a user