npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@golevelup/nestjs-stripe

v0.8.0

Published

Badass utilities for integrating stripe and NestJS

Downloads

28,454

Readme

@golevelup/nestjs-stripe

Interacting with the Stripe API or consuming Stripe webhooks in your NestJS applications is now easy as pie 🥧

Features

  • 💉 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 routes incoming events to them

  • 🧭 Route events to logical services easily simply by providing the Stripe webhook event type

Getting Started

Install

NPM

  • Install the package along with the stripe peer dependency

    npm install --save @golevelup/nestjs-stripe stripe

YARN

  • Install the package using yarn with the stripe peer dependency

    yarn add @golevelup/nestjs-stripe stripe

Import

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 Click to reveal button.

account - The webhook secret registered in the Stripe Dashboard for events on your accounts
account_test - The webhook secret registered in the Stripe Dashboard for events on your accounts in test mode
connect - The webhook secret registered in the Stripe Dashboard for events on Connected accounts connect_test - The webhook secret registered in the Stripe Dashboard for events on Connected accounts in test mode

import { StripeModule } from '@golevelup/nestjs-stripe';

@Module({
  imports: [
    StripeModule.forRoot(StripeModule, {
      apiKey: '123',
      webhookConfig: {
        stripeSecrets: {
          account: 'abc',
          accountTest: 'cba',
          connect: 'foo',
          connectTest: 'bar',
        },
      },
    }),
  ],
})
export class AppModule {
  // ...
}

Configuration

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.

Injectable Providers

The module exposes two injectable providers with accompanying decorators for your convenience. These can be provided to the constructors of controllers and other providers:

 // injects the instantiated Stripe client which can be used to make API calls
@InjectStripeClient() stripeClient: Stripe
// injects the module configuration
@InjectStripeModuleConfig() config: StripeModuleConfig

Consuming Webhooks

Included API Endpoint

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.

⚠️ Configure Raw Request Body Handling

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.

// main.ts
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
  rawBody: true,
});

You can then manually set up bodyProperty to use rawBody:

StripeModule.forRoot(StripeModule, {
  apiKey: '',
  webhookConfig: {
    stripeWebhookSecret: '',
    requestBodyProperty: 'rawBody', // <-- Set to 'rawBody'
  },
});

Decorate Methods For Processing Webhook Events

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.

@Injectable()
class PaymentCreatedService {
  @StripeWebhookHandler('payment_intent.created')
  handlePaymentIntentCreated(evt: StripeEvent) {
    // execute your custom business logic
  }
}

Webhook Controller Decorators

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.

StripeModule.forRoot(StripeModule, {
  apiKey: '123',
  webhookConfig: {
    stripeWebhookSecret: 'super-secret',
    decorators: [SkipThrottle()],
  },
}),

Usage with Interceptors, Guards and Filters

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':

@Injectable()
class ExampleInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler<any>) {
    const contextType = context.getType<'http' | 'stripe_webhook'>();

    // Do nothing if this is a Stripe webhook event
    if (contextType === 'stripe_webhook') {
      return next.handle();
    }

    // Execute custom interceptor logic for HTTP request/response
    return next.handle();
  }
}

Configure Webhooks in the Stripe Dashboard

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.

Contribute

Contributions welcome! Read the contribution guidelines first.

License

MIT License