在NestJS 中添加对Stripe 的WebHook 验证

805 阅读3分钟

在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 中间件

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

  1. 给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();
  }
}
  1. 给其他地方用的普通的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 {}

大功告成!