payment-refund.integration.test.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import { describe, it, expect, beforeEach, vi } from 'vitest';
  2. import { DataSource } from 'typeorm';
  3. import {
  4. IntegrationTestDatabase,
  5. setupIntegrationDatabaseHooksWithEntities
  6. } from '@d8d/shared-test-util';
  7. import { PaymentMtService } from '../../src/services/payment.mt.service.js';
  8. import { PaymentMtEntity } from '../../src/entities/payment.mt.entity.js';
  9. import { PaymentStatus } from '../../src/entities/payment.types.js';
  10. // Mock 微信支付SDK
  11. vi.mock('wechatpay-node-v3', () => {
  12. return {
  13. default: vi.fn().mockImplementation(() => ({
  14. refunds: vi.fn().mockResolvedValue({
  15. id: 'mock_refund_id_123',
  16. out_refund_no: 'REFUND_ORDER_123_1234567890',
  17. status: 'SUCCESS'
  18. }),
  19. verifySign: vi.fn().mockResolvedValue(true),
  20. decipher_gcm: vi.fn().mockReturnValue(JSON.stringify({
  21. out_refund_no: 'REFUND_ORDER_123_1234567890',
  22. refund_status: 'SUCCESS'
  23. }))
  24. }))
  25. };
  26. });
  27. // Mock 系统配置服务
  28. vi.mock('@d8d/core-module-mt/system-config-module-mt', () => ({
  29. SystemConfigServiceMt: vi.fn().mockImplementation(() => ({
  30. getConfigsByKeys: vi.fn().mockResolvedValue({
  31. 'wx.payment.merchant.id': 'mock_merchant_id',
  32. 'wx.mini.app.id': 'mock_app_id',
  33. 'wx.payment.v3.key': 'mock_v3_key',
  34. 'wx.payment.notify.url': 'mock_notify_url',
  35. 'wx.payment.cert.serial.no': 'mock_cert_serial_no',
  36. 'wx.payment.public.key': 'mock_public_key',
  37. 'wx.payment.private.key': 'mock_private_key'
  38. })
  39. }))
  40. }));
  41. // Mock 订单服务
  42. vi.mock('@d8d/orders-module-mt', () => ({
  43. OrderMtService: vi.fn().mockImplementation(() => ({})),
  44. OrderMt: vi.fn()
  45. }));
  46. // 设置集成测试钩子
  47. setupIntegrationDatabaseHooksWithEntities([PaymentMtEntity])
  48. describe('PaymentRefund Integration Tests', () => {
  49. let dataSource: DataSource;
  50. let paymentService: PaymentMtService;
  51. beforeEach(async () => {
  52. // 获取集成测试数据库连接
  53. dataSource = await IntegrationTestDatabase.getDataSource();
  54. paymentService = new PaymentMtService(dataSource);
  55. });
  56. describe('refund method', () => {
  57. it('应该成功处理已支付订单的退款', async () => {
  58. // 准备测试数据
  59. const payment = new PaymentMtEntity();
  60. payment.tenantId = 1;
  61. payment.externalOrderId = 1001;
  62. payment.userId = 1;
  63. payment.totalAmount = 1000; // 10元
  64. payment.description = '测试订单';
  65. payment.paymentStatus = PaymentStatus.PAID;
  66. payment.outTradeNo = 'PAYMENT_1001_1234567890';
  67. payment.openid = 'mock_openid';
  68. payment.wechatTransactionId = 'mock_transaction_id';
  69. await dataSource.getRepository(PaymentMtEntity).save(payment);
  70. // 执行退款
  71. const refundResult = await paymentService.refund(
  72. 1,
  73. 'PAYMENT_1001_1234567890',
  74. 1000,
  75. '测试退款'
  76. );
  77. // 验证退款结果
  78. expect(refundResult).toMatchObject({
  79. refundId: expect.stringContaining('REFUND_PAYMENT_1001_1234567890'),
  80. outRefundNo: expect.stringContaining('REFUND_PAYMENT_1001_1234567890'),
  81. refundStatus: 'SUCCESS',
  82. refundAmount: 1000,
  83. refundTime: expect.any(String)
  84. });
  85. // 验证支付记录已更新
  86. const updatedPayment = await dataSource.getRepository(PaymentMtEntity).findOne({
  87. where: { outTradeNo: 'PAYMENT_1001_1234567890', tenantId: 1 }
  88. });
  89. expect(updatedPayment).toBeDefined();
  90. expect(updatedPayment?.refundStatus).toBe(PaymentStatus.REFUNDED);
  91. expect(updatedPayment?.refundAmount).toBe(1000);
  92. expect(updatedPayment?.refundTime).toBeInstanceOf(Date);
  93. });
  94. it('应该对不存在的支付记录抛出错误', async () => {
  95. await expect(
  96. paymentService.refund(1, 'NON_EXISTENT_ORDER', 1000)
  97. ).rejects.toThrow('支付记录不存在');
  98. });
  99. it('应该对未支付订单抛出错误', async () => {
  100. const payment = new PaymentMtEntity();
  101. payment.tenantId = 1;
  102. payment.externalOrderId = 1002;
  103. payment.userId = 1;
  104. payment.totalAmount = 1000;
  105. payment.description = '测试订单';
  106. payment.paymentStatus = PaymentStatus.PENDING;
  107. payment.outTradeNo = 'PAYMENT_1002_1234567890';
  108. payment.openid = 'mock_openid';
  109. await dataSource.getRepository(PaymentMtEntity).save(payment);
  110. await expect(
  111. paymentService.refund(1, 'PAYMENT_1002_1234567890', 1000)
  112. ).rejects.toThrow('订单支付状态不正确');
  113. });
  114. it('应该对无效退款金额抛出错误', async () => {
  115. const payment = new PaymentMtEntity();
  116. payment.tenantId = 1;
  117. payment.externalOrderId = 1003;
  118. payment.userId = 1;
  119. payment.totalAmount = 1000;
  120. payment.description = '测试订单';
  121. payment.paymentStatus = PaymentStatus.PAID;
  122. payment.outTradeNo = 'PAYMENT_1003_1234567890';
  123. payment.openid = 'mock_openid';
  124. payment.wechatTransactionId = 'mock_transaction_id';
  125. await dataSource.getRepository(PaymentMtEntity).save(payment);
  126. // 测试退款金额为0
  127. await expect(
  128. paymentService.refund(1, 'PAYMENT_1003_1234567890', 0)
  129. ).rejects.toThrow('退款金额无效');
  130. // 测试退款金额超过支付金额
  131. await expect(
  132. paymentService.refund(1, 'PAYMENT_1003_1234567890', 2000)
  133. ).rejects.toThrow('退款金额无效');
  134. });
  135. });
  136. describe('handleRefundCallback method', () => {
  137. it('应该成功处理退款回调', async () => {
  138. const mockCallbackData = {
  139. resource: {
  140. ciphertext: 'mock_ciphertext',
  141. associated_data: '',
  142. nonce: 'mock_nonce'
  143. }
  144. };
  145. const mockHeaders = {
  146. 'wechatpay-timestamp': 'mock_timestamp',
  147. 'wechatpay-nonce': 'mock_nonce',
  148. 'wechatpay-signature': 'mock_signature',
  149. 'wechatpay-serial': 'mock_serial'
  150. };
  151. const mockRawBody = 'mock_raw_body';
  152. // 执行退款回调处理
  153. await expect(
  154. paymentService.handleRefundCallback(mockCallbackData, mockHeaders, mockRawBody)
  155. ).resolves.not.toThrow();
  156. });
  157. });
  158. describe('multi-tenant refund data isolation', () => {
  159. it('应该只退款特定租户的支付记录', async () => {
  160. // 创建租户1的支付记录
  161. const payment1 = new PaymentMtEntity();
  162. payment1.tenantId = 1;
  163. payment1.externalOrderId = 1004;
  164. payment1.userId = 1;
  165. payment1.totalAmount = 1000;
  166. payment1.description = '租户1订单';
  167. payment1.paymentStatus = PaymentStatus.PAID;
  168. payment1.outTradeNo = 'PAYMENT_1004_1234567890';
  169. payment1.openid = 'mock_openid';
  170. payment1.wechatTransactionId = 'mock_transaction_id';
  171. // 创建租户2的支付记录
  172. const payment2 = new PaymentMtEntity();
  173. payment2.tenantId = 2;
  174. payment2.externalOrderId = 1004;
  175. payment2.userId = 1;
  176. payment2.totalAmount = 1000;
  177. payment2.description = '租户2订单';
  178. payment2.paymentStatus = PaymentStatus.PAID;
  179. payment2.outTradeNo = 'PAYMENT_1004_1234567890';
  180. payment2.openid = 'mock_openid';
  181. payment2.wechatTransactionId = 'mock_transaction_id';
  182. await dataSource.getRepository(PaymentMtEntity).save([payment1, payment2]);
  183. // 为租户1执行退款
  184. await paymentService.refund(1, 'PAYMENT_1004_1234567890', 1000);
  185. // 验证租户1的支付记录已更新
  186. const tenant1Payment = await dataSource.getRepository(PaymentMtEntity).findOne({
  187. where: { outTradeNo: 'PAYMENT_1004_1234567890', tenantId: 1 }
  188. });
  189. expect(tenant1Payment?.refundStatus).toBe(PaymentStatus.REFUNDED);
  190. // 验证租户2的支付记录未受影响
  191. const tenant2Payment = await dataSource.getRepository(PaymentMtEntity).findOne({
  192. where: { outTradeNo: 'PAYMENT_1004_1234567890', tenantId: 2 }
  193. });
  194. expect(tenant2Payment?.refundStatus).toBeNull();
  195. });
  196. });
  197. });