payment.integration.test.ts 12 KB

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