Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: webhook signing Nestjs #1895

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions examples/webhook-signing/nestjs/app.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// create payment controller

import {
Controller,
Post,
Headers,
Get,
RawBodyRequest,
Req,
Res,
} from '@nestjs/common'
import { STRIPE_CLIENT, Stripe } from '@sggc/stripe-nestjs'
import { Inject } from '@nestjs/common'
import { Request,Response } from 'express'

@Controller()
export class AppController {
constructor(
@Inject(STRIPE_CLIENT) private client: Stripe,
private config: ConfigService
) {}

@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.json({received: true});
}
}
37 changes: 37 additions & 0 deletions examples/webhook-signing/nestjs/app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Module } from "@nestjs/common";
import { StripeModule } from '@sggc/stripe-nestjs'
import { ConfigService,ConfigModule } from '@nestjs/config'
import { Config } from "./config";
import { AppController } from "./app.controller";

export const configuration = async (): Promise<Config> => {
const { config } = <{ config: Config }> await import(`${__dirname}/config`);
return config;
};

@Module({
controllers: [AppController],
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [configuration],
envFilePath: `.env`,
}),
StripeModule.forRootAsync({
isGlobal: true,
inject: [ConfigService],
createOptions: async (config: ConfigService) => {
const apiKey = config.get<string>('Stripe.api_secret') // secret for api call
if (!apiKey) {
throw new Error('STRIPE_API_SECRET is not defined')
}
const apiVersion = config.get('Stripe.version') || '2022-11-15'
return {
apiKey,
apiVersion,
}
},
}),
],
})
export class AppModule {}
16 changes: 16 additions & 0 deletions examples/webhook-signing/nestjs/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const config: {
Stripe: {
publishable_key: string
api_secret: string
webhook_secret: string
}
} = {
Stripe: {
publishable_key: process.env.STRIPE_SECRET_KEY || '',
api_secret: process.env.STRIPE_WEBHOOK_SECRET || '',
webhook_secret: process.env.STRIPE_WEBHOOK_SECRET || '',
}
}
export type Config = typeof config;


17 changes: 17 additions & 0 deletions examples/webhook-signing/nestjs/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/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(3000, () => {
alikarimii marked this conversation as resolved.
Show resolved Hide resolved
console.log(`Webhook endpoint available at http://localhost:3000/webhooks`);
});
}
bootstrap();
31 changes: 31 additions & 0 deletions examples/webhook-signing/nestjs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"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",
"@sggc/stripe-nestjs": "^1.0.7",
alikarimii marked this conversation as resolved.
Show resolved Hide resolved
"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"
}
}
alikarimii marked this conversation as resolved.
Show resolved Hide resolved
Empty file.
122 changes: 122 additions & 0 deletions examples/webhook-signing/nestjs/test/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
#!/usr/bin/env -S npm run-script run
alikarimii marked this conversation as resolved.
Show resolved Hide resolved
/* eslint-disable prettier/prettier */

import env from 'dotenv';
import * as fs from 'fs';
import * as child_process from 'child_process';
import Stripe from 'stripe';
import * as http from 'http';
import {exit} from 'process';

const path = process.argv[3];

if (!path || !fs.statSync(path)) {
console.error('Please specify the test application path');
process.exit(1);
}

child_process.execSync('npm install', {
cwd: path,
});

const server = child_process.exec('./main.ts', {
cwd: path,
});
server.stdout.pipe(process.stdout);
server.stderr.pipe(process.stdout);

const serverReady = new Promise<string>((resolve, reject) => {
server.stdout.on('data', (data) => {
const match = /Webhook endpoint available at (.*)/gm.exec(data);
if (match) {
resolve(match[1]);
}
});
server.on('error', (m) => reject(m));
server.on('exit', (m) => reject(m));
});

env.config({
path: `${path}/.env`,
});

const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2023-08-16',
});

const payload = Buffer.from(
JSON.stringify(
{
id: 'evt_123',
type: 'charge.succeeded',
object: 'event',
data: {
object: {
id: 'ch_123',
},
},
},
null,
2
)
);

const signatureHeader = stripe.webhooks.generateTestHeaderString({
payload: payload.toString(),
secret: webhookSecret,
});

const sendTestRequest = async (url: string): Promise<string> => {
return new Promise<string>((resolve, reject) => {
const request = http.request(
url,
{
method: 'POST',
headers: {
'Stripe-Signature': signatureHeader,
'Content-Length': payload.length,
'Content-Type': 'application/json',
},
},
(res) => {
const chunks = [];
res.on('data', (d) => {
chunks.push(d);
});
res.on('end', () => {
resolve(Buffer.concat(chunks).toString());
});
res.on('error', (e) => reject(e));

if (res.statusCode != 200) {
reject(new Error('Non 200 status code'));
}
}
);
request.write(payload);
request.end();
});
};

(async () => {
try {
console.log(`Waiting for server to start`);
const url = await serverReady;
console.log(`Server ready at ${url}`);
const response = await sendTestRequest(url);
if (response != '{"received":true}') {
throw new Error(`Unexpected response ${response}`);
}
console.log('Test succeeded');
process.exit(0);
} catch (e) {
console.error(e);
throw e;
} finally {
server.kill();
}
})().catch((e) => {
console.error(e);
process.exit(1);
});