angularnestjsstripe-paymentsnestjs-typeorm

When to add data to DB after Stripe payment


I am having issue with adding new order data to my database after succesfull payment using Stripe.

This is my Angular code:

HTML:

<button mat-raised-button color="primary" (click)="checkout()">Checkout</button>

TypeScript:

  async checkout() {

    const cartProducts = this.getArrFromLocalStorage()

    this.api.checkout(cartProducts).subscribe({
      next: async (session: any) => {
        const stripe = await loadStripe(environment.stripeConfig.publishable_key);
        stripe?.redirectToCheckout({
          sessionId: session.id
        })
      },
      error: (err) => {
        alert(err)
      }
    })
  }

and this is my NestJS code:

payment.controller.ts:

@Controller('payment')
export class PaymentController {

  constructor(private paymentService: PaymentService) {
  }


  @Post()
  async createPayment(@Body() data: CartItem[]){
    return this.paymentService.processPayment(data)
  }

}

payment.service.ts


    const processedCartItems: ProcessedCartItem[] = await this.getProcessedCartItems(cartItems)
    return this.createSession(processedCartItems)

  }
  
  async createSession(processedCartItems: ProcessedCartItem[]){

    return this.stripe.checkout.sessions.create({
      line_items: processedCartItems.map(item => ({
        price_data: {
          currency: 'usd',
          unit_amount: item.price * 100,
          product_data: {
            name: item.name,
            images: ['https://material.angular.io/assets/img/examples/shiba1.jpg'] // test img
          },
        },
        quantity: item.quantity,
      })),
      mode: 'payment',
      success_url: process.env.STRIPE_SUCCESS_URL,
      cancel_url: process.env.STRIPE_CANCEL_URL,
    });
  }

How do i add data after successfull payment? what should i do and how to deal with this? Thanks in advance!


Solution

  • I recommend a couple of things here: