如何在NestJS中添加對(duì)Stripe的WebHook驗(yàn)證詳解
背景介紹
Nest 是一個(gè)用于構(gòu)建高效,可擴(kuò)展的NodeJS 服務(wù)器端應(yīng)用程序的框架。它使用漸進(jìn)式JavaScript, 內(nèi)置并完全支持TypeScript, 但仍然允許開發(fā)人員使用純JavaScript 編寫代碼。并結(jié)合了OOP(面向?qū)ο缶幊蹋?,F(xiàn)P(函數(shù)式編程)和 FRP(函數(shù)式響應(yīng)編程)的元素。
Stripe 是一家美國金融服務(wù)和軟件即服務(wù)公司,總部位于美國加利福尼亞州舊金山。主要提供用于電子商務(wù)網(wǎng)站和移動(dòng)應(yīng)用程序的支付處理軟件和應(yīng)用程序編程接口。2020年8月4日,《蘇州高新區(qū) · 2020胡潤全球獨(dú)角獸榜》發(fā)布,Stripe 排名第5位。
注:接下來的內(nèi)容需要有NodeJS 及NestJS 的使用經(jīng)驗(yàn),如果沒有需要另外學(xué)習(xí)如何使用。
代碼實(shí)現(xiàn)
1. 去除自帶的Http Body Parser.
因?yàn)镹est 默認(rèn)會(huì)將所有請(qǐng)求的結(jié)果在內(nèi)部直接轉(zhuǎn)換成JavaScript 對(duì)象,這在一般情況下是很方便的,但如果我們要對(duì)響應(yīng)的內(nèi)容進(jìn)行自定義的驗(yàn)證的話就會(huì)有問題了,所以我們要先替換成自定義的。
首先,在根入口啟動(dòng)應(yīng)用時(shí)傳入?yún)?shù)禁用掉自帶的Parser.
import {NestFactory} from '@nestjs/core';
import {ExpressAdapter, NestExpressApplication} from '@nestjs/platform-express';
// 應(yīng)用根
import {AppModule} from '@app/app/app.module';
// 禁用bodyParser
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
new ExpressAdapter(),
{cors: true, bodyParser: false},
);2. Parser 中間件
然后定義三個(gè)不同的中間件:
- 給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);
}
}基于上面的兩個(gè)不同的場(chǎng)景,在根App 里面給注入進(jìn)去:
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('*');
}
}這里我們對(duì)實(shí)際處理WebHook 的相關(guān)Controller 應(yīng)用了RawBodyMiddleware, RawBodyParserMiddleware 這兩個(gè)中間件,它會(huì)在原來的轉(zhuǎn)換結(jié)果基礎(chǔ)上添加一個(gè)未轉(zhuǎn)換的鍵,將Raw Response 也返回到程序內(nèi)以作進(jìn)一步處理;對(duì)于其他的地方,則全部使用一個(gè)默認(rèn)的,和內(nèi)置那個(gè)效果一樣的Json Parser.
3. Interceptor 校驗(yàn)器
接下來,我們寫一個(gè)用來校驗(yàn)的Interceptor. 用來處理驗(yàn)證,如果正常則通過,如果校驗(yàn)不通過則直接攔截返回。
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'];
// 因?yàn)镾tripe 的驗(yàn)證是不同的WebHook 有不同的密鑰的
// 這里只需要根據(jù)業(yè)務(wù)的需求增加對(duì)應(yīng)的密鑰就行
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. 應(yīng)用到Controller
最后,我們把這個(gè)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中添加對(duì)Stripe的WebHook驗(yàn)證詳解的詳細(xì)內(nèi)容,更多關(guān)于NestJS添加Stripe WebHook驗(yàn)證的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Node.js與MongoDB構(gòu)建后端評(píng)論系統(tǒng)實(shí)戰(zhàn)指南
Node.js作為一門基于Chrome V8引擎的JavaScript運(yùn)行環(huán)境,它的非阻塞I/O模型和事件驅(qū)動(dòng)架構(gòu)使得它在處理大量并發(fā)連接方面表現(xiàn)優(yōu)異,成為了構(gòu)建網(wǎng)絡(luò)應(yīng)用的流行選擇,本文講述Node.js與MongoDB構(gòu)建后端評(píng)論系統(tǒng)實(shí)戰(zhàn),感興趣的朋友一起看看吧2025-04-04
NodeJs的優(yōu)勢(shì)和適合開發(fā)的程序
做頁游或webqq這樣的應(yīng)用nodejs有優(yōu)勢(shì),但如果做微博、豆瓣、facebook這樣的社交網(wǎng)絡(luò),nodejs還有優(yōu)勢(shì)嗎?另外不知道大家是什么原因選擇的nodejs?是因?yàn)閼?yīng)用需求還是對(duì)javascript這門語言的喜歡?2016-08-08
創(chuàng)建簡單的node服務(wù)器實(shí)例(分享)
下面小編就為大家?guī)硪黄獎(jiǎng)?chuàng)建簡單的node服務(wù)器實(shí)例(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
Node.js利用Net模塊實(shí)現(xiàn)多人命令行聊天室的方法
Node.js Net 模塊提供了一些用于底層的網(wǎng)絡(luò)通信的小工具,包含了創(chuàng)建服務(wù)器/客戶端的方法,下面這篇文章主要給大家介紹了Node.js利用Net模塊實(shí)現(xiàn)命令行多人聊天室的方法,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-12-12
Node.js Buffer模塊功能及常用方法實(shí)例分析
這篇文章主要介紹了Node.js Buffer模塊功能及常用方法,結(jié)合實(shí)例形式分析了Buffer模塊的各種常用函數(shù)及相關(guān)使用技巧,需要的朋友可以參考下2019-01-01

