import { Body, Controller, Get, HttpException, HttpStatus, Param, Post, Req, Res, UseGuards } from '@nestjs/common'; import { Request, Response } from 'express'; import { OptionalAuthGuard } from 'src/jwt-auth/optional-auth.guard'; import { Checkout } from 'src/models/main.model'; import Stripe from 'stripe'; import { PaymentService } from './payment.service'; @Controller('payment') export class PaymentController { constructor(private readonly paymentService: PaymentService) {} // @Post() // async createSubscription(@Body() subscriptionData: any) { // return this.paymentService.createSubscription(subscriptionData); // } // @UseGuards(AdminAuthGuard) // @Get('user/all') // async getAllStripeCustomer(): Promise { // return await this.paymentService.getAllStripeCustomer(); // } // @UseGuards(AdminAuthGuard) // @Get('subscription/all') // async getAllStripeSubscriptions(): Promise { // return await this.paymentService.getAllStripeSubscriptions(); // } // @UseGuards(AdminAuthGuard) // @Get('paymentmethod/:email') // async getStripePaymentMethods(@Param('email') email: string): Promise { // return await this.paymentService.getStripePaymentMethod(email); // } @UseGuards(OptionalAuthGuard) @Post('create-checkout-session') async createCheckoutSession(@Body() checkout: Checkout) { return await this.paymentService.createCheckoutSession(checkout); } @Post('webhook') async handleWebhook(@Req() req: Request, @Res() res: Response): Promise { const signature = req.headers['stripe-signature'] as string; try { // Konvertieren Sie den req.body Buffer in einen lesbaren String const payload = req.body instanceof Buffer ? req.body.toString('utf8') : req.body; const event = await this.paymentService.constructEvent(payload, signature); // const event = await this.paymentService.constructEvent(req.body, signature); if (event.type === 'checkout.session.completed') { await this.paymentService.handleCheckoutSessionCompleted(event.data.object as Stripe.Checkout.Session); } res.status(200).send('Webhook received'); } catch (error) { console.error(`Webhook Error: ${error.message}`); throw new HttpException('Webhook Error', HttpStatus.BAD_REQUEST); } } @UseGuards(OptionalAuthGuard) @Get('subscriptions/:email') async findSubscriptionsById(@Param('email') email: string): Promise { return await this.paymentService.getSubscription(email); } /** * Endpoint zum Löschen eines Stripe-Kunden. * Beispiel: DELETE /stripe/customer/cus_12345 */ // @UseGuards(AdminAuthGuard) // @Delete('customer/:id') // @HttpCode(HttpStatus.NO_CONTENT) // async deleteCustomer(@Param('id') customerId: string): Promise { // await this.paymentService.deleteCustomerCompletely(customerId); // } }