I am using stripe api with webhooks and also nest js with a next js frontend. How can I…
- User
I am using stripe api with webhooks and also nest js with a next js frontend. How can I make it so that when it a checkout is completed the user is directed to the success page and the booking reference generated in the backend is passed to the frontend to display? I also want to send conformation emails to the user when they create a booking
- Assistant
To achieve this, you can follow the below steps:
-
When the checkout is completed, Stripe will send a webhook to your backend. You can listen to this webhook in your Nest JS backend and generate a booking reference.
-
After generating the booking reference, you can include it in the redirect URL to the success page so that it's available on the frontend. For example, your redirect URL can look like this:
https://example.com/success?bookingRef=ABC123 -
In your Next JS frontend, you can extract the booking reference from the URL using the
queryobject and display it on the success page. -
To send confirmation emails to the user, you can use a third-party email service like SendGrid or Mailgun. In your Nest JS backend, after generating the booking reference, you can trigger the sending of the confirmation email to the user's email address. You can include the booking reference in the email so that the user has a record of it.
With the above steps, your users will be directed to the success page after checkout, and the booking reference will be displayed. Additionally, they will receive a confirmation email with the booking reference for their records.
-
- User
So I have this webhook @Controller('webhook') export class StripeWebhookController { constructor(private user: UsersService, private booking: BookingsService) {} @Post() async handleStripeWebhook( @Req() req: RawBodyRequest, @Res() res: Response, ): Promise { const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { apiVersion: '2022-11-15', });
const event = stripe.webhooks.constructEvent( req.rawBody, req.headers['stripe-signature'], process.env.STRIPE_WEBHOOK_SECRET, ); try { if (event.type === 'checkout.session.completed') { const session = event.data.object as Stripe.Checkout.Session; const paymentIntentId = session.payment_intent; const { vanVariationId, extras, fromDate, toDate, vanId } = JSON.parse( session.metadata.bookingData, ); const booking = await this.booking.create({ fromDate, toDate, vanId, vanVariationId, extras, stripePaymentIntentId: paymentIntentId as string, user: { email: session.customer_details.email, name: session.customer_details.name, phone: session.customer_details.phone, }, cost: session.amount_total / 100, }); return booking; } } catch (error) { // Handle any errors that occur during webhook processing console.error('Error processing webhook:', error); } // Respond with a 200 status to acknowledge receipt of the webhook event res.status(200).send('Webhook Received'); - Assistant
You can add a query parameter to the redirect URL with the booking ID or reference. For example, if you have a booking ID generated after the checkout is completed, you can modify the redirect URL to something like this:
https://example.com/success?bookingId=123456In your Nest JS controller that handles the Stripe webhook, you can return a redirect response with this URL after creating the booking in the database:
return res.redirect(`https://example.com/success?bookingId=${booking.id}`);This will redirect the user to the success page with the booking ID as a query parameter. In your Next.js frontend, you can extract the booking ID from the
router.queryobject and use it to display the booking information on the success page. - User
When you create a checkout session you have to give it a success url, so this overrides the res.redirect in the webhook
- Assistant
That is correct, the
success_urlthat you provide when creating the checkout session overrides theres.redirectin your Stripe webhook controller. However, you can still pass additional query parameters to thesuccess_urlby including them in the metadata of the checkout session.For example, you could include the booking ID or reference in the metadata of the checkout session, like so:
const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items: [...], mode: 'payment', metadata: { bookingId: booking.id // or booking reference }, success_url: 'https://example.com/success', cancel_url: 'https://example.com/cancel', });Then, in your Next.js frontend, you can extract the booking ID or reference from the metadata by accessing the object. To do this, you can modify your success page to use the or Next.js functions to fetch the booking data based on the booking ID or reference retrieved from the object.