packServer/backend/test/app/controller/subject-order.test.js
liufumingren 8949b7198c feat(pay): 微信 Native 扫码支付(下单出码 + 回调入账 + 扫码轮询)
- 新增 service/wxpay.js:统一下单 / 查询订单 / 关闭订单 / APIv2 验签,二维码在服务端本地生成 SVG
- 新增 pay/wechat.js 与 XML 编解码,公开回调 POST /api/pay/wechat/notify
- 订单:同主体 + 同套餐复用未超时待支付单;2 小时超时关单;回调 / 查单 / 手工确认统一走 payNotify
- 迁移 subject_orders 增加 code_url / prepay_id 等字段,配置项 WXPAY_*
- 前端续期弹窗展示二维码并按 2s 轮询支付结果
- 文档与测试同步更新

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-07 16:23:03 +08:00

482 lines
19 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { app, mock, assert } = require('egg-mock/bootstrap');
const crypto = require('crypto');
/** 假实例:update 时把字段同时合并回实例自身(present 读的是实例属性) */
const instance = data => {
const obj = {
toJSON: () => data,
update: async fields => {
Object.assign(data, fields);
Object.assign(obj, fields);
},
};
return Object.assign(obj, data);
};
const USER = { id: 1, username: 'admin', nickname: '管理员', status: 1 };
const SUBJECT_ID = 21;
const ORDER_TTL_MS = 2 * 3600 * 1000;
/**
* 续期订单 + 支付回调
*
* 重点:
* - 下单只建单(待支付),不动期限;
* - 支付回调才续期,并**失效主体状态缓存**(设备心跳/上报立刻看到新期限);
* - 重复回调幂等(`duplicated: true`,不重复续期);
* - 配了回调密钥就校验签名。
*/
describe('test/app/controller/subject-order.test.js', () => {
const token = () => `Bearer ${app.createAnonymousContext().service.jwt.signUser(USER)}`;
const auth = () => ({ Authorization: token() });
/** 记录 `SubjectOrder.update()` 的调用(超时关单) */
let orderUpdates = [];
const subjectRow = expireAt => instance({
id: SUBJECT_ID,
name: '测试主体',
adminUserId: 1,
status: 1,
expireAt,
});
const orderRow = (overrides = {}) => instance(Object.assign({
id: 100,
orderNo: 'SO20261020120000000001',
subjectId: SUBJECT_ID,
userId: 1,
days: 30,
amount: 99,
status: 0,
channel: 'mock',
transactionId: null,
paidAt: null,
expireBefore: new Date(Date.now() - 86400000),
expireAfter: null,
remark: null,
createdAt: new Date(),
}, overrides));
function fakeTransaction(log = []) {
return {
LOCK: { UPDATE: 'UPDATE' },
async commit() { log.push('commit'); },
async rollback() { log.push('rollback'); },
};
}
/** 套餐行(subject_plans):天数与定价都在库里,下单只认 planId */
const planRow = (overrides = {}) => instance(Object.assign({
id: 7,
code: 'p30',
name: '30 天',
days: 30,
price: 99,
originalPrice: null,
tag: null,
description: null,
sort: 10,
status: 1,
}, overrides));
function mockModels({ memberRole = 1, subject, order, plan, log, pendingOrders = [], onCreate } = {}) {
mock(app, 'model', {
User: { async findByPk() { return instance(Object.assign({}, USER)); } },
SubjectMember: {
async findOne() {
return instance({ id: 11, subjectId: SUBJECT_ID, userId: 1, name: '管理员', role: memberRole, status: 1 });
},
},
Subject: {
async findByPk() { return typeof subject === 'function' ? subject() : subject; },
},
SubjectPlan: {
async findOne() {
if (plan === undefined) return planRow();
return typeof plan === 'function' ? plan() : plan;
},
async findAll() { return [ planRow() ]; },
},
SubjectOrder: {
async create(fields) {
if (onCreate) onCreate(fields);
return orderRow(Object.assign({ id: 101 }, fields));
},
async findOne() { return typeof order === 'function' ? order() : order; },
async findByPk() { return typeof order === 'function' ? order() : order; },
async findAll() { return typeof pendingOrders === 'function' ? pendingOrders() : pendingOrders; },
async findAndCountAll() { return { rows: [ orderRow() ], count: 1 }; },
async update(fields, options) {
orderUpdates.push({ fields, options });
return [ 1 ];
},
},
transaction: async () => fakeTransaction(log),
});
}
beforeEach(() => {
orderUpdates = [];
app.createAnonymousContext().service.subjectState.clearLocalCache();
});
// ---------------- 微信 Native 支付(回调 + 订单复用) ----------------
const WX_KEY = 'wx-key-1';
/** 微信 APIv2 签名(测试里独立实现) */
function wxSign(params, key = WX_KEY) {
const content = Object.keys(params)
.filter(name => name !== 'sign' && params[name] !== undefined && params[name] !== null && params[name] !== '')
.sort()
.map(name => `${name}=${params[name]}`)
.join('&');
return crypto.createHash('md5').update(`${content}&key=${key}`, 'utf8').digest('hex').toUpperCase();
}
/** 微信回调 XML(自动带正确签名) */
function wxNotifyXml(params) {
const fields = Object.assign({}, params);
fields.sign = wxSign(fields);
return `<xml>${Object.keys(fields).map(name => `<${name}><![CDATA[${fields[name]}]]></${name}>`).join('')}</xml>`;
}
/** 填上一套假凭证,让 service 认为「微信支付已开通」 */
function enableWxpay() {
mock(app.config.wxpay, 'enabled', true);
mock(app.config.wxpay, 'appId', 'wx-app-1');
mock(app.config.wxpay, 'mchId', '1900000109');
mock(app.config.wxpay, 'apiKey', WX_KEY);
mock(app.config.wxpay, 'signType', 'MD5');
}
it('GET /api/web/subject-plans:返回上架套餐(含计算好的每天单价)', async () => {
mockModels();
const res = await app.httpRequest().get('/api/web/subject-plans').set(auth()).expect(200);
const list = res.body.data.list;
assert(list.length === 1, JSON.stringify(res.body));
assert(list[0].days === 30 && list[0].price === 99);
assert(list[0].pricePerDay === 3.3, `pricePerDay 应为 3.3,实际 ${list[0].pricePerDay}`);
});
it('POST /api/web/subjects/:id/orders:选套餐下单 → 201(待支付,不动期限,金额取套餐价)', async () => {
const subject = subjectRow(new Date(Date.now() - 86400000));
let subjectUpdated = 0;
const rawUpdate = subject.update;
subject.update = async (...args) => {
subjectUpdated++;
return rawUpdate(...args);
};
mockModels({ subject });
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(201);
assert(res.body.data.orderNo, JSON.stringify(res.body));
assert(res.body.data.status === 0 && res.body.data.days === 30);
assert(res.body.data.amount === 99, `金额应取套餐价 99,实际 ${res.body.data.amount}`);
assert(res.body.data.planId === 7 && res.body.data.planName === '30 天');
assert(subjectUpdated === 0, '下单不能改主体期限');
});
it('POST /api/web/subjects/:id/orders:前端传的金额被忽略(只认套餐价)', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)) });
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7, amount: 0.01, days: 9999 }).expect(201);
assert(res.body.data.amount === 99, JSON.stringify(res.body));
assert(res.body.data.days === 30);
});
it('POST /api/web/subjects/:id/orders:普通成员不能下单(403)', async () => {
mockModels({
memberRole: 2,
subject: instance({ id: SUBJECT_ID, name: '别人的主体', adminUserId: 99, status: 1, expireAt: new Date(Date.now() + 86400000) }),
});
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(403);
});
it('POST /api/web/subjects/:id/orders:没选套餐 / 套餐不存在 → 422', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)) });
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({}).expect(422);
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), plan: null });
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 999 }).expect(422);
});
it('POST /api/web/subjects/:id/orders:套餐没配价格 → 422', async () => {
mockModels({
subject: subjectRow(new Date(Date.now() + 86400000)),
plan: planRow({ price: 0 }),
});
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(422);
});
it('POST /api/web/subjects/:id/orders:返回 2 小时支付截止时间(payExpireAt)', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)) });
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(201);
const data = res.body.data;
const ttl = new Date(data.payExpireAt).getTime() - new Date(data.createdAt).getTime();
assert(ttl === ORDER_TTL_MS, `支付截止时间应为下单后 2 小时,实际 ${ttl}ms`);
assert(data.expired === false && data.pending === true, JSON.stringify(data));
});
it('GET /api/web/subjects/:id/orders/:orderNo:超过 2 小时未支付 → 自动关闭', async () => {
const order = orderRow({ createdAt: new Date(Date.now() - 3 * 3600 * 1000) });
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => order });
const res = await app.httpRequest()
.get(`/api/web/subjects/${SUBJECT_ID}/orders/${order.orderNo}`)
.set(auth()).expect(200);
assert(res.body.data.status === 2, JSON.stringify(res.body));
assert(res.body.data.pending === false, JSON.stringify(res.body));
assert(orderUpdates.some(item => item.fields.status === 2), JSON.stringify(orderUpdates));
});
it('POST /api/pay/notify:超过 2 小时未支付 → 409,订单被关闭', async () => {
const order = orderRow({ createdAt: new Date(Date.now() - 3 * 3600 * 1000) });
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => order });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: order.orderNo, amount: 99 })
.expect(409);
assert(orderUpdates.some(item => item.fields.status === 2), JSON.stringify(orderUpdates));
});
it('定时任务 sweepExpired():批量关闭超时未支付订单', async () => {
mockModels({});
const closed = await app.createAnonymousContext().service.subjectOrder.sweepExpired();
assert(closed === 1, `应关闭 1 笔,实际 ${closed}`);
assert(orderUpdates.length === 1 && orderUpdates[0].fields.status === 2, JSON.stringify(orderUpdates));
assert(orderUpdates[0].options.where.status === 0, JSON.stringify(orderUpdates[0].options));
// 时间戳属性名是 created_at(不是 createdAt),写错会变成「不存在的列」
assert(orderUpdates[0].options.where.created_at, JSON.stringify(orderUpdates[0].options.where));
assert(orderUpdates[0].options.where.createdAt === undefined, JSON.stringify(orderUpdates[0].options.where));
});
it('POST /api/pay/notify:支付成功后主体续期,且缓存失效(设备立刻看到新期限)', async () => {
const log = [];
const order = orderRow();
const subject = subjectRow(new Date(Date.now() - 86400000));
mockModels({ subject: () => subject, order: () => order, log });
// 先预热缓存:此刻是「已过期」
const before = await app.createAnonymousContext().service.subjectState.get(SUBJECT_ID);
assert(before.expired === true, JSON.stringify(before));
const res = await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: order.orderNo, transactionId: 'TXN-1', amount: 99 })
.expect(200);
assert(res.body.data.duplicated === false, JSON.stringify(res.body));
assert(res.body.data.order.status === 1);
assert(log.includes('commit'));
const after = await app.createAnonymousContext().service.subjectState.get(SUBJECT_ID);
assert(after.expired === false, JSON.stringify(after));
assert(after.remainingSeconds > 29 * 86400, `续期 30 天后应剩余约 30 天,实际 ${after.remainingSeconds}`);
});
it('POST /api/pay/notify:重复回调幂等(不重复续期)', async () => {
const log = [];
const order = orderRow({ status: 1 });
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => order, log });
const res = await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: order.orderNo, amount: 99 })
.expect(200);
assert(res.body.data.duplicated === true, JSON.stringify(res.body));
assert(log.includes('rollback'), '已支付的订单应回滚事务,不做任何写入');
});
it('POST /api/pay/notify:金额不符 → 422;订单不存在 → 404', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => orderRow() });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: 'SO20261020120000000001', amount: 1 })
.expect(422);
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => null });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: 'SO-NOT-EXIST' })
.expect(404);
});
it('POST /api/pay/notify:配了回调密钥必须带正确签名', async () => {
mock(app.config.pay, 'callbackSecret', 's3cret');
mock(app.config.pay, 'mock', false);
mockModels({ subject: subjectRow(new Date(Date.now() - 1000)), order: () => orderRow() });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: 'SO20261020120000000001', transactionId: 'TXN-1', amount: 99 })
.expect(400);
const sign = crypto.createHmac('sha256', 's3cret')
.update('SO20261020120000000001\nTXN-1\n99')
.digest('hex');
await app.httpRequest().post('/api/pay/notify')
.set('X-Pay-Sign', sign)
.send({ orderNo: 'SO20261020120000000001', transactionId: 'TXN-1', amount: 99 })
.expect(200);
});
it('POST /api/internal/subject-orders/:orderNo/pay:运维模拟支付(内部令牌)', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() - 1000)), order: () => orderRow() });
await app.httpRequest()
.post('/api/internal/subject-orders/SO20261020120000000001/pay')
.expect(401);
const res = await app.httpRequest()
.post('/api/internal/subject-orders/SO20261020120000000001/pay')
.set('X-Internal-Token', 'test-internal-token')
.expect(200);
assert(res.body.data.order.status === 1, JSON.stringify(res.body));
});
it('POST /api/web/subjects/:id/orders:同套餐还有未支付订单 → 复用原单(不重复建单,剩余时间照旧)', async () => {
const existing = orderRow({ id: 200, orderNo: 'SO-REUSE-0001', createdAt: new Date() });
let created = 0;
mockModels({
subject: subjectRow(new Date(Date.now() + 86400000)),
pendingOrders: [ existing ],
onCreate: () => { created++; },
});
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(201);
const data = res.body.data;
assert(data.orderNo === 'SO-REUSE-0001', JSON.stringify(data));
assert(data.reused === true, JSON.stringify(data));
assert(created === 0, '同套餐未支付订单存在时不能再建单');
const remain = new Date(data.payExpireAt).getTime() - Date.now();
assert(remain > ORDER_TTL_MS - 60000 && remain <= ORDER_TTL_MS,
`应显示原订单剩余时间(约 2 小时),实际 ${remain}ms`);
});
it('POST /api/web/subjects/:id/orders:原订单已超时 → 关掉原单再建新单', async () => {
const stale = orderRow({ id: 200, orderNo: 'SO-STALE-0001', createdAt: new Date(Date.now() - 3 * 3600 * 1000) });
let created = 0;
mockModels({
subject: subjectRow(new Date(Date.now() + 86400000)),
pendingOrders: [ stale ],
onCreate: () => { created++; },
});
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(201);
assert(res.body.data.orderNo !== 'SO-STALE-0001', JSON.stringify(res.body));
assert(res.body.data.reused === false, JSON.stringify(res.body));
assert(created === 1, '超时订单不能复用,应新建一笔');
assert(orderUpdates.some(item => item.fields.status === 2), '超时的原订单应被关闭');
});
it('POST /api/web/subjects/:id/orders:微信支付未配置 → 订单照建但没有二维码', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)) });
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(201);
const data = res.body.data;
assert(data.qrImage === null && data.payable === false, JSON.stringify(data));
assert(data.codeUrl === null, JSON.stringify(data));
});
it('POST /api/pay/wechat/notify:验签通过 → 入账并回 SUCCESS(XML)', async () => {
enableWxpay();
const order = orderRow();
mockModels({ subject: subjectRow(new Date(Date.now() - 86400000)), order: () => order });
const xml = wxNotifyXml({
return_code: 'SUCCESS',
result_code: 'SUCCESS',
appid: 'wx-app-1',
mch_id: '1900000109',
nonce_str: 'wx-nonce',
out_trade_no: order.orderNo,
transaction_id: '4200001234',
total_fee: '9900',
time_end: '20261106103000',
});
const res = await app.httpRequest().post('/api/pay/wechat/notify')
.set('Content-Type', 'text/xml').send(xml).expect(200);
assert(res.text.includes('<![CDATA[SUCCESS]]>'), res.text);
assert(order.status === 1, JSON.stringify(order));
assert(order.transactionId === '4200001234', JSON.stringify(order));
assert(order.channel === 'wechat', JSON.stringify(order));
});
it('POST /api/pay/wechat/notify:签名不对 → 回 FAIL,不入账', async () => {
enableWxpay();
const order = orderRow();
mockModels({ subject: subjectRow(new Date(Date.now() - 86400000)), order: () => order });
const xml = '<xml><return_code><![CDATA[SUCCESS]]></return_code>'
+ '<result_code><![CDATA[SUCCESS]]></result_code>'
+ '<appid><![CDATA[wx-app-1]]></appid><mch_id><![CDATA[1900000109]]></mch_id>'
+ `<out_trade_no><![CDATA[${order.orderNo}]]></out_trade_no>`
+ '<total_fee><![CDATA[9900]]></total_fee><sign><![CDATA[BAD]]></sign></xml>';
const res = await app.httpRequest().post('/api/pay/wechat/notify')
.set('Content-Type', 'text/xml').send(xml).expect(200);
assert(res.text.includes('<![CDATA[FAIL]]>'), res.text);
assert(order.status === 0, '验签失败不能入账');
});
it('POST /api/pay/wechat/notify:微信支付未配置 → 回 FAIL', async () => {
const res = await app.httpRequest().post('/api/pay/wechat/notify')
.set('Content-Type', 'text/xml')
.send('<xml><return_code><![CDATA[SUCCESS]]></return_code>'
+ '<result_code><![CDATA[SUCCESS]]></result_code>'
+ '<out_trade_no><![CDATA[SO1]]></out_trade_no></xml>')
.expect(200);
assert(res.text.includes('<![CDATA[FAIL]]>'), res.text);
});
it('POST /api/web/subjects/:id/orders:微信返回「签名错误」→ 502 且透出原因(订单被关掉)', async () => {
enableWxpay();
mock(app, 'httpclient', {
async request() {
return {
status: 200,
data: '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名错误]]></return_msg></xml>',
};
},
});
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)) });
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(502);
assert(String(res.body.message).includes('签名错误'), JSON.stringify(res.body));
assert(orderUpdates.some(item => item.fields.status === 2), '下单失败要顺手关掉这笔订单');
});
});