From 7506cb20eb77a4ac56cf90368ddc41dcc382e7b7 Mon Sep 17 00:00:00 2001 From: Anand Chowdhary Date: Mon, 2 Nov 2020 17:50:58 +0530 Subject: [PATCH] :sparkles: Handle Stripe webhook event --- src/modules/stripe/stripe-webhook.controller.ts | 7 +++---- src/modules/stripe/stripe.service.ts | 14 ++++++++++++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/modules/stripe/stripe-webhook.controller.ts b/src/modules/stripe/stripe-webhook.controller.ts index eaecd9571..8891f09ea 100644 --- a/src/modules/stripe/stripe-webhook.controller.ts +++ b/src/modules/stripe/stripe-webhook.controller.ts @@ -1,5 +1,4 @@ import { Body, Controller, Headers, Post } from '@nestjs/common'; -import Stripe from 'stripe'; import { Public } from '../auth/public.decorator'; import { StripeService } from './stripe.service'; @@ -11,8 +10,8 @@ export class StripeWebhookController { @Post() async handleWebhook( @Headers('stripe-signature') signature: string, - @Body() event: Stripe.Event, - ): Promise { - return this.stripeService.handleWebhook(signature, event); + @Body() raw: Buffer, + ): Promise<{ received: true }> { + return this.stripeService.handleWebhook(signature, raw); } } diff --git a/src/modules/stripe/stripe.service.ts b/src/modules/stripe/stripe.service.ts index 6bde5c73a..c49264869 100644 --- a/src/modules/stripe/stripe.service.ts +++ b/src/modules/stripe/stripe.service.ts @@ -1,6 +1,7 @@ import { BadRequestException, Injectable, + Logger, NotFoundException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; @@ -10,6 +11,7 @@ import { PrismaService } from '../prisma/prisma.service'; @Injectable() export class StripeService { stripe: Stripe; + logger = new Logger('stripe'); constructor( private configService: ConfigService, @@ -209,12 +211,20 @@ export class StripeService { }); } - async handleWebhook(signature: string, payload: any) { - this.stripe.webhooks.constructEvent( + async handleWebhook( + signature: string, + payload: Buffer, + ): Promise<{ received: true }> { + const event = this.stripe.webhooks.constructEvent( payload, signature, this.configService.get('payments.stripeEndpointSecret') ?? '', ); + switch (event.type) { + default: + this.logger.warn(`Unhandled event type ${event.type}`); + } + return { received: true }; } private list(result: Stripe.Response>) {