| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { z } from 'zod';
- import { AppDataSource } from '@d8d/shared-utils';
- import { authMiddleware } from '@d8d/auth-module';
- import { AuthContext } from '@d8d/shared-types';
- import { PaymentService } from '../../services/payment.service.js';
- import { PaymentCreateRequestSchema, PaymentCreateResponseSchema } from '../../schemas/payment.schema.js';
- // 支付创建路由定义
- const createPaymentRoute = createRoute({
- method: 'post',
- path: '/',
- middleware: [authMiddleware],
- request: {
- body: {
- content: {
- 'application/json': { schema: PaymentCreateRequestSchema }
- }
- }
- },
- responses: {
- 200: {
- description: '支付创建成功',
- content: { 'application/json': { schema: PaymentCreateResponseSchema } }
- },
- 400: {
- description: '参数错误',
- content: { 'application/json': { schema: z.object({ message: z.string() }) } }
- },
- 401: {
- description: '未授权',
- content: { 'application/json': { schema: z.object({ message: z.string() }) } }
- },
- 500: {
- description: '服务器错误',
- content: { 'application/json': { schema: z.object({ message: z.string() }) } }
- }
- }
- });
- const app = new OpenAPIHono<AuthContext>()
- .openapi(createPaymentRoute, async (c) => {
- try {
- const paymentData = c.req.valid('json');
- const user = c.get('user');
- // 检查用户是否有openid(小程序用户必需)
- if (!user?.openid) {
- return c.json({
- message: '用户未绑定微信小程序,无法进行支付'
- }, 400);
- }
- // 创建支付服务实例
- const paymentService = new PaymentService(AppDataSource);
- // 创建支付订单,从认证用户中获取openid
- const paymentResult = await paymentService.createPayment(
- paymentData.orderId,
- user.id,
- paymentData.totalAmount,
- paymentData.description,
- user.openid
- );
- return c.json(paymentResult, 200);
- } catch (error) {
- console.error('支付创建失败:', error);
- return c.json({
- message: error instanceof Error ? error.message : '支付创建失败'
- }, 500);
- }
- });
- export default app;
|