-
Notifications
You must be signed in to change notification settings - Fork 755
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: webhook signing Nestjs (#1895)
- Loading branch information
1 parent
02cdfc5
commit 5bfdaca
Showing
7 changed files
with
161 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 || '', | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters