payment.integration.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. import { describe, it, expect, beforeEach, vi } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import {
  4. IntegrationTestDatabase,
  5. setupIntegrationDatabaseHooks,
  6. TestDataFactory
  7. } from '~/utils/server/integration-test-db';
  8. import { paymentRoutesExport } from '@d8d/server/api';
  9. import { AuthService } from '@d8d/server/modules/auth/auth.service';
  10. import { UserService } from '@d8d/server/modules/users/user.service';
  11. import { OrderStatus, PaymentStatus } from '@d8d/server/share/order.types';
  12. import { config } from 'dotenv';
  13. import { resolve } from 'path';
  14. // 导入微信支付SDK用于模拟
  15. import WxPay from 'wechatpay-node-v3';
  16. // 在测试环境中加载环境变量
  17. config({ path: resolve(process.cwd(), '.env') });
  18. vi.mock('wechatpay-node-v3')
  19. // 设置集成测试钩子
  20. setupIntegrationDatabaseHooks()
  21. describe('支付API集成测试', () => {
  22. let client: ReturnType<typeof testClient<typeof paymentRoutesExport>>['api']['v1'];
  23. let testToken: string;
  24. let testUser: any;
  25. let testRoute: any;
  26. let testOrder: any;
  27. beforeEach(async () => {
  28. // 创建测试客户端
  29. client = testClient(paymentRoutesExport).api.v1;
  30. // 创建测试用户并生成token
  31. const dataSource = await IntegrationTestDatabase.getDataSource();
  32. const userService = new UserService(dataSource);
  33. const authService = new AuthService(userService);
  34. // 创建测试用户
  35. testUser = await TestDataFactory.createTestUser(dataSource);
  36. // 生成测试用户的token
  37. testToken = authService.generateToken(testUser);
  38. // 创建测试路线
  39. testRoute = await TestDataFactory.createTestRoute(dataSource);
  40. // 创建测试订单
  41. testOrder = await TestDataFactory.createTestOrder(dataSource, {
  42. userId: testUser.id,
  43. routeId: testRoute.id,
  44. passengerCount: 2,
  45. totalAmount: 200.00,
  46. status: OrderStatus.PENDING_PAYMENT,
  47. paymentStatus: PaymentStatus.PENDING
  48. });
  49. // 设置微信支付SDK的全局mock
  50. const mockWxPay = {
  51. transactions_jsapi: vi.fn().mockResolvedValue({
  52. package: 'prepay_id=wx_test_prepay_id_123456',
  53. timeStamp: Math.floor(Date.now() / 1000).toString(),
  54. nonceStr: 'test_nonce_string',
  55. signType: 'RSA',
  56. paySign: 'test_pay_sign'
  57. }),
  58. verifySign: vi.fn().mockResolvedValue(true),
  59. decipher_gcm: vi.fn().mockReturnValue(JSON.stringify({
  60. out_trade_no: `ORDER_${testOrder.id}_${Date.now()}`,
  61. trade_state: 'SUCCESS',
  62. transaction_id: 'test_transaction_id',
  63. amount: {
  64. total: 20000
  65. }
  66. })),
  67. getSignature: vi.fn().mockReturnValue('mock_signature')
  68. };
  69. // 模拟PaymentService的wxPay实例
  70. vi.mocked(WxPay).mockImplementation(() => mockWxPay as any);
  71. });
  72. describe('POST /payment - 创建支付', () => {
  73. it('应该成功创建支付订单', async () => {
  74. const response = await client.payment.$post({
  75. json: {
  76. orderId: testOrder.id,
  77. totalAmount: 20000, // 200元,单位分
  78. description: '测试支付订单',
  79. openid: 'oJy1-16IIG18XZLl7G32k1hHMUFg'
  80. },
  81. },
  82. {
  83. headers: {
  84. 'Authorization': `Bearer ${testToken}`
  85. }
  86. });
  87. expect(response.status).toBe(200);
  88. if (response.status === 200) {
  89. const result = await response.json();
  90. console.debug('支付创建返回结果:', result);
  91. expect(result).toHaveProperty('paymentId');
  92. expect(result).toHaveProperty('timeStamp');
  93. expect(result).toHaveProperty('nonceStr');
  94. expect(result).toHaveProperty('package');
  95. expect(result).toHaveProperty('signType');
  96. expect(result).toHaveProperty('paySign');
  97. expect(result.paymentId).toBeDefined();
  98. expect(result.paymentId).not.toBe('undefined');
  99. }
  100. });
  101. it('应该拒绝未认证的请求', async () => {
  102. const response = await client.payment.$post({
  103. json: {
  104. orderId: testOrder.id,
  105. totalAmount: 20000,
  106. description: '测试支付订单'
  107. }
  108. });
  109. expect(response.status).toBe(401);
  110. });
  111. it('应该验证订单存在性', async () => {
  112. const response = await client.payment.$post({
  113. json: {
  114. orderId: 99999, // 不存在的订单ID
  115. totalAmount: 20000,
  116. description: '测试支付订单'
  117. },
  118. },
  119. {
  120. headers: {
  121. 'Authorization': `Bearer ${testToken}`
  122. }
  123. });
  124. expect(response.status).toBe(500);
  125. if (response.status === 500) {
  126. const result = await response.json();
  127. expect(result.message).toContain('订单不存在');
  128. }
  129. });
  130. it('应该验证支付金额匹配', async () => {
  131. const response = await client.payment.$post({
  132. json: {
  133. orderId: testOrder.id,
  134. totalAmount: 30000, // 金额不匹配
  135. description: '测试支付订单'
  136. },
  137. },
  138. {
  139. headers: {
  140. 'Authorization': `Bearer ${testToken}`
  141. }
  142. });
  143. expect(response.status).toBe(500);
  144. if (response.status === 500) {
  145. const result = await response.json();
  146. expect(result.message).toContain('支付金额与订单金额不匹配');
  147. }
  148. });
  149. it('应该验证订单支付状态', async () => {
  150. // 更新订单状态为已支付
  151. const dataSource = await IntegrationTestDatabase.getDataSource();
  152. const orderRepository = dataSource.getRepository('Order');
  153. await orderRepository.update(testOrder.id, {
  154. paymentStatus: PaymentStatus.PAID
  155. });
  156. const response = await client.payment.$post({
  157. json: {
  158. orderId: testOrder.id,
  159. totalAmount: 20000,
  160. description: '测试支付订单'
  161. },
  162. },
  163. {
  164. headers: {
  165. 'Authorization': `Bearer ${testToken}`
  166. }
  167. });
  168. expect(response.status).toBe(500);
  169. if (response.status === 500) {
  170. const result = await response.json();
  171. expect(result.message).toContain('订单支付状态不正确');
  172. }
  173. });
  174. });
  175. describe('POST /payment/callback - 支付回调', () => {
  176. it('应该成功处理支付成功回调', async () => {
  177. const timestamp = Math.floor(Date.now() / 1000).toString();
  178. const nonce = Math.random().toString(36).substring(2, 15);
  179. const callbackData = {
  180. id: 'EV-201802251122332345',
  181. create_time: '2018-06-08T10:34:56+08:00',
  182. event_type: 'TRANSACTION.SUCCESS',
  183. resource_type: 'encrypt-resource',
  184. resource: {
  185. algorithm: 'AEAD_AES_256_GCM',
  186. ciphertext: 'encrypted_data',
  187. nonce: 'random_nonce',
  188. associated_data: 'associated_data'
  189. },
  190. summary: 'payment_success'
  191. };
  192. const response = await client.payment.callback.$post({
  193. json: callbackData
  194. }, {
  195. headers: {
  196. 'wechatpay-timestamp': timestamp,
  197. 'wechatpay-nonce': nonce,
  198. 'wechatpay-signature': 'mock_signature_for_test',
  199. 'wechatpay-serial': process.env.WECHAT_PLATFORM_CERT_SERIAL_NO || ''
  200. }
  201. });
  202. expect(response.status).toBe(200);
  203. if (response.status === 200) {
  204. const result = await response.text();
  205. expect(result).toBe('SUCCESS');
  206. }
  207. });
  208. it('应该处理支付失败回调', async () => {
  209. const timestamp = Math.floor(Date.now() / 1000).toString();
  210. const nonce = Math.random().toString(36).substring(2, 15);
  211. const callbackData = {
  212. id: 'EV-201802251122332346',
  213. create_time: '2018-06-08T10:34:56+08:00',
  214. event_type: 'TRANSACTION.FAIL',
  215. resource_type: 'encrypt-resource',
  216. resource: {
  217. algorithm: 'AEAD_AES_256_GCM',
  218. ciphertext: 'encrypted_data',
  219. nonce: 'random_nonce',
  220. associated_data: 'associated_data'
  221. },
  222. summary: 'payment_failed'
  223. };
  224. const response = await client.payment.callback.$post({
  225. json: callbackData
  226. }, {
  227. headers: {
  228. 'wechatpay-timestamp': timestamp,
  229. 'wechatpay-nonce': nonce,
  230. 'wechatpay-signature': 'mock_signature_for_test',
  231. 'wechatpay-serial': process.env.WECHAT_PLATFORM_CERT_SERIAL_NO || ''
  232. }
  233. });
  234. expect(response.status).toBe(200);
  235. if (response.status === 200) {
  236. const result = await response.text();
  237. expect(result).toBe('SUCCESS');
  238. }
  239. });
  240. it('应该处理无效的回调数据', async () => {
  241. const response = await client.payment.callback.$post({
  242. json: { invalid: 'data' } as any
  243. }, {
  244. headers: {
  245. 'wechatpay-timestamp': '1622456896',
  246. 'wechatpay-nonce': 'random_nonce_string',
  247. 'wechatpay-signature': 'signature_data',
  248. 'wechatpay-serial': process.env.WECHAT_PLATFORM_CERT_SERIAL_NO || ''
  249. }
  250. });
  251. expect(response.status).toBe(400);
  252. });
  253. });
  254. describe('支付状态流转测试', () => {
  255. it('应该正确更新订单支付状态', async () => {
  256. // 创建支付
  257. const createResponse = await client.payment.$post({
  258. json: {
  259. orderId: testOrder.id,
  260. totalAmount: 20000,
  261. description: '测试支付订单',
  262. openid: 'oJy1-16IIG18XZLl7G32k1hHMUFg'
  263. },
  264. },
  265. {
  266. headers: {
  267. 'Authorization': `Bearer ${testToken}`
  268. }
  269. });
  270. expect(createResponse.status).toBe(200);
  271. // 验证订单状态已更新为处理中
  272. const dataSource = await IntegrationTestDatabase.getDataSource();
  273. const orderRepository = dataSource.getRepository('Order');
  274. const updatedOrder = await orderRepository.findOne({
  275. where: { id: testOrder.id }
  276. });
  277. expect(updatedOrder?.paymentStatus).toBe(PaymentStatus.PROCESSING);
  278. });
  279. });
  280. describe('微信支付JSAPI参数生成测试', () => {
  281. it('应该生成正确的支付参数格式', async () => {
  282. const response = await client.payment.$post({
  283. json: {
  284. orderId: testOrder.id,
  285. totalAmount: 20000,
  286. description: '测试支付订单',
  287. openid: 'oJy1-16IIG18XZLl7G32k1hHMUFg'
  288. },
  289. },
  290. {
  291. headers: {
  292. 'Authorization': `Bearer ${testToken}`
  293. }
  294. });
  295. expect(response.status).toBe(200);
  296. if (response.status === 200) {
  297. const result = await response.json();
  298. // 验证返回参数格式
  299. expect(result.timeStamp).toMatch(/^\d+$/); // 时间戳应该是数字字符串
  300. expect(result.nonceStr).toBeTruthy(); // 随机字符串应该存在
  301. expect(result.package).toContain('prepay_id=');
  302. expect(result.signType).toBe('RSA');
  303. expect(result.paySign).toBeTruthy(); // 签名应该存在
  304. }
  305. });
  306. });
  307. });