如何在NestJS中添加对Stripe的WebHook验证详解

 更新时间:2023年08月08日 10:03:56   作者:阿兵  
这篇文章主要为大家介绍了如何在NestJS中添加对Stripe的WebHook验证详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

背景介绍

Nest 是一个用于构建高效,可扩展的NodeJS 服务器端应用程序的框架。它使用渐进式JavaScript, 内置并完全支持TypeScript, 但仍然允许开发人员使用纯JavaScript 编写代码。并结合了OOP(面向对象编程),FP(函数式编程)和 FRP(函数式响应编程)的元素。

Stripe 是一家美国金融服务和软件即服务公司,总部位于美国加利福尼亚州旧金山。主要提供用于电子商务网站和移动应用程序的支付处理软件和应用程序编程接口。2020年8月4日,《苏州高新区 · 2020胡润全球独角兽榜》发布,Stripe 排名第5位。

注:接下来的内容需要有NodeJS 及NestJS 的使用经验,如果没有需要另外学习如何使用。

代码实现

1. 去除自带的Http Body Parser.

因为Nest 默认会将所有请求的结果在内部直接转换成JavaScript 对象,这在一般情况下是很方便的,但如果我们要对响应的内容进行自定义的验证的话就会有问题了,所以我们要先替换成自定义的。

首先,在根入口启动应用时传入参数禁用掉自带的Parser.

import {NestFactory} from '@nestjs/core';
import {ExpressAdapter, NestExpressApplication} from '@nestjs/platform-express';
// 应用根
import {AppModule} from '@app/app/app.module';
// 禁用bodyParser
const app = await NestFactory.create<NestExpressApplication>(
  AppModule,
  new ExpressAdapter(),
  {cors: true, bodyParser: false},
);

2. Parser 中间件

然后定义三个不同的中间件:

  • 给Stripe 用的Parser
// raw-body.middleware.ts
import {Injectable, NestMiddleware} from '@nestjs/common';
import {Request, Response} from 'express';
import * as bodyParser from 'body-parser';
@Injectable()
export class RawBodyMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: () => any) {
    bodyParser.raw({type: '*/*'})(req, res, next);
  }
}
// raw-body-parser.middleware.ts
import {Injectable, NestMiddleware} from '@nestjs/common';
import {Request, Response} from 'express';
@Injectable()
export class RawBodyParserMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: () => any) {
    req['rawBody'] = req.body;
    req.body = JSON.parse(req.body.toString());
    next();
  }
}
  • 给其他地方用的普通的Parser
// json-body.middleware.ts
import {Request, Response} from 'express';
import * as bodyParser from 'body-parser';
import {Injectable, NestMiddleware} from '@nestjs/common';
@Injectable()
export class JsonBodyMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: () => any) {
    bodyParser.json()(req, res, next);
  }
}

基于上面的两个不同的场景,在根App 里面给注入进去:

import {Module, NestModule, MiddlewareConsumer} from '@nestjs/common';
import {JsonBodyMiddleware} from '@app/core/middlewares/json-body.middleware';
import {RawBodyMiddleware} from '@app/core/middlewares/raw-body.middleware';
import {RawBodyParserMiddleware} from '@app/core/middlewares/raw-body-parser.middleware';
import {StripeController} from '@app/events/stripe/stripe.controller';
@Module()
export class AppModule implements NestModule {
  public configure(consumer: MiddlewareConsumer): void {
    consumer
      .apply(RawBodyMiddleware, RawBodyParserMiddleware)
      .forRoutes(StripeController)
      .apply(JsonBodyMiddleware)
      .forRoutes('*');
  }
}

这里我们对实际处理WebHook 的相关Controller 应用了RawBodyMiddleware, RawBodyParserMiddleware 这两个中间件,它会在原来的转换结果基础上添加一个未转换的键,将Raw Response 也返回到程序内以作进一步处理;对于其他的地方,则全部使用一个默认的,和内置那个效果一样的Json Parser.

3. Interceptor 校验器

接下来,我们写一个用来校验的Interceptor. 用来处理验证,如果正常则通过,如果校验不通过则直接拦截返回。

