create.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { z } from 'zod';
  3. import { AppDataSource } from '@d8d/shared-utils';
  4. import { authMiddleware } from '@d8d/auth-module';
  5. import { AuthContext } from '@d8d/shared-types';
  6. import { PaymentService } from '../../services/payment.service.js';
  7. import { PaymentCreateRequestSchema, PaymentCreateResponseSchema } from '../../schemas/payment.schema.js';
  8. // 支付创建路由定义
  9. const createPaymentRoute = createRoute({
  10. method: 'post',
  11. path: '/',
  12. middleware: [authMiddleware],
  13. request: {
  14. body: {
  15. content: {
  16. 'application/json': { schema: PaymentCreateRequestSchema }
  17. }
  18. }
  19. },
  20. responses: {
  21. 200: {
  22. description: '支付创建成功',
  23. content: { 'application/json': { schema: PaymentCreateResponseSchema } }
  24. },
  25. 400: {
  26. description: '参数错误',
  27. content: { 'application/json': { schema: z.object({ message: z.string() }) } }
  28. },
  29. 401: {
  30. description: '未授权',
  31. content: { 'application/json': { schema: z.object({ message: z.string() }) } }
  32. },
  33. 500: {
  34. description: '服务器错误',
  35. content: { 'application/json': { schema: z.object({ message: z.string() }) } }
  36. }
  37. }
  38. });
  39. const app = new OpenAPIHono<AuthContext>()
  40. .openapi(createPaymentRoute, async (c) => {
  41. try {
  42. const paymentData = c.req.valid('json');
  43. const user = c.get('user');
  44. // 检查用户是否有openid(小程序用户必需)
  45. if (!user?.openid) {
  46. return c.json({
  47. message: '用户未绑定微信小程序,无法进行支付'
  48. }, 400);
  49. }
  50. // 创建支付服务实例
  51. const paymentService = new PaymentService(AppDataSource);
  52. // 创建支付订单,从认证用户中获取openid
  53. const paymentResult = await paymentService.createPayment(
  54. paymentData.orderId,
  55. user.id,
  56. paymentData.totalAmount,
  57. paymentData.description,
  58. user.openid
  59. );
  60. return c.json(paymentResult, 200);
  61. } catch (error) {
  62. console.error('支付创建失败:', error);
  63. return c.json({
  64. message: error instanceof Error ? error.message : '支付创建失败'
  65. }, 500);
  66. }
  67. });
  68. export default app;