如何在NestJS中添加對Stripe的WebHook驗證詳解
背景介紹
Nest 是一個用于構建高效,可擴展的NodeJS 服務器端應用程序的框架。它使用漸進式JavaScript, 內置并完全支持TypeScript, 但仍然允許開發(fā)人員使用純JavaScript 編寫代碼。并結合了OOP(面向對象編程),F(xiàn)P(函數(shù)式編程)和 FRP(函數(shù)式響應編程)的元素。
Stripe 是一家美國金融服務和軟件即服務公司,總部位于美國加利福尼亞州舊金山。主要提供用于電子商務網站和移動應用程序的支付處理軟件和應用程序編程接口。2020年8月4日,《蘇州高新區(qū) · 2020胡潤全球獨角獸榜》發(fā)布,Stripe 排名第5位。
注:接下來的內容需要有NodeJS 及NestJS 的使用經驗,如果沒有需要另外學習如何使用。
代碼實現(xiàn)
1. 去除自帶的Http Body Parser.
因為Nest 默認會將所有請求的結果在內部直接轉換成JavaScript 對象,這在一般情況下是很方便的,但如果我們要對響應的內容進行自定義的驗證的話就會有問題了,所以我們要先替換成自定義的。
首先,在根入口啟動應用時傳入?yún)?shù)禁用掉自帶的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 有不同的密鑰的
// 這里只需要根據(jù)業(yè)務的需求增加對應的密鑰就行
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驗證的資料請關注腳本之家其它相關文章!
相關文章
nodejs使用PassThrough流進行數(shù)據(jù)傳遞合并示例詳解
這篇文章主要為大家介紹了nodejs使用PassThrough流進行數(shù)據(jù)傳遞合并示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
如何正確使用Nodejs 的 c++ module 鏈接到 OpenSSL
這篇文章主要介紹了如何正確使用Nodejs 的 c++ module 鏈接到 OpenSSL,需要的朋友可以參考下2014-08-08
Node.js+Express+MySql實現(xiàn)用戶登錄注冊功能
這篇文章主要為大家詳細介紹了Node.js+Express+MySql實現(xiàn)用戶登錄注冊,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
Node.js 中 cookie-parser 依賴安裝使用詳解
文章介紹了如何在Node.js中使用cookie-parser中間件來解析、設置、簽名和清除HTTP請求中的Cookie,感興趣的朋友一起看看吧2025-02-02
在Nodejs中實現(xiàn)一個緩存系統(tǒng)的方法詳解
在數(shù)據(jù)庫查詢遇到瓶頸時,我們通??梢圆捎镁彺鎭硖嵘樵兯俣?同時緩解數(shù)據(jù)庫壓力,在一些簡單場景中,我們也可以自己實現(xiàn)一個緩存系統(tǒng),避免使用額外的緩存中間件,這篇文章將帶你一步步實現(xiàn)一個完善的緩存系統(tǒng),需要的朋友可以參考下2024-03-03