import {
  BadRequestException,
  CallHandler,
  ExecutionContext,
  Injectable,
  Logger,
  NestInterceptor,
} from '@nestjs/common';
import Stripe from 'stripe';
import {Observable} from 'rxjs';
import {ConfigService} from '@app/shared/config/config.service';
import {StripeService} from '@app/shared/services/stripe.service';
@Injectable()
export class StripeInterceptor implements NestInterceptor {
  private readonly stripe: Stripe;
  private readonly logger = new Logger(StripeInterceptor.name);
  constructor(
    private readonly configService: ConfigService,
    private readonly stripeService: StripeService,
  ) {
    // 等同于
    // this.stripe = new Stripe(secret, {} as Stripe.StripeConfig);
    this.stripe = stripeService.getClient();
  }
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const signature = request.headers['stripe-signature'];
    // 因为Stripe 的验证是不同的WebHook 有不同的密钥的
    // 这里只需要根据业务的需求增加对应的密钥就行
    const CHARGE_SUCCEEDED = this.configService.get(
      'STRIPE_SECRET_CHARGE_SUCCEEDED',
    );
    const secrets = {
      'charge.succeed': CHARGE_SUCCEEDED,
    };
    const secret = secrets[request.body['type']];
    if (!secret) {
      throw new BadRequestException({
        status: 'Oops, Nice Try',
        message: 'WebHook Error: Function not supported',
      });
    }
    try {
      this.logger.log(signature, 'Stripe WebHook Signature');
      this.logger.log(request.body, 'Stripe WebHook Body');
      const event = this.stripe.webhooks.constructEvent(
        request.rawBody,
        signature,
        secret,
      );
      this.logger.log(event, 'Stripe WebHook Event');
    } catch (e) {
      this.logger.error(e.message, 'Stripe WebHook Validation');
      throw new BadRequestException({
        status: 'Oops, Nice Try',
        message: `WebHook Error: ${e.message as string}`,
      });
    }
    return next.handle();
  }
}

4. 应用到Controller

最后,我们把这个Interceptor 加到我们的WebHook Controller 上。

import {Controller, UseInterceptors} from '@nestjs/common';
import {StripeInterceptor} from '@app/core/interceptors/stripe.interceptor';
@Controller('stripe')
@UseInterceptors(StripeInterceptor)
export class StripeController {}

大功告成!

以上就是如何在NestJS中添加对Stripe的WebHook验证详解的详细内容,更多关于NestJS添加Stripe WebHook验证的资料请关注脚本之家其它相关文章!

相关文章

  • node.js中的fs.readFileSync方法使用说明

    node.js中的fs.readFileSync方法使用说明

    这篇文章主要介绍了node.js中的fs.readFileSync方法使用说明,本文介绍了fs.readFileSync的方法说明、语法、接收参数、使用实例和实现源码,需要的朋友可以参考下
    2014-12-12
  • 基于Node.js实现nodemailer邮件发送

    基于Node.js实现nodemailer邮件发送

    Nodemailer 是一个简单易用的 Node.JS 邮件发送模块(通过 SMTP,sendmail,或者 Amazon SES),支持 unicode,你可以使用任何你喜欢的字符集。Nodemailer是一个简单易用的Node.js邮件发送组件,需要的朋友可以参考下
    2016-01-01
  • node里的filesystem模块文件读写操作详解

    node里的filesystem模块文件读写操作详解

    这篇文章主要为大家介绍了node里的filesystem模块文件读写操作详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • nodejs nedb 封装库与使用方法示例

    nodejs nedb 封装库与使用方法示例

    这篇文章主要介绍了nodejs nedb 封装库与使用方法,结合实例形式分析了nodejs nedb.js封装库的定义与使用技巧,需要的朋友可以参考下
    2020-02-02
  • node.js中joi模块的基本使用方式

    node.js中joi模块的基本使用方式

    这篇文章主要介绍了node.js中joi模块的基本使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09
  • node文件批量重命名的方法示例

    node文件批量重命名的方法示例

    本篇文章主要介绍了node文件批量重命名的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • 详解Nodejs的timers模块

    详解Nodejs的timers模块

    本篇文章主要介绍了Nodejs的timers模块,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-12-12
  • node.js中express中间件body-parser的介绍与用法详解

    node.js中express中间件body-parser的介绍与用法详解

    这篇文章主要给大家介绍了关于node.js中express中间件body-parser的相关资料,文章通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧。
    2017-05-05
  • Node.js自定义实现文件路由功能

    Node.js自定义实现文件路由功能

    这篇文章主要介绍了Node.js自定义实现文件路由功能的相关资料,需要的朋友可以参考下
    2017-09-09
  • 爬虫利器Puppeteer实战

    爬虫利器Puppeteer实战

    本文详细的介绍了什么是Puppeteer以及使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-01-01

最新评论