payment-callback.integration.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import {
  4. IntegrationTestDatabase,
  5. setupIntegrationDatabaseHooksWithEntities
  6. } from '@d8d/shared-test-util';
  7. import { PaymentMtRoutes } from '../../src/routes/payment.mt.routes.js';
  8. import { PaymentMtEntity } from '../../src/entities/payment.mt.entity.js';
  9. import { PaymentStatus } from '../../src/entities/payment.types.js';
  10. import { UserEntityMt } from '@d8d/user-module-mt';
  11. import { RoleMt } from '@d8d/user-module-mt';
  12. import { FileMt } from '@d8d/file-module-mt';
  13. import { OrderMt } from '@d8d/orders-module-mt';
  14. import { MerchantMt } from '@d8d/merchant-module-mt';
  15. import { SupplierMt } from '@d8d/supplier-module-mt';
  16. import { DeliveryAddressMt } from '@d8d/delivery-address-module-mt';
  17. import { AreaEntityMt } from '@d8d/geo-areas-mt';
  18. import { config } from 'dotenv';
  19. import { resolve } from 'path';
  20. // 导入微信支付SDK用于模拟
  21. import WxPay from 'wechatpay-node-v3';
  22. // 在测试环境中加载环境变量
  23. config({ path: resolve(process.cwd(), '.env.test') });
  24. vi.mock('wechatpay-node-v3')
  25. // 设置集成测试钩子
  26. setupIntegrationDatabaseHooksWithEntities([PaymentMtEntity, UserEntityMt, FileMt, RoleMt, OrderMt, MerchantMt, SupplierMt, DeliveryAddressMt, AreaEntityMt])
  27. describe('支付回调API集成测试 - 多租户版本', () => {
  28. let client: ReturnType<typeof testClient<typeof PaymentMtRoutes>>;
  29. let testUser: UserEntityMt;
  30. let testPayment: PaymentMtEntity;
  31. let testOrder: OrderMt;
  32. // 使用真实的微信支付回调数据 - 直接使用原始请求体字符串
  33. const rawBody = '{"id":"495e231b-9fd8-54a1-8a30-2a38a807744c","create_time":"2025-10-25T12:48:11+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"tl1/8FRRn6g0gRq8IoVR8+95VuIADYBDOt6N9PKiHVhiD6l++W5g/wg6VlsCRIZJ+KWMYTaf5FzQHMjCs8o9otIkLLuJA2aZC+kCQtGxNfyVBwxool/tLT9mHd0dFGThqbj8vb/lm+jjNcmmiWHz+J1ZRvGl7mH4I714vudok7JRt5Q0u0tYaLWr76TTXuQErlA7T4KbeVeGAj8iMpu2ErCpR9QRif36Anc5ARjNYrIWfraXlmUXVbXermDyJ8r4o/4QCFfGk8L1u1WqNYASrRTQvQ8OPqj/J21OkDxbPPrOiEmAX1jOvONvIVEe9Lbkm6rdhW4aLRoZYtiusAk/Vm7MI/UYPwRZbyuc4wwdA1T1D4RdJd/m2I4KSvZHQgs0DM0tLqlb0z3880XYNr8iPFnyu2r8Z8LGcXD+COm06vc7bvNWh3ODwmMrmZQkym/Y/T3X/h/4MZj7+1h2vYHqnnrsgtNPHc/2IwWC/fQlPwtSrLh6iUxSd0betFpKLSq08CaJZvnenpDf1ORRMvd8EhTtIJJ4mV4v+VzCOYNhIcBhKp9XwsuhxIdkpGGmNPpow2c2BXY=","associated_data":"transaction","nonce":"sTnWce32BTQP"}}';
  34. const callbackHeader = {
  35. 'wechatpay-timestamp': '1761367693',
  36. 'wechatpay-nonce': 'PVDFxrQiJclkR28HpAYPDiIlS2VaGp9U',
  37. 'wechatpay-signature': 'hwR1KKN1bIPAhatIHTen7fwNDyvONS/picpcqSHtUCGkbvhYLVUqC87ksBJs6bovNI0cKNvrLr6gqp/HR4TK/ijgrD6w9W/oYc6bKyO9lNarggsQKHBv5x5yX8OjBOzqtgiHOVj44RCPrglJ5bFDlxIhnhs9jnGUine0qlvrVwBZAylt5X4oFmPammHoV4lLHtGt0L4zr5y6LoZL80LpctDCOCtwC4JdUUY5AumkMYo8lNs+xK0NAN7EVNKCWUzoQ1pVdBTGZWDP+b8+6gswP6JDsL3a4H4Fw3WGh4DZPskDQAe0sn85UGXO3m03OkDq3WkiCkOut4YZMuKBeCBpWA==',
  38. 'wechatpay-serial': '6C2C991E621267BFA5BFD5F32476427343A0B2AD'
  39. };
  40. beforeEach(async () => {
  41. // 创建测试客户端
  42. client = testClient(PaymentMtRoutes);
  43. // 创建测试用户
  44. const dataSource = await IntegrationTestDatabase.getDataSource();
  45. const userRepository = dataSource.getRepository(UserEntityMt);
  46. testUser = userRepository.create({
  47. username: `test_user_${Date.now()}`,
  48. password: 'test_password',
  49. nickname: '测试用户',
  50. openid: 'oJy1-16IIG18XZLl7G32k1hHMUFg',
  51. tenantId: 1
  52. });
  53. await userRepository.save(testUser);
  54. // 创建商户记录
  55. const merchantRepository = dataSource.getRepository(MerchantMt);
  56. const testMerchant = merchantRepository.create({
  57. tenantId: 1,
  58. name: '测试商户',
  59. username: `m${Date.now()}`.slice(-19), // 确保不超过20字符
  60. password: 'test_password',
  61. state: 1,
  62. createdBy: testUser.id,
  63. updatedBy: testUser.id
  64. });
  65. await merchantRepository.save(testMerchant);
  66. // 创建供货商记录
  67. const supplierRepository = dataSource.getRepository(SupplierMt);
  68. const testSupplier = supplierRepository.create({
  69. tenantId: 1,
  70. name: '测试供货商',
  71. username: `s${Date.now()}`.slice(-49), // 确保不超过50字符
  72. password: 'test_password',
  73. state: 1,
  74. createdBy: testUser.id,
  75. updatedBy: testUser.id
  76. });
  77. await supplierRepository.save(testSupplier);
  78. // 创建配送地址记录
  79. const addressRepository = dataSource.getRepository(DeliveryAddressMt);
  80. const testAddress = addressRepository.create({
  81. tenantId: 1,
  82. userId: testUser.id,
  83. name: '测试收货人',
  84. mobile: '13800138000',
  85. province: 110000,
  86. city: 110100,
  87. district: 110101,
  88. town: 110101001,
  89. address: '测试地址',
  90. isDefault: 1,
  91. createdBy: testUser.id,
  92. updatedBy: testUser.id
  93. });
  94. await addressRepository.save(testAddress);
  95. // 创建测试订单
  96. const orderRepository = dataSource.getRepository(OrderMt);
  97. testOrder = orderRepository.create({
  98. tenantId: 1,
  99. orderNo: `ORD${Date.now()}`,
  100. userId: testUser.id,
  101. amount: 1,
  102. costAmount: 0.5,
  103. payAmount: 1,
  104. orderType: 1,
  105. payType: 2,
  106. payState: 0, // 未支付
  107. state: 0,
  108. addressId: testAddress.id,
  109. merchantId: testMerchant.id,
  110. supplierId: testSupplier.id,
  111. createdBy: testUser.id,
  112. updatedBy: testUser.id
  113. });
  114. await orderRepository.save(testOrder);
  115. // 创建测试支付记录,使用与真实回调数据一致的金额
  116. const paymentRepository = dataSource.getRepository(PaymentMtEntity);
  117. testPayment = paymentRepository.create({
  118. externalOrderId: testOrder.id, // 使用订单ID作为外部订单ID
  119. userId: testUser.id,
  120. totalAmount: 1, // 1分钱,与真实回调数据一致
  121. description: '测试支付',
  122. paymentStatus: PaymentStatus.PROCESSING, // 设置为处理中状态,模拟已发起支付
  123. openid: testUser.openid!,
  124. outTradeNo: `ORDER_${testOrder.id}_${Date.now()}`,
  125. tenantId: 1
  126. });
  127. await paymentRepository.save(testPayment);
  128. // 设置微信支付SDK的全局mock
  129. const mockWxPay = {
  130. transactions_jsapi: vi.fn().mockResolvedValue({
  131. package: 'prepay_id=wx_test_prepay_id_123456',
  132. timeStamp: Math.floor(Date.now() / 1000).toString(),
  133. nonceStr: 'test_nonce_string',
  134. signType: 'RSA',
  135. paySign: 'test_pay_sign'
  136. }),
  137. verifySign: vi.fn().mockResolvedValue(true),
  138. decipher_gcm: vi.fn().mockReturnValue(JSON.stringify({
  139. out_trade_no: testPayment.outTradeNo, // 使用数据库中保存的 outTradeNo
  140. trade_state: 'SUCCESS',
  141. transaction_id: 'test_transaction_id',
  142. amount: {
  143. total: 1
  144. }
  145. })),
  146. getSignature: vi.fn().mockReturnValue('mock_signature')
  147. };
  148. // 模拟PaymentService的wxPay实例
  149. vi.mocked(WxPay).mockImplementation(() => mockWxPay as any);
  150. });
  151. afterEach(() => {
  152. // 清理 mock
  153. vi.mocked(WxPay).mockClear();
  154. });
  155. describe('POST /payment/callback - 支付回调', () => {
  156. it('应该成功处理支付成功回调并更新订单状态', async () => {
  157. const response = await client.payment.callback.$post({
  158. // 使用空的json参数,通过init传递原始请求体
  159. json: {}
  160. }, {
  161. headers: callbackHeader,
  162. init: {
  163. body: rawBody
  164. }
  165. });
  166. // 现在支付记录存在,回调处理应该成功
  167. expect(response.status).toBe(200);
  168. if (response.status === 200) {
  169. const result = await response.text();
  170. expect(result).toBe('SUCCESS');
  171. // 验证订单状态已更新为已支付 (2)
  172. const dataSource = await IntegrationTestDatabase.getDataSource();
  173. const orderRepository = dataSource.getRepository(OrderMt);
  174. const updatedOrder = await orderRepository.findOne({
  175. where: { id: testOrder.id, tenantId: 1 }
  176. });
  177. expect(updatedOrder).toBeDefined();
  178. expect(updatedOrder?.payState).toBe(2); // 已支付
  179. }
  180. });
  181. it('应该处理支付失败回调并更新订单状态', async () => {
  182. // 模拟支付失败的回调数据
  183. const mockWxPay = {
  184. verifySign: vi.fn().mockResolvedValue(true),
  185. decipher_gcm: vi.fn().mockReturnValue(JSON.stringify({
  186. out_trade_no: testPayment.outTradeNo,
  187. trade_state: 'FAIL',
  188. transaction_id: null,
  189. amount: {
  190. total: 1
  191. }
  192. }))
  193. };
  194. vi.mocked(WxPay).mockImplementation(() => mockWxPay as any);
  195. const response = await client.payment.callback.$post({
  196. json: {}
  197. }, {
  198. headers: callbackHeader,
  199. init: {
  200. body: rawBody
  201. }
  202. });
  203. expect(response.status).toBe(200);
  204. if (response.status === 200) {
  205. const result = await response.text();
  206. expect(result).toBe('SUCCESS');
  207. // 验证订单状态已更新为支付失败 (4)
  208. const dataSource = await IntegrationTestDatabase.getDataSource();
  209. const orderRepository = dataSource.getRepository(OrderMt);
  210. const updatedOrder = await orderRepository.findOne({
  211. where: { id: testOrder.id, tenantId: 1 }
  212. });
  213. expect(updatedOrder).toBeDefined();
  214. expect(updatedOrder?.payState).toBe(4); // 支付失败
  215. }
  216. });
  217. it('应该处理退款回调并更新订单状态', async () => {
  218. // 模拟退款回调数据
  219. const mockWxPay = {
  220. verifySign: vi.fn().mockResolvedValue(true),
  221. decipher_gcm: vi.fn().mockReturnValue(JSON.stringify({
  222. out_trade_no: testPayment.outTradeNo,
  223. trade_state: 'REFUND',
  224. transaction_id: 'test_refund_transaction_id',
  225. amount: {
  226. total: 1
  227. }
  228. }))
  229. };
  230. vi.mocked(WxPay).mockImplementation(() => mockWxPay as any);
  231. const response = await client.payment.callback.$post({
  232. json: {}
  233. }, {
  234. headers: callbackHeader,
  235. init: {
  236. body: rawBody
  237. }
  238. });
  239. expect(response.status).toBe(200);
  240. if (response.status === 200) {
  241. const result = await response.text();
  242. expect(result).toBe('SUCCESS');
  243. // 验证订单状态已更新为已退款 (3)
  244. const dataSource = await IntegrationTestDatabase.getDataSource();
  245. const orderRepository = dataSource.getRepository(OrderMt);
  246. const updatedOrder = await orderRepository.findOne({
  247. where: { id: testOrder.id, tenantId: 1 }
  248. });
  249. expect(updatedOrder).toBeDefined();
  250. expect(updatedOrder?.payState).toBe(3); // 已退款
  251. }
  252. });
  253. it('应该验证多租户数据隔离', async () => {
  254. // 创建第二个租户的测试数据
  255. const dataSource = await IntegrationTestDatabase.getDataSource();
  256. const userRepository = dataSource.getRepository(UserEntityMt);
  257. const testUser2 = userRepository.create({
  258. username: `test_user2_${Date.now()}`,
  259. password: 'test_password',
  260. nickname: '测试用户2',
  261. openid: 'oJy1-16IIG18XZLl7G32k1hHMUFg2',
  262. tenantId: 2
  263. });
  264. await userRepository.save(testUser2);
  265. // 创建第二个租户的商户记录
  266. const merchantRepository = dataSource.getRepository(MerchantMt);
  267. const testMerchant2 = merchantRepository.create({
  268. tenantId: 2,
  269. name: '测试商户2',
  270. username: `test_merchant2_${Date.now()}`,
  271. password: 'test_password',
  272. state: 1,
  273. createdBy: testUser2.id,
  274. updatedBy: testUser2.id
  275. });
  276. await merchantRepository.save(testMerchant2);
  277. // 创建第二个租户的供货商记录
  278. const supplierRepository = dataSource.getRepository(SupplierMt);
  279. const testSupplier2 = supplierRepository.create({
  280. tenantId: 2,
  281. name: '测试供货商2',
  282. username: `test_supplier2_${Date.now()}`,
  283. password: 'test_password',
  284. state: 1,
  285. createdBy: testUser2.id,
  286. updatedBy: testUser2.id
  287. });
  288. await supplierRepository.save(testSupplier2);
  289. // 创建第二个租户的配送地址记录
  290. const addressRepository = dataSource.getRepository(DeliveryAddressMt);
  291. const testAddress2 = addressRepository.create({
  292. tenantId: 2,
  293. userId: testUser2.id,
  294. name: '测试收货人2',
  295. mobile: '13800138001',
  296. province: 110000,
  297. city: 110100,
  298. district: 110101,
  299. town: 110101001,
  300. address: '测试地址2',
  301. isDefault: 1,
  302. createdBy: testUser2.id,
  303. updatedBy: testUser2.id
  304. });
  305. await addressRepository.save(testAddress2);
  306. const orderRepository = dataSource.getRepository(OrderMt);
  307. const testOrder2 = orderRepository.create({
  308. tenantId: 2,
  309. orderNo: `ORD${Date.now()}_2`,
  310. userId: testUser2.id,
  311. amount: 1,
  312. costAmount: 0.5,
  313. payAmount: 1,
  314. orderType: 1,
  315. payType: 2,
  316. payState: 0,
  317. state: 0,
  318. addressId: testAddress2.id,
  319. merchantId: testMerchant2.id,
  320. supplierId: testSupplier2.id,
  321. createdBy: testUser2.id,
  322. updatedBy: testUser2.id
  323. });
  324. await orderRepository.save(testOrder2);
  325. const paymentRepository = dataSource.getRepository(PaymentMtEntity);
  326. const testPayment2 = paymentRepository.create({
  327. externalOrderId: testOrder2.id,
  328. userId: testUser2.id,
  329. totalAmount: 1,
  330. description: '测试支付2',
  331. paymentStatus: PaymentStatus.PROCESSING,
  332. openid: testUser2.openid!,
  333. outTradeNo: `ORDER_${testOrder2.id}_${Date.now()}`,
  334. tenantId: 2
  335. });
  336. await paymentRepository.save(testPayment2);
  337. // 处理租户1的支付回调
  338. const response = await client.payment.callback.$post({
  339. json: {}
  340. }, {
  341. headers: callbackHeader,
  342. init: {
  343. body: rawBody
  344. }
  345. });
  346. expect(response.status).toBe(200);
  347. // 验证租户1的订单状态已更新
  348. const updatedOrder1 = await orderRepository.findOne({
  349. where: { id: testOrder.id, tenantId: 1 }
  350. });
  351. expect(updatedOrder1?.payState).toBe(2); // 已支付
  352. // 验证租户2的订单状态未受影响
  353. const updatedOrder2 = await orderRepository.findOne({
  354. where: { id: testOrder2.id, tenantId: 2 }
  355. });
  356. expect(updatedOrder2?.payState).toBe(0); // 仍为未支付
  357. });
  358. it('应该处理无效的回调数据格式', async () => {
  359. const response = await client.payment.callback.$post({
  360. body: 'invalid json data'
  361. }, {
  362. headers: {
  363. ...callbackHeader,
  364. 'content-type': 'text/plain'
  365. }
  366. });
  367. // 由于JSON解析失败,应该返回500错误
  368. expect(response.status).toBe(500);
  369. });
  370. it('应该处理缺少必要头信息的情况', async () => {
  371. const response = await client.payment.callback.$post({
  372. body: rawBody
  373. }, {
  374. headers: {
  375. // 缺少必要的微信支付头信息
  376. 'Content-Type': 'text/plain'
  377. }
  378. });
  379. // 由于缺少必要头信息,应该返回500错误
  380. expect(response.status).toBe(500);
  381. });
  382. it('应该验证回调数据解密后的支付处理', async () => {
  383. const response = await client.payment.callback.$post({
  384. // 使用空的json参数,通过init传递原始请求体
  385. json: {}
  386. }, {
  387. headers: callbackHeader,
  388. init: {
  389. body: rawBody
  390. }
  391. });
  392. // 现在支付记录存在,回调处理应该成功
  393. expect(response.status).toBe(200);
  394. if (response.status === 200) {
  395. const result = await response.text();
  396. expect(result).toBe('SUCCESS');
  397. }
  398. });
  399. });
  400. });