# @golevelup/nestjs-stripe 中文文档

规范地址：https://npmcn.com/package/%40golevelup/nestjs-stripe/

版本：3\.0\.0
npm 元数据更新时间：2026-03-18T20:15:22.048Z
中文译文更新时间：2026-11-16T18:44:58.656Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40golevelup/nestjs-stripe
原文对照：https://npmcn.com/package/%40golevelup/nestjs-stripe/?lang=original
项目主页：https://github.com/golevelup/nestjs#readme
源码仓库：https://github.com/golevelup/nestjs

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：58.2 kB，39 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：stripe ^20\.4\.1
- 首次发布：2020-04-08T11:39:07.461Z
- 最新版本发布：2026-03-18T20:15:21.877Z
- 近 30 天下载量：63093（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：38（近 12 个月 8 个）

## 中文简介

整合条纹和雀巢JS的不良公用事业

## 安装

```sh
npm install @golevelup/nestjs-stripe
```

也可以使用：`pnpm add @golevelup/nestjs-stripe`、`yarn add @golevelup/nestjs-stripe`、`bun add @golevelup/nestjs-stripe`

## README

# 条纹

在您的 NestJS 应用程序中与 Streape API 或消费 Streape webhooks 交互, 现在容易成为馅饼 QQ

[![version](https://img.shields.io/npm/v/@golevelup/nestjs-stripe.svg?style=flat)](https://www.npmjs.com/package/@golevelup/nestjs-stripe) [![downloads](https://img.shields.io/npm/dt/@golevelup/nestjs-stripe.svg?style=flat)](https://www.npmjs.com/package/@golevelup/nestjs-stripe) ![license](https://img.shields.io/npm/l/@golevelup/nestjs-stripe.svg)

## 开始

\* :密码组

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

```bash
yarn add @golevelup/nestjs-stripe stripe
```

```bash
pnpm add @golevelup/nestjs-stripe stripe
```

\* :

## 特征

-   在控制器和提供者中与 Streape API 交互的可注入条纹客户端
    
-   QQ 可选地曝光您 NestJS 应用程序中的 API 端点, 用于 Strede 的 Webhook 事件处理 。 默认为 `/stripe/webhook` 但可以轻松配置
    
-   QQ 自动验证事件有效载荷是使用配置的 Webhook 签名秘密从 Strebe 发送的
    
-   QQ 从您的应用程序中发现提供者 `StripeWebhookHandler` 财务报告和审定财务报表 `StripeThinWebhookHandler` 以及前往它们途中的路线
    
-   QQ 路由事件到逻辑服务, 只需提供 Strepe webhook 事件类型即可
    
-   \* \* 支持传统快照事件和Frede的新 v2 瘦事件
    

## 导入

导入并添加 `StripeModule` 页:1 `imports` 消费单元的一节(最有可能) `AppModule`) (中文(简体) ). 您的 Frede API 密钥是需要的, 如果您计划在您的应用程序中消费 Frede 网络hook 事件, 您可以选择包含一个 webhook 配置 . 从你的Dashboard上可以得到的 隐藏秘密 [Webhoks 设置](https://dashboard.stripe.com/webhooks)。选择一个想要获取该秘密的终点,然后单击“签名秘密”下方的启示录链接.

**快照事件( 传统 Webhooks ) :** `account` - 你帐号上的事件 在Frede Dashboard上注册的 Webhook秘密 `accountTest` - 在Frede Dashboard上注册的用于测试模式中您账户上的事件的 Webhook 秘密 `connect` - 在Frede Dashboard上注册的关于Connected账户事件的网站库秘密 `connectTest` - 在Frede Dashboard为测试模式下连接账户上的事件注册的 Webhook 秘密

**细事件( V2 Webhooks - 可选) :** `stripeThinSecrets` - Frede v2 细小事件(仅在使用时需要)的单独秘密 `@StripeThinWebhookHandler`(中文(简体) )

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

@Module({
  imports: [
    StripeModule.forRoot({
      apiKey: 'sk_***',
      webhookConfig: {
        // Snapshot event secrets
        stripeSecrets: {
          account: 'whsec_***',
          accountTest: 'whsec_***',
          connect: 'whsec_***',
          connectTest: 'whsec_***',
        },
        // Thin event secrets (optional)
        stripeThinSecrets: {
          account: 'whsec_***',
          accountTest: 'whsec_***',
          connect: 'whsec_***',
          connectTest: 'whsec_***',
        },
      },
    }),
  ],
})
export class AppModule {
  // ...
}
```

### 配置

条纹模块支持 `forRoot` 财务报告和审定财务报表 `forRootAsync` 配置模式,这样您就可以轻松地从一个 `ConfigService` 或其他提供者.

### 可注射供应商

该模块曝光出两个可注射的供应商,并配有配套的装饰来方便您. 这些可以提供给控制器和其他提供者的构造者:

```typescript
 // injects the instantiated Stripe client which can be used to make API calls
@InjectStripeClient() stripeClient: Stripe
```

```typescript
// injects the module configuration
@InjectStripeModuleConfig() config: StripeModuleConfig
```

## 正在关闭 Webhooks

### 包含 API 终点

此模块将自动为您的 NestJS 应用程序添加一个新的 API 端点, 用于处理 Webhooks 。 默认情况下,此端点的路由将是 `stripe/webhook` 但您可以修改此选项, 使用不同的前缀 `controllerPrefix` 财产的财产 `webhookConfig` 当导入模块时.

### 配置原始请求正文处理

如果您希望您的 NestJS 应用程序能够处理收到的webhooks, 就必须让 Stale 能够访问原始请求的有效载荷 .

默认情况下, NestJS 被配置为使用 JSON body 剖析中间软件,在它被 Strede 库验证之前会转换请求.

你可以选择 [通过原始请求正文](https://docs.nestjs.com/faq/raw-body#use-with-express) 根据每项请求, 这不会给您现有的建筑设计和其他API带来副作用.

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

然后手动设置 `bodyProperty` 用于使用生的Body :

```typescript
StripeModule.forRoot({
  apiKey: 'sk_***',
  webhookConfig: {
    stripeSecrets: { ... },
    requestBodyProperty: 'rawBody', // <-- Set to 'rawBody'
  },
});
```

### 装饰处理 Webhook 事件的方法

曝光处理花旗事件所使用的提供者/服务方法很简单!. 简单地使用所提供的装饰并显示处理器应接收的事件类型 .

[审查花旗文件](https://stripe.com/docs/api/events/types) 需要更多关于现有事件类型的信息.

#### 快照事件( 传统)

使用 `@StripeWebhookHandler` 用于传统花旗网游活动。 其中包括有效载荷中的全部事件物体.

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

**Webhook 網址 :** `https://your-domain.com/stripe/webhook`

#### 细事件( V2)

使用 `@StripeThinWebhookHandler` 因为史崔克的五一事件 这些轻量级事件只包括元数据 - 你需要单独获取完整的对象.

```typescript
@Injectable()
class BillingService {
  constructor(@InjectStripeClient() private stripe: Stripe) {}

  @StripeThinWebhookHandler('v1.billing.meter.error_report_triggered')
  async handleBillingMeterError(
    evt: Stripe.Events.V1BillingMeterErrorReportTriggeredEventNotification,
  ) {
    // Thin events require fetching the full object
    const meter = await evt.fetchRelatedObject();
    // execute your custom business logic
  }
}
```

**Webhook 網址 :** `https://your-domain.com/stripe/webhook?mode=thin`

#### 通卡处理器

你用得着 `'*'` 用于处理特定类型的所有事件:

```typescript
@Injectable()
class WebhookLogger {
  @StripeWebhookHandler('*')
  logAllSnapshotEvents(evt: Stripe.Event) {
    console.log('Received snapshot event:', evt.type);
  }

  @StripeThinWebhookHandler('*')
  logAllThinEvents(evt: Stripe.V2.Core.Event) {
    console.log('Received thin event:', evt.type);
  }
}
```

### Webhook 控制器

您也可以通过任何类的装饰器 `decorators` 财产的财产 `webhookConfig` 对象作为模块配置的一部分。 这可以用于诸如使用 `@nestjs/throttler` 软件包和需要应用 `@SkipThrottle()` 装饰器,或者当您有全局守护,但需要通过某些元数据跳过路径时.

```typescript
StripeModule.forRoot({
  apiKey: 'sk_***',
  webhookConfig: {
    stripeSecrets: { ... },
    decorators: [SkipThrottle()],
  },
}),
```

### 使用拦截器、警卫和过滤器

这个库是使用一个叫做NestJS的基本概念建造的 `External Contexts` 允许将方法纳入NestJS生命周期。 这意味着"护卫","截取"和"滤取"(统称为"增强")可以与"花纹"(Strepe webhook)处理器结合使用. 但是,如果使用下列方法,则会产生意外/意外后果: _全球_ 应用程序中的增强器,因为这些器件也将适用于所有 Strepe webhook 处理器。 如果您先前期望所有上下文都是正则的 HTTP 上下文, 您可能需要添加条件逻辑来阻止您的增强器应用到 Strepe webhook 处理器 .

您可以按其上下文类型识别 Stale webhook 上下文, `'stripe_webhook'`数字 :

```typescript
import { STRIPE_WEBHOOK_CONTEXT_TYPE } from '@golevelup/nestjs-stripe';

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

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

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

### 在条形板上配置 Webhooks

遵循来自 [条形文档](https://stripe.com/docs/webhooks) 用于在您启动前测试您与 CLI 的整合等剩余整合步骤, 并正确配置 Frede 仪表板的端点, 以便将正确的事件发送到您的 NestJS 应用程序 .

## 常见问题

### @golevelup/nestjs-stripe 是什么？

整合条纹和雀巢JS的不良公用事业

### 如何安装 @golevelup/nestjs-stripe？

在项目目录运行 npm install @golevelup/nestjs-stripe，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：stripe（^20\.4\.1）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @golevelup/nestjs-stripe 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @golevelup/nestjs-stripe 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @golevelup/nestjs-stripe 可以商用吗？

@golevelup/nestjs-stripe 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @golevelup/nestjs-stripe 的下载量有多少？

根据 npm 官方下载统计，@golevelup/nestjs-stripe 在 2026/10/17 – 2026/11/15 这 30 天内被下载 63,093 次，日均约 2,103 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @golevelup/nestjs-stripe 还在维护吗？

最新版本 3\.0\.0 发布于 2026/03/19（7 个月前）；至今共发布 38 个版本，其中过去 12 个月发布了 8 个；首次发布于 2020/04/08。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

