Skip to content

Commit

Permalink
feat: webhook signing Nestjs (#1895)
Browse files Browse the repository at this point in the history
  • Loading branch information
alikarimii authored Sep 11, 2023
1 parent 02cdfc5 commit 5bfdaca
Show file tree
Hide file tree
Showing 7 changed files with 161 additions and 1 deletion.
72 changes: 72 additions & 0 deletions examples/webhook-signing/nestjs/app.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// create payment controller

import {
Controller,
Post,
Headers,
Get,
RawBodyRequest,
Req,
Res,
Injectable,
Inject,
} from '@nestjs/common';
import {Request, Response} from 'express';
import Stripe from 'stripe';
import {ConfigService} from '@nestjs/config';

@Controller()
export class AppController {
private readonly client: Stripe;
constructor(@Inject(ConfigService) private readonly config: ConfigService) {
this.client = new Stripe(this.config.get('Stripe.secret_key'), {
apiVersion: '2022-11-15',
typescript: true,
});
}

@Get('/')
async index(): Promise<string> {
return 'ok';
}

@Post('/webhooks')
async webhooks(
@Headers('stripe-signature') sig: string,
@Req() req: RawBodyRequest<Request>,
@Res() res: Response
) {
let event: Stripe.Event;

try {
event = this.client.webhooks.constructEvent(
req.rawBody,
sig,
this.config.get('Stripe.webhook_secret')
);
} catch (err) {
// On error, log and return the error message
console.log(`❌ Error message: ${err.message}`);
res.status(400).send(`Webhook Error: ${err.message}`);
return;
}

// Successfully constructed event
console.log('✅ Success:', event.id);

// Cast event data to Stripe object
if (event.type === 'payment_intent.succeeded') {
const stripeObject: Stripe.PaymentIntent = event.data
.object as Stripe.PaymentIntent;
console.log(`💰 PaymentIntent status: ${stripeObject.status}`);
} else if (event.type === 'charge.succeeded') {
const charge = event.data.object as Stripe.Charge;
console.log(`💵 Charge id: ${charge.id}`);
} else {
console.warn(`🤷‍♀️ Unhandled event type: ${event.type}`);
}

// Return a response to acknowledge receipt of the event
res.status(200).json({received: true});
}
}
16 changes: 16 additions & 0 deletions examples/webhook-signing/nestjs/app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {Module} from '@nestjs/common';
import {ConfigModule} from '@nestjs/config';
import {config} from './config';
import {AppController} from './app.controller';

@Module({
controllers: [AppController],
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [config],
envFilePath: `.env`,
}),
],
})
export class AppModule {}
13 changes: 13 additions & 0 deletions examples/webhook-signing/nestjs/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
type Config = {
Stripe: {
secret_key: string;
webhook_secret: string;
};
};

export const config = (): Config => ({
Stripe: {
secret_key: process.env.STRIPE_SECRET_KEY || '',
webhook_secret: process.env.STRIPE_WEBHOOK_SECRET || '',
},
});
18 changes: 18 additions & 0 deletions examples/webhook-signing/nestjs/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/usr/bin/env -S npm run-script run

import {NestFactory} from '@nestjs/core';
import {INestApplication} from '@nestjs/common';
import {AppModule} from './app.module';

async function bootstrap() {
const app = await NestFactory.create<INestApplication>(AppModule, {
rawBody: true,
});
app.enableCors({
origin: '*',
});

await app.listen(0);
console.log(`Webhook endpoint available at ${await app.getUrl()}/webhooks`);
}
bootstrap();
30 changes: 30 additions & 0 deletions examples/webhook-signing/nestjs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "webhook-signing-example-nestjs",
"version": "1.0.0",
"description": "Nestjs webhook parsing sample",
"repository": {},
"main": "./main.ts",
"scripts": {
"run": "ts-node-transpile-only ./main.ts",
"prepare": "../prepare.sh"
},
"author": "Ali karimi",
"license": "ISC",
"dependencies": {
"@nestjs/common": "^10.2.1",
"@nestjs/config": "^3.0.0",
"@nestjs/core": "^10.2.1",
"dotenv": "^16.3.1",
"@nestjs/platform-express": "^10.2.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1",
"stripe": "^12.18.0"
},
"devDependencies": {
"eslint": "^8.33.0",
"@types/node": "^20.5.4",
"@types/express": "^4.17.17",
"typescript": "^5.2.2",
"ts-node": "^10.9.1"
}
}
4 changes: 3 additions & 1 deletion examples/webhook-signing/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

/* Advanced Options */
/* Disallow inconsistently-cased references to the same file. */
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,

"experimentalDecorators": true,
}
}
9 changes: 9 additions & 0 deletions test/Integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,13 @@ describe('Integration test', function() {
});

it('Webhook sample deno', () => runWebhookTest('deno'));

it('Webhook sample nestjs', function() {
// Next.js supports Node.js >=16
if (nodeVersion < 16) {
this.skip();
}

runWebhookTest('nestjs');
});
});

0 comments on commit 5bfdaca

Please sign in to comment.