payment.integration.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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.paymentId).toBeDefined();
  99. expect(result.paymentId).not.toBe('undefined');
  100. }
  101. });
  102. it('应该拒绝未认证的请求', async () => {
  103. const response = await client.payment.$post({
  104. json: {
  105. orderId: testOrder.id,
  106. totalAmount: 20000,
  107. description: '测试支付订单'
  108. }
  109. });
  110. expect(response.status).toBe(401);
  111. });
  112. it('应该验证订单存在性', async () => {
  113. const response = await client.payment.$post({
  114. json: {
  115. orderId: 99999, // 不存在的订单ID
  116. totalAmount: 20000,
  117. description: '测试支付订单'
  118. },
  119. },
  120. {
  121. headers: {
  122. 'Authorization': `Bearer ${testToken}`
  123. }
  124. });
  125. expect(response.status).toBe(500);
  126. if (response.status === 500) {
  127. const result = await response.json();
  128. expect(result.message).toContain('订单不存在');
  129. }
  130. });
  131. it('应该验证支付金额匹配', async () => {
  132. const response = await client.payment.$post({
  133. json: {
  134. orderId: testOrder.id,
  135. totalAmount: 30000, // 金额不匹配
  136. description: '测试支付订单'
  137. },
  138. },
  139. {
  140. headers: {
  141. 'Authorization': `Bearer ${testToken}`
  142. }
  143. });
  144. expect(response.status).toBe(500);
  145. if (response.status === 500) {
  146. const result = await response.json();
  147. expect(result.message).toContain('支付金额与订单金额不匹配');
  148. }
  149. });
  150. it('应该验证订单支付状态', async () => {
  151. // 更新订单状态为已支付
  152. const dataSource = await IntegrationTestDatabase.getDataSource();
  153. const orderRepository = dataSource.getRepository('Order');
  154. await orderRepository.update(testOrder.id, {
  155. paymentStatus: PaymentStatus.PAID
  156. });
  157. const response = await client.payment.$post({
  158. json: {
  159. orderId: testOrder.id,
  160. totalAmount: 20000,
  161. description: '测试支付订单'
  162. },
  163. },
  164. {
  165. headers: {
  166. 'Authorization': `Bearer ${testToken}`
  167. }
  168. });
  169. expect(response.status).toBe(500);
  170. if (response.status === 500) {
  171. const result = await response.json();
  172. expect(result.message).toContain('订单支付状态不正确');
  173. }
  174. });
  175. it('应该拒绝没有openid的用户支付', async () => {
  176. // 创建没有openid的测试用户
  177. const dataSource = await IntegrationTestDatabase.getDataSource();
  178. const userService = new UserService(dataSource);
  179. const authService = new AuthService(userService);
  180. const userWithoutOpenid = await TestDataFactory.createTestUser(dataSource, {
  181. openid: null
  182. });
  183. const tokenWithoutOpenid = authService.generateToken(userWithoutOpenid);
  184. const response = await client.payment.$post({
  185. json: {
  186. orderId: testOrder.id,
  187. totalAmount: 20000,
  188. description: '测试支付订单'
  189. },
  190. },
  191. {
  192. headers: {
  193. 'Authorization': `Bearer ${tokenWithoutOpenid}`
  194. }
  195. });
  196. expect(response.status).toBe(400);
  197. if (response.status === 400) {
  198. const result = await response.json();
  199. expect(result.message).toContain('用户未绑定微信小程序');
  200. }
  201. });
  202. });
  203. describe('POST /payment/callback - 支付回调', () => {
  204. it('应该成功处理支付成功回调', async () => {
  205. const timestamp = Math.floor(Date.now() / 1000).toString();
  206. const nonce = Math.random().toString(36).substring(2, 15);
  207. const callbackData = {
  208. id: 'EV-201802251122332345',
  209. create_time: '2018-06-08T10:34:56+08:00',
  210. event_type: 'TRANSACTION.SUCCESS',
  211. resource_type: 'encrypt-resource',
  212. resource: {
  213. algorithm: 'AEAD_AES_256_GCM',
  214. ciphertext: 'encrypted_data',
  215. nonce: 'random_nonce',
  216. associated_data: 'associated_data'
  217. },
  218. summary: 'payment_success'
  219. };
  220. const response = await client.payment.callback.$post({
  221. json: callbackData
  222. }, {
  223. headers: {
  224. 'wechatpay-timestamp': timestamp,
  225. 'wechatpay-nonce': nonce,
  226. 'wechatpay-signature': 'mock_signature_for_test',
  227. 'wechatpay-serial': process.env.WECHAT_PLATFORM_CERT_SERIAL_NO || ''
  228. }
  229. });
  230. expect(response.status).toBe(200);
  231. if (response.status === 200) {
  232. const result = await response.text();
  233. expect(result).toBe('SUCCESS');
  234. }
  235. });
  236. it('应该处理支付失败回调', async () => {
  237. const timestamp = Math.floor(Date.now() / 1000).toString();
  238. const nonce = Math.random().toString(36).substring(2, 15);
  239. const callbackData = {
  240. id: 'EV-201802251122332346',
  241. create_time: '2018-06-08T10:34:56+08:00',
  242. event_type: 'TRANSACTION.FAIL',
  243. resource_type: 'encrypt-resource',
  244. resource: {
  245. algorithm: 'AEAD_AES_256_GCM',
  246. ciphertext: 'encrypted_data',
  247. nonce: 'random_nonce',
  248. associated_data: 'associated_data'
  249. },
  250. summary: 'payment_failed'
  251. };
  252. const response = await client.payment.callback.$post({
  253. json: callbackData
  254. }, {
  255. headers: {
  256. 'wechatpay-timestamp': timestamp,
  257. 'wechatpay-nonce': nonce,
  258. 'wechatpay-signature': 'mock_signature_for_test',
  259. 'wechatpay-serial': process.env.WECHAT_PLATFORM_CERT_SERIAL_NO || ''
  260. }
  261. });
  262. expect(response.status).toBe(200);
  263. if (response.status === 200) {
  264. const result = await response.text();
  265. expect(result).toBe('SUCCESS');
  266. }
  267. });
  268. it('应该处理无效的回调数据', async () => {
  269. const response = await client.payment.callback.$post({
  270. json: { invalid: 'data' } as any
  271. }, {
  272. headers: {
  273. 'wechatpay-timestamp': '1622456896',
  274. 'wechatpay-nonce': 'random_nonce_string',
  275. 'wechatpay-signature': 'signature_data',
  276. 'wechatpay-serial': process.env.WECHAT_PLATFORM_CERT_SERIAL_NO || ''
  277. }
  278. });
  279. expect(response.status).toBe(400);
  280. });
  281. });
  282. describe('支付状态流转测试', () => {
  283. it('应该正确更新订单支付状态', async () => {
  284. // 创建支付
  285. const createResponse = await client.payment.$post({
  286. json: {
  287. orderId: testOrder.id,
  288. totalAmount: 20000,
  289. description: '测试支付订单'
  290. },
  291. },
  292. {
  293. headers: {
  294. 'Authorization': `Bearer ${testToken}`
  295. }
  296. });
  297. expect(createResponse.status).toBe(200);
  298. // 验证订单状态已更新为处理中
  299. const dataSource = await IntegrationTestDatabase.getDataSource();
  300. const orderRepository = dataSource.getRepository('Order');
  301. const updatedOrder = await orderRepository.findOne({
  302. where: { id: testOrder.id }
  303. });
  304. expect(updatedOrder?.paymentStatus).toBe(PaymentStatus.PROCESSING);
  305. });
  306. });
  307. describe('微信支付JSAPI参数生成测试', () => {
  308. it('应该生成正确的支付参数格式', async () => {
  309. const response = await client.payment.$post({
  310. json: {
  311. orderId: testOrder.id,
  312. totalAmount: 20000,
  313. description: '测试支付订单'
  314. },
  315. },
  316. {
  317. headers: {
  318. 'Authorization': `Bearer ${testToken}`
  319. }
  320. });
  321. expect(response.status).toBe(200);
  322. if (response.status === 200) {
  323. const result = await response.json();
  324. // 验证返回参数格式
  325. expect(result.timeStamp).toMatch(/^\d+$/); // 时间戳应该是数字字符串
  326. expect(result.nonceStr).toBeTruthy(); // 随机字符串应该存在
  327. expect(result.package).toContain('prepay_id=');
  328. expect(result.signType).toBe('RSA');
  329. expect(result.paySign).toBeTruthy(); // 签名应该存在
  330. }
  331. });
  332. });
  333. });