Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
✨ Handle Stripe webhook event
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Nov 2, 2020
1 parent c0b928a commit 7506cb2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
7 changes: 3 additions & 4 deletions src/modules/stripe/stripe-webhook.controller.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -11,8 +10,8 @@ export class StripeWebhookController {
@Post()
async handleWebhook(
@Headers('stripe-signature') signature: string,
@Body() event: Stripe.Event,
): Promise<void> {
return this.stripeService.handleWebhook(signature, event);
@Body() raw: Buffer,
): Promise<{ received: true }> {
return this.stripeService.handleWebhook(signature, raw);
}
}
14 changes: 12 additions & 2 deletions src/modules/stripe/stripe.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
BadRequestException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
Expand All @@ -10,6 +11,7 @@ import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class StripeService {
stripe: Stripe;
logger = new Logger('stripe');

constructor(
private configService: ConfigService,
Expand Down Expand Up @@ -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<string>('payments.stripeEndpointSecret') ?? '',
);
switch (event.type) {
default:
this.logger.warn(`Unhandled event type ${event.type}`);
}
return { received: true };
}

private list<T>(result: Stripe.Response<Stripe.ApiList<T>>) {
Expand Down

0 comments on commit 7506cb2

Please sign in to comment.