Badass utilities for integrating stripe and NestJS
npm install @golevelup/nestjs-stripeInteracting with the Stripe API or consuming Stripe webhooks in your NestJS applications is now easy as pie 🥧
::: code-group
``bash [npm]`
npm install ---save @golevelup/nestjs-stripe stripe
`bash [yarn]`
yarn add @golevelup/nestjs-stripe stripe
`bash [pnpm]`
pnpm add @golevelup/nestjs-stripe stripe
:::
- 💉 Injectable Stripe client for interacting with the Stripe API in Controllers and Providers
- 🎉 Optionally exposes an API endpoint from your NestJS application at to be used for webhook event processing from Stripe. Defaults to /stripe/webhook but can be easily configured
- 🔒 Automatically validates that the event payload was actually sent from Stripe using the configured webhook signing secret
- 🕵️ Discovers providers from your application decorated with StripeWebhookHandler and StripeThinWebhookHandler and routes incoming events to them
- 🧭 Route events to logical services easily simply by providing the Stripe webhook event type
- ⚡ Support for both traditional snapshot events and Stripe's new v2 thin events
Import and add StripeModule to the imports section of the consuming module (most likely AppModule). Your Stripe API key is required, and you can optionally include a webhook configuration if you plan on consuming Stripe webhook events inside your app.
Stripe secrets you can get from your Dashboard's Webhooks settings. Select an endpoint that you want to obtain the secret for, then click the Reveal link below "Signing secret".
Snapshot Events (Traditional Webhooks):
account - The webhook secret registered in the Stripe Dashboard for events on your accountsaccountTest - The webhook secret registered in the Stripe Dashboard for events on your accounts in test modeconnect - The webhook secret registered in the Stripe Dashboard for events on Connected accountsconnectTest - The webhook secret registered in the Stripe Dashboard for events on Connected accounts in test mode
Thin Events (V2 Webhooks - Optional):
stripeThinSecrets - Separate secrets for Stripe's v2 thin events (only required if using @StripeThinWebhookHandler)
`typescript
import { StripeModule } from '@golevelup/nestjs-stripe';
@Module({
imports: [
StripeModule.forRoot({
apiKey: 'sk_*',
webhookConfig: {
// Snapshot event secrets
stripeSecrets: {
account: 'whsec_*',
accountTest: 'whsec_*',
connect: 'whsec_*',
connectTest: 'whsec_*',
},
// Thin event secrets (optional)
stripeThinSecrets: {
account: 'whsec_*',
accountTest: 'whsec_*',
connect: 'whsec_*',
connectTest: 'whsec_*',
},
},
}),
],
})
export class AppModule {
// ...
}
`
The Stripe Module supports both the forRoot and forRootAsync patterns for configuration, so you can easily retrieve the necessary config values from a ConfigService or other provider.
The module exposes two injectable providers with accompanying decorators for your convenience. These can be provided to the constructors of controllers and other providers:
`typescript`
// injects the instantiated Stripe client which can be used to make API calls
@InjectStripeClient() stripeClient: Stripe
`typescript`
// injects the module configuration
@InjectStripeModuleConfig() config: StripeModuleConfig
This module will automatically add a new API endpoint to your NestJS application for processing webhooks. By default, the route for this endpoint will be stripe/webhook but you can modify this to use a different prefix using the controllerPrefix property of the webhookConfig when importing the module.
If you would like your NestJS application to be able to process incoming webhooks, it is essential that Stripe has access to the raw request payload.
By default, NestJS is configured to use JSON body parsing middleware which will transform the request before it can be validated by the Stripe library.
You can choose to pass the raw request body into the context of each Request,
which will not cause side effects to any of your existing project's architectural design and other APIs.
`typescript`
// main.ts
const app = await NestFactory.create
rawBody: true,
});
You can then manually set up bodyProperty to use rawBody:
`typescript`
StripeModule.forRoot({
apiKey: 'sk_*',
webhookConfig: {
stripeSecrets: { ... },
requestBodyProperty: 'rawBody', // <-- Set to 'rawBody'
},
});
Exposing provider/service methods to be used for processing Stripe events is easy! Simply use the provided decorator and indicate the event type that the handler should receive.
Review the Stripe documentation for more information about the types of events available.
#### Snapshot Events (Traditional)
Use @StripeWebhookHandler for traditional Stripe webhook events. These include the full event object in the payload.
`typescript`
@Injectable()
class PaymentCreatedService {
@StripeWebhookHandler('payment_intent.created')
handlePaymentIntentCreated(evt: Stripe.PaymentIntentPaymentCreatedEvent) {
// execute your custom business logic
}
}
Webhook URL: https://your-domain.com/stripe/webhook
#### Thin Events (V2)
Use @StripeThinWebhookHandler for Stripe's v2 thin events. These are lightweight events that only include metadata - you'll need to fetch the full object separately.
`typescript
@Injectable()
class BillingService {
constructor(@InjectStripeClient() private stripe: Stripe) {}
@StripeThinWebhookHandler('v1.billing.meter.error_report_triggered')
async handleBillingMeterError(
evt: Stripe.Events.V1BillingMeterErrorReportTriggeredEventNotification,
) {
// Thin events require fetching the full object
const meter = await evt.fetchRelatedObject();
// execute your custom business logic
}
}
`
Webhook URL: https://your-domain.com/stripe/webhook?mode=thin
#### Wildcard Handlers
You can use '*' to handle all events of a specific type:
`typescript
@Injectable()
class WebhookLogger {
@StripeWebhookHandler('*')
logAllSnapshotEvents(evt: Stripe.Event) {
console.log('Received snapshot event:', evt.type);
}
@StripeThinWebhookHandler('*')
logAllThinEvents(evt: Stripe.V2.Core.Event) {
console.log('Received thin event:', evt.type);
}
}
`
You can also pass any class decorator to the decorators property of the webhookConfig object as a part of the module configuration. This could be used in situations like when using the @nestjs/throttler package and needing to apply the @SkipThrottle() decorator, or when you have a global guard but need to skip routes with certain metadata.
`typescript`
StripeModule.forRoot({
apiKey: 'sk_*',
webhookConfig: {
stripeSecrets: { ... },
decorators: [SkipThrottle()],
},
}),
This library is built using an underlying NestJS concept called External Contexts which allows for methods to be included in the NestJS lifecycle. This means that Guards, Interceptors and Filters (collectively known as "enhancers") can be used in conjunction with Stripe webhook handlers. However, this can have unwanted/unintended consequences if you are using _Global_ enhancers in your application as these will also apply to all Stripe webhook handlers. If you were previously expecting all contexts to be regular HTTP contexts, you may need to add conditional logic to prevent your enhancers from applying to Stripe webhook handlers.
You can identify Stripe webhook contexts by their context type, 'stripe_webhook':
`typescript
import { STRIPE_WEBHOOK_CONTEXT_TYPE } from '@golevelup/nestjs-stripe';
@Injectable()
class ExampleInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler
const contextType = context.getType<
'http' | typeof STRIPE_WEBHOOK_CONTEXT_TYPE
>();
// Do nothing if this is a Stripe webhook event
if (contextType === STRIPE_WEBHOOK_CONTEXT_TYPE) {
return next.handle();
}
// Execute custom interceptor logic for HTTP request/response
return next.handle();
}
}
``
Follow the instructions from the Stripe Documentation for remaining integration steps such as testing your integration with the CLI before you go live and properly configuring the endpoint from the Stripe dashboard so that the correct events are sent to your NestJS app.