express-stripe-webhook-middleware 0.1.0 โ†’ 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,224 +1,315 @@
1
1
  # Express Stripe Webhook Middleware
2
2
 
3
- You can easy to verify the Webhook request from Stripe.
3
+ [![npm version](https://badge.fury.io/js/express-stripe-webhook-middleware.svg)](https://www.npmjs.com/package/express-stripe-webhook-middleware)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
5
 
6
+ A modern, type-safe Express middleware for verifying Stripe webhook signatures. Built with TypeScript and Vite.
5
7
 
6
- ## Install
8
+ ## Features
9
+
10
+ - โœ… **Type-safe**: Full TypeScript support with strict type checking
11
+ - ๐Ÿ”’ **Secure**: Automatic signature verification using Stripe's SDK
12
+ - ๐ŸŽฏ **Simple API**: Easy to use with Express applications
13
+ - ๐Ÿ”ง **Flexible**: Custom error handlers and logging
14
+ - โšก **Modern**: Built with Vite and latest dependencies
15
+ - ๐Ÿงช **Well-tested**: Comprehensive test coverage with Vitest
16
+
17
+ ## Installation
7
18
 
8
19
  ```bash
9
- $ yarn add express-stripe-webhook-middleware
20
+ npm install express-stripe-webhook-middleware stripe express
21
+ # or
22
+ yarn add express-stripe-webhook-middleware stripe express
23
+ # or
24
+ pnpm add express-stripe-webhook-middleware stripe express
25
+ ```
26
+
27
+ ## Quick Start
28
+
29
+ ### TypeScript
30
+
31
+ ```typescript
32
+ import Stripe from 'stripe';
33
+ import express from 'express';
34
+ import { createStripeWebhookMiddleware } from 'express-stripe-webhook-middleware';
35
+
36
+ const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
37
+ const app = express();
38
+
39
+ app.post(
40
+ '/webhook',
41
+ ...createStripeWebhookMiddleware(process.env.STRIPE_WEBHOOK_SECRET!, stripe),
42
+ (req, res) => {
43
+ const event = req.body as Stripe.Event;
44
+
45
+ // Handle the event
46
+ switch (event.type) {
47
+ case 'payment_intent.succeeded':
48
+ console.log('PaymentIntent was successful!');
49
+ break;
50
+ case 'payment_method.attached':
51
+ console.log('PaymentMethod was attached to a Customer!');
52
+ break;
53
+ default:
54
+ console.log(`Unhandled event type ${event.type}`);
55
+ }
56
+
57
+ res.json({ received: true });
58
+ }
59
+ );
60
+
61
+ app.listen(4242, () => console.log('Server running on port 4242'));
10
62
  ```
11
63
 
12
- ## Usage
64
+ ### JavaScript (CommonJS)
13
65
 
14
66
  ```javascript
15
67
  const Stripe = require('stripe');
16
68
  const express = require('express');
17
- const { StripeWebhookMiddlewareFactory } = require('express-stripe-webhook-middleware')
18
- require('dotenv').config()
69
+ const { createStripeWebhookMiddleware } = require('express-stripe-webhook-middleware');
70
+
71
+ const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
72
+ const app = express();
73
+
74
+ app.post(
75
+ '/webhook',
76
+ ...createStripeWebhookMiddleware(process.env.STRIPE_WEBHOOK_SECRET, stripe),
77
+ (req, res) => {
78
+ const event = req.body;
79
+ console.log('Received event:', event.type);
80
+ res.json({ received: true });
81
+ }
82
+ );
83
+
84
+ app.listen(4242);
85
+ ```
86
+
87
+ ## Advanced Usage
88
+
89
+ ### Using the Factory Pattern
90
+
91
+ ```typescript
92
+ import { StripeWebhookMiddlewareFactory } from 'express-stripe-webhook-middleware';
19
93
 
20
- const stripe = new Stripe(process.env.STRIPE_SECRET_API_KEY, {
21
- apiVersion: '2020-08-27',
94
+ const factory = new StripeWebhookMiddlewareFactory(
95
+ process.env.STRIPE_WEBHOOK_SECRET!,
96
+ stripe
97
+ );
98
+
99
+ app.post('/webhook', ...factory.create(), (req, res) => {
100
+ const event = req.body as Stripe.Event;
101
+ // Handle event
102
+ res.json({ received: true });
22
103
  });
104
+ ```
105
+
106
+ ### Custom Error Handling
107
+
108
+ ```typescript
109
+ const factory = new StripeWebhookMiddlewareFactory(
110
+ process.env.STRIPE_WEBHOOK_SECRET!,
111
+ stripe,
112
+ {
113
+ onError: (error, req, res) => {
114
+ console.error('Webhook error:', error.message);
115
+ res.status(400).json({
116
+ error: 'Webhook signature verification failed',
117
+ message: error.message
118
+ });
119
+ }
120
+ }
121
+ );
23
122
 
24
- /**
25
- * Examples
26
- */
27
- const app = express();
28
- const webhookRouter = express.Router();
29
- const factory = new StripeWebhookMiddlewareFactory(process.env.STRIPE_WEBHOOK_SECRET_KEY, stripe)
30
- webhookRouter.use(
31
- '/webhook',
32
- factory.create()
33
- );
34
-
35
- webhookRouter.post('/webhook', (request, response) => {
36
- const payload = request.body;
37
- console.log('=====');
38
- console.log(payload);
39
- response.status(200).send('Webhook done!');
40
- });
41
-
42
-
43
- app.post('/webhook', webhookRouter);
44
- app.get('/', async (req, res) => {
45
- const data = stripe.customers.list();
46
- res.status(200).send(JSON.stringify(data));
47
- });
48
- app.listen(4242, () => console.log('start'));
49
-
123
+ app.post('/webhook', ...factory.create(), (req, res) => {
124
+ res.json({ received: true });
125
+ });
50
126
  ```
51
127
 
52
- ## Why?
128
+ ### Custom Logger
53
129
 
54
- Stripe recommend to check the Webhook signatures from Stripe.
55
- https://stripe.com/docs/webhooks/signatures
130
+ ```typescript
131
+ import pino from 'pino';
56
132
 
57
- Stripe show us these example code to verify the signatures.
133
+ const logger = pino();
58
134
 
59
- ```javascript
60
- // Set your secret key. Remember to switch to your live secret key in production.
61
- // See your keys here: https://dashboard.stripe.com/apikeys
62
- const stripe = require('stripe')('sk_testXXXXXX');
135
+ const factory = new StripeWebhookMiddlewareFactory(
136
+ process.env.STRIPE_WEBHOOK_SECRET!,
137
+ stripe,
138
+ {
139
+ logger: (error) => logger.error({ error }, 'Webhook verification failed')
140
+ }
141
+ );
142
+ ```
63
143
 
64
- // If you are testing your webhook locally with the Stripe CLI you
65
- // can find the endpoint's secret by running `stripe listen`
66
- // Otherwise, find your endpoint's secret in your webhook settings in the Developer Dashboard
67
- const endpointSecret = 'whsec_...';
144
+ ## Why This Package?
68
145
 
69
- // This example uses Express to receive webhooks
70
- const app = require('express')();
146
+ [Stripe recommends verifying webhook signatures](https://stripe.com/docs/webhooks/signatures) to ensure the requests actually come from Stripe.
71
147
 
72
- // Use body-parser to retrieve the raw body as a buffer
73
- const bodyParser = require('body-parser');
148
+ ### Without This Package
74
149
 
75
- // Match the raw body to content type application/json
76
- app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
77
- const sig = request.headers['stripe-signature'];
150
+ Following Stripe's official example, you need to manually set up body parsing and signature verification:
78
151
 
152
+ ```javascript
153
+ const stripe = require('stripe')('sk_test_...');
154
+ const bodyParser = require('body-parser');
155
+ const app = require('express')();
156
+
157
+ app.post('/webhook', bodyParser.raw({type: 'application/json'}), (req, res) => {
158
+ const sig = req.headers['stripe-signature'];
79
159
  let event;
80
160
 
81
161
  try {
82
- event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
83
- }
84
- catch (err) {
85
- response.status(400).send(`Webhook Error: ${err.message}`);
162
+ event = stripe.webhooks.constructEvent(req.body, sig, 'whsec_...');
163
+ } catch (err) {
164
+ return res.status(400).send(`Webhook Error: ${err.message}`);
86
165
  }
87
166
 
88
167
  // Handle the event
89
168
  switch (event.type) {
90
169
  case 'payment_intent.succeeded':
91
- const paymentIntent = event.data.object;
92
- console.log('PaymentIntent was successful!');
93
- break;
94
- case 'payment_method.attached':
95
- const paymentMethod = event.data.object;
96
- console.log('PaymentMethod was attached to a Customer!');
170
+ console.log('PaymentIntent succeeded!');
97
171
  break;
98
- // ... handle other event types
99
- default:
100
- console.log(`Unhandled event type ${event.type}`);
172
+ // ... more cases
101
173
  }
102
174
 
103
- // Return a response to acknowledge receipt of the event
104
- response.json({received: true});
175
+ res.json({ received: true });
105
176
  });
106
-
107
- app.listen(4242, () => console.log('Running on port 4242'));
108
177
  ```
109
178
 
110
- When using this package, we can re-write the code like this.
179
+ ### With This Package
111
180
 
112
- ```javascript
113
- require('dotenv').config()
114
- const Stripe = require('stripe');
115
- const express = require('express');
116
- const { StripeWebhookMiddlewareFactory } = require('express-stripe-webhook-middleware')
181
+ Much cleaner and type-safe:
117
182
 
118
- const stripe = new Stripe(process.env.STRIPE_SECRET_API_KEY, {
119
- apiVersion: '2020-08-27',
120
- });
183
+ ```typescript
184
+ import { createStripeWebhookMiddleware } from 'express-stripe-webhook-middleware';
185
+
186
+ app.post(
187
+ '/webhook',
188
+ ...createStripeWebhookMiddleware('whsec_...', stripe),
189
+ (req, res) => {
190
+ const event = req.body as Stripe.Event;
121
191
 
122
- const app = express();
123
- const factory = new StripeWebhookMiddlewareFactory(process.env.STRIPE_WEBHOOK_SECRET_KEY, stripe)
124
- app.post('/webhook', factory.create());
125
- app.post('/webhook', async (request, response) => {
126
- const event = request.body
127
- // Handle the event
128
192
  switch (event.type) {
129
193
  case 'payment_intent.succeeded':
130
- const paymentIntent = event.data.object;
131
- console.log('PaymentIntent was successful!');
194
+ console.log('PaymentIntent succeeded!');
132
195
  break;
133
- case 'payment_method.attached':
134
- const paymentMethod = event.data.object;
135
- console.log('PaymentMethod was attached to a Customer!');
136
- break;
137
- // ... handle other event types
138
- default:
139
- console.log(`Unhandled event type ${event.type}`);
140
196
  }
141
-
142
- // Return a response to acknowledge receipt of the event
143
- response.json({received: true});
144
- });
145
- app.listen(4242, () => console.log('Running on port 4242'));
197
+
198
+ res.json({ received: true });
199
+ }
200
+ );
146
201
  ```
147
202
 
148
- ## Try it out!
203
+ ## API Reference
149
204
 
150
- You can test the package on the `example/` directory
205
+ ### `createStripeWebhookMiddleware(endpointSecret, stripe, options?)`
151
206
 
152
- ### Clone the project
207
+ Convenience function that creates and returns the middleware array.
153
208
 
154
- ``` bash
155
- $ git clone git@github.com:hideokamoto/express-stripe-webhook-middleware.git
156
- $ cd express-stripe-webhook-middleware
157
- $ npm install
158
- ```
209
+ **Parameters:**
210
+ - `endpointSecret` (string): Your Stripe webhook secret (starts with `whsec_`)
211
+ - `stripe` (Stripe): Stripe SDK instance
212
+ - `options` (optional): Configuration options
213
+ - `logger`: Custom logger function
214
+ - `onError`: Custom error handler
159
215
 
160
- ### Step1: Install packages
216
+ **Returns:** `RequestHandler[]` - Array of Express middleware
161
217
 
162
- Install libraries.
218
+ ### `StripeWebhookMiddlewareFactory`
163
219
 
164
- ```bash
165
- $ cd example
166
- $ npm install
220
+ Factory class for creating the middleware.
221
+
222
+ **Constructor:**
223
+ ```typescript
224
+ new StripeWebhookMiddlewareFactory(
225
+ endpointSecret: string,
226
+ stripe: Stripe,
227
+ options?: StripeWebhookMiddlewareOptions
228
+ )
167
229
  ```
168
230
 
169
- ### Step2: Put your Stripe API keys
231
+ **Methods:**
232
+ - `create()`: Returns `RequestHandler[]`
170
233
 
171
- Open `.env` file, and replace api key from dummy to your account one.
234
+ ## Testing Your Webhooks
172
235
 
173
- ```bash
174
- $ vim .env
175
- STRIPE_SECRET_API_KEY=sk_test_XXXXXXX
176
- STRIPE_WEBHOOK_SECRET_KEY=whsec_XXXXXXX
177
- ```
236
+ ### Using Stripe CLI
178
237
 
179
- ### Step3: Start the express server
238
+ 1. Install [Stripe CLI](https://stripe.com/docs/stripe-cli)
180
239
 
181
- You can start the demo server by this command.
240
+ 2. Forward webhooks to your local server:
241
+ ```bash
242
+ stripe listen --forward-to localhost:4242/webhook
243
+ ```
182
244
 
245
+ 3. Trigger test events:
183
246
  ```bash
184
- $ node index.js
247
+ stripe trigger payment_intent.succeeded
185
248
  ```
186
249
 
187
- ### Step4: Listen and forward Stripe Webhook request by using Stripe CLI
250
+ ### Example Test Server
188
251
 
189
- Stripe CLI can forward the Webhook request to your localhost server.
252
+ ```typescript
253
+ import Stripe from 'stripe';
254
+ import express from 'express';
255
+ import { createStripeWebhookMiddleware } from 'express-stripe-webhook-middleware';
190
256
 
191
- ```bash
192
- $ stripe listen --forward-to localhost:4242/webhook
257
+ const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
258
+ const app = express();
259
+
260
+ app.post(
261
+ '/webhook',
262
+ ...createStripeWebhookMiddleware(process.env.STRIPE_WEBHOOK_SECRET!, stripe),
263
+ (req, res) => {
264
+ const event = req.body as Stripe.Event;
265
+ console.log('โœ… Received event:', event.type);
266
+ res.json({ received: true });
267
+ }
268
+ );
269
+
270
+ app.listen(4242, () => {
271
+ console.log('๐Ÿš€ Webhook server running on http://localhost:4242');
272
+ });
193
273
  ```
194
274
 
195
- ### Step5: Execute Stripe Webhook event by using Stripe CLI
275
+ ## Requirements
276
+
277
+ - Node.js >= 18
278
+ - Express ^4.18.0 || ^5.0.0
279
+ - Stripe SDK ^14.0.0 || newer
280
+
281
+ ## Contributing
282
+
283
+ Contributions are welcome! Please feel free to submit a Pull Request.
196
284
 
197
- Trigger test webhook event from Stripe CLI.
285
+ This repository uses [pnpm](https://pnpm.io/) (the version is pinned by `packageManager` in `package.json`):
198
286
 
199
287
  ```bash
200
- $ stripe trigger payment_intent.created
288
+ pnpm install
289
+ pnpm run lint
290
+ pnpm run typecheck
291
+ pnpm run build
292
+ pnpm test
201
293
  ```
202
294
 
203
- Then, you can see the request body on the server log.
295
+ Releases are automated: merging to `main` runs semantic-release on CircleCI, which decides the next version from [Conventional Commits](https://www.conventionalcommits.org/) since the last `v*` tag, publishes to npm, and creates the GitHub Release. Do not bump `version` in `package.json` by hand.
204
296
 
205
- ```bash
206
- % node index.js
207
- start
208
- =====
209
- {
210
- id: 'evt_1JBeVwDHnG67uihbF0mxej38',
211
- object: 'event',
212
- api_version: '2020-08-27',
213
- created: 1625917112,
214
- data: {
215
- object: {
216
- id: 'pi_1JBeVwDHnG67uihb1LH7ioR2',
217
- object: 'payment_intent',
218
- amount: 2000,
219
- amount_capturable: 0,
220
- amount_received: 0,
221
- application: null,
222
- application_fee_amount: null,
223
- ...
224
- ```
297
+ ## License
298
+
299
+ MIT ยฉ [Hidetaka Okamoto](https://github.com/hideokamoto)
300
+
301
+ ## Changelog
302
+
303
+ ### v0.2.0
304
+ - ๐Ÿš€ Migrated from TSDX to Vite
305
+ - ๐Ÿ“ฆ Updated to latest dependencies (Stripe SDK v17+, TypeScript 5.7)
306
+ - โœจ Added `createStripeWebhookMiddleware` helper function
307
+ - ๐Ÿ”ง Added custom error handler support via `onError` option
308
+ - ๐ŸŽฏ Improved type safety with strict TypeScript settings
309
+ - โœ… Enhanced test coverage with Vitest
310
+ - ๐Ÿ“ Comprehensive JSDoc documentation
311
+ - โšก Better error handling for missing signatures
312
+ - ๐Ÿ”„ Now exports both ESM and CommonJS formats
313
+
314
+ ### v0.1.0
315
+ - Initial release with TSDX
package/dist/index.cjs ADDED
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
6
+ const bodyParser = require("body-parser");
7
+ class StripeWebhookMiddlewareFactory {
8
+ /**
9
+ * Creates a new StripeWebhookMiddlewareFactory instance
10
+ *
11
+ * @param endpointSecret - Stripe webhook secret key (starts with `whsec_`)
12
+ * @param client - Stripe SDK client instance
13
+ * @param options - Optional configuration
14
+ */
15
+ constructor(endpointSecret, client, options) {
16
+ __publicField(this, "endpointSecret");
17
+ __publicField(this, "stripe");
18
+ __publicField(this, "log");
19
+ __publicField(this, "onError");
20
+ this.endpointSecret = endpointSecret;
21
+ this.stripe = client;
22
+ this.log = (options == null ? void 0 : options.logger) ?? console.error;
23
+ this.onError = options == null ? void 0 : options.onError;
24
+ }
25
+ /**
26
+ * Creates an array of middleware handlers for Stripe webhook verification
27
+ *
28
+ * Returns an array containing:
29
+ * 1. body-parser middleware to parse raw body
30
+ * 2. Stripe signature verification middleware
31
+ *
32
+ * @returns Array of Express request handlers
33
+ */
34
+ create() {
35
+ const { endpointSecret, stripe, log, onError } = this;
36
+ const rawBodyParser = bodyParser.raw({ type: "application/json" });
37
+ const verifySignature = (req, res, next) => {
38
+ const sig = req.headers["stripe-signature"];
39
+ if (!sig) {
40
+ const error = new Error("Missing stripe-signature header");
41
+ log(error);
42
+ if (onError) {
43
+ onError(error, req, res);
44
+ return;
45
+ }
46
+ res.status(400).send(`Webhook Error: ${error.message}`);
47
+ return;
48
+ }
49
+ try {
50
+ const event = stripe.webhooks.constructEvent(
51
+ req.body,
52
+ sig,
53
+ endpointSecret
54
+ );
55
+ req.body = event;
56
+ next();
57
+ } catch (err) {
58
+ const error = err instanceof Error ? err : new Error(String(err));
59
+ log(error);
60
+ if (onError) {
61
+ onError(error, req, res);
62
+ return;
63
+ }
64
+ res.status(400).send(`Webhook Error: ${error.message}`);
65
+ }
66
+ };
67
+ return [rawBodyParser, verifySignature];
68
+ }
69
+ }
70
+ function createStripeWebhookMiddleware(endpointSecret, client, options) {
71
+ const factory = new StripeWebhookMiddlewareFactory(
72
+ endpointSecret,
73
+ client,
74
+ options
75
+ );
76
+ return factory.create();
77
+ }
78
+ exports.StripeWebhookMiddlewareFactory = StripeWebhookMiddlewareFactory;
79
+ exports.createStripeWebhookMiddleware = createStripeWebhookMiddleware;
80
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import type Stripe from 'stripe';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { raw } from 'body-parser';\n\nexport type Logger = (message?: unknown, ...optionalParams: unknown[]) => void;\n\nexport interface StripeWebhookMiddlewareOptions {\n /**\n * Custom logger function for error logging\n * @default console.error\n */\n logger?: Logger;\n\n /**\n * Custom error handler function\n * If not provided, sends a 400 response with the error message\n */\n onError?: (error: Error, req: Request, res: Response) => void;\n}\n\n/**\n * Factory class for creating Express middleware that verifies Stripe webhook signatures\n *\n * @example\n * ```typescript\n * import Stripe from 'stripe';\n * import express from 'express';\n * import { StripeWebhookMiddlewareFactory } from 'express-stripe-webhook-middleware';\n *\n * const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);\n * const factory = new StripeWebhookMiddlewareFactory(\n * process.env.STRIPE_WEBHOOK_SECRET,\n * stripe\n * );\n *\n * const app = express();\n * app.post('/webhook', ...factory.create(), (req, res) => {\n * const event = req.body as Stripe.Event;\n * console.log('Received event:', event.type);\n * res.json({ received: true });\n * });\n * ```\n */\nexport class StripeWebhookMiddlewareFactory {\n private readonly endpointSecret: string;\n private readonly stripe: Stripe;\n private readonly log: Logger;\n private readonly onError?: (error: Error, req: Request, res: Response) => void;\n\n /**\n * Creates a new StripeWebhookMiddlewareFactory instance\n *\n * @param endpointSecret - Stripe webhook secret key (starts with `whsec_`)\n * @param client - Stripe SDK client instance\n * @param options - Optional configuration\n */\n constructor(\n endpointSecret: string,\n client: Stripe,\n options?: StripeWebhookMiddlewareOptions\n ) {\n this.endpointSecret = endpointSecret;\n this.stripe = client;\n this.log = options?.logger ?? console.error;\n this.onError = options?.onError;\n }\n\n /**\n * Creates an array of middleware handlers for Stripe webhook verification\n *\n * Returns an array containing:\n * 1. body-parser middleware to parse raw body\n * 2. Stripe signature verification middleware\n *\n * @returns Array of Express request handlers\n */\n public create(): RequestHandler[] {\n const { endpointSecret, stripe, log, onError } = this;\n\n const rawBodyParser = raw({ type: 'application/json' });\n\n const verifySignature: RequestHandler = (\n req: Request,\n res: Response,\n next: NextFunction\n ): void => {\n const sig = req.headers['stripe-signature'];\n\n if (!sig) {\n const error = new Error('Missing stripe-signature header');\n log(error);\n if (onError) {\n onError(error, req, res);\n return;\n }\n res.status(400).send(`Webhook Error: ${error.message}`);\n return;\n }\n\n try {\n const event = stripe.webhooks.constructEvent(\n req.body as Buffer,\n sig,\n endpointSecret\n );\n req.body = event;\n next();\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n log(error);\n if (onError) {\n onError(error, req, res);\n return;\n }\n res.status(400).send(`Webhook Error: ${error.message}`);\n }\n };\n\n return [rawBodyParser, verifySignature];\n }\n}\n\n/**\n * Creates Stripe webhook verification middleware\n *\n * This is a convenience function that creates a factory and returns the middleware\n *\n * @param endpointSecret - Stripe webhook secret key (starts with `whsec_`)\n * @param client - Stripe SDK client instance\n * @param options - Optional configuration\n * @returns Array of Express request handlers\n *\n * @example\n * ```typescript\n * import Stripe from 'stripe';\n * import express from 'express';\n * import { createStripeWebhookMiddleware } from 'express-stripe-webhook-middleware';\n *\n * const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);\n * const app = express();\n *\n * app.post(\n * '/webhook',\n * ...createStripeWebhookMiddleware(process.env.STRIPE_WEBHOOK_SECRET, stripe),\n * (req, res) => {\n * const event = req.body as Stripe.Event;\n * res.json({ received: true });\n * }\n * );\n * ```\n */\nexport function createStripeWebhookMiddleware(\n endpointSecret: string,\n client: Stripe,\n options?: StripeWebhookMiddlewareOptions\n): RequestHandler[] {\n const factory = new StripeWebhookMiddlewareFactory(\n endpointSecret,\n client,\n options\n );\n return factory.create();\n}\n"],"names":["raw"],"mappings":";;;;;;AA2CO,MAAM,+BAA+B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAa1C,YACE,gBACA,QACA,SACA;AAhBe;AACA;AACA;AACA;AAcf,SAAK,iBAAiB;AACtB,SAAK,SAAS;AACd,SAAK,OAAM,mCAAS,WAAU,QAAQ;AACtC,SAAK,UAAU,mCAAS;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWO,SAA2B;AAChC,UAAM,EAAE,gBAAgB,QAAQ,KAAK,YAAY;AAEjD,UAAM,gBAAgBA,WAAAA,IAAI,EAAE,MAAM,oBAAoB;AAEtD,UAAM,kBAAkC,CACtC,KACA,KACA,SACS;AACT,YAAM,MAAM,IAAI,QAAQ,kBAAkB;AAE1C,UAAI,CAAC,KAAK;AACR,cAAM,QAAQ,IAAI,MAAM,iCAAiC;AACzD,YAAI,KAAK;AACT,YAAI,SAAS;AACX,kBAAQ,OAAO,KAAK,GAAG;AACvB;AAAA,QACF;AACA,YAAI,OAAO,GAAG,EAAE,KAAK,kBAAkB,MAAM,OAAO,EAAE;AACtD;AAAA,MACF;AAEA,UAAI;AACF,cAAM,QAAQ,OAAO,SAAS;AAAA,UAC5B,IAAI;AAAA,UACJ;AAAA,UACA;AAAA,QAAA;AAEF,YAAI,OAAO;AACX,aAAA;AAAA,MACF,SAAS,KAAK;AACZ,cAAM,QAAQ,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAChE,YAAI,KAAK;AACT,YAAI,SAAS;AACX,kBAAQ,OAAO,KAAK,GAAG;AACvB;AAAA,QACF;AACA,YAAI,OAAO,GAAG,EAAE,KAAK,kBAAkB,MAAM,OAAO,EAAE;AAAA,MACxD;AAAA,IACF;AAEA,WAAO,CAAC,eAAe,eAAe;AAAA,EACxC;AACF;AA+BO,SAAS,8BACd,gBACA,QACA,SACkB;AAClB,QAAM,UAAU,IAAI;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEF,SAAO,QAAQ,OAAA;AACjB;;;"}
@@ -0,0 +1,93 @@
1
+ import { default as Stripe } from 'stripe';
2
+ import { Request, RequestHandler, Response } from 'express';
3
+ export type Logger = (message?: unknown, ...optionalParams: unknown[]) => void;
4
+ export interface StripeWebhookMiddlewareOptions {
5
+ /**
6
+ * Custom logger function for error logging
7
+ * @default console.error
8
+ */
9
+ logger?: Logger;
10
+ /**
11
+ * Custom error handler function
12
+ * If not provided, sends a 400 response with the error message
13
+ */
14
+ onError?: (error: Error, req: Request, res: Response) => void;
15
+ }
16
+ /**
17
+ * Factory class for creating Express middleware that verifies Stripe webhook signatures
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * import Stripe from 'stripe';
22
+ * import express from 'express';
23
+ * import { StripeWebhookMiddlewareFactory } from 'express-stripe-webhook-middleware';
24
+ *
25
+ * const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
26
+ * const factory = new StripeWebhookMiddlewareFactory(
27
+ * process.env.STRIPE_WEBHOOK_SECRET,
28
+ * stripe
29
+ * );
30
+ *
31
+ * const app = express();
32
+ * app.post('/webhook', ...factory.create(), (req, res) => {
33
+ * const event = req.body as Stripe.Event;
34
+ * console.log('Received event:', event.type);
35
+ * res.json({ received: true });
36
+ * });
37
+ * ```
38
+ */
39
+ export declare class StripeWebhookMiddlewareFactory {
40
+ private readonly endpointSecret;
41
+ private readonly stripe;
42
+ private readonly log;
43
+ private readonly onError?;
44
+ /**
45
+ * Creates a new StripeWebhookMiddlewareFactory instance
46
+ *
47
+ * @param endpointSecret - Stripe webhook secret key (starts with `whsec_`)
48
+ * @param client - Stripe SDK client instance
49
+ * @param options - Optional configuration
50
+ */
51
+ constructor(endpointSecret: string, client: Stripe, options?: StripeWebhookMiddlewareOptions);
52
+ /**
53
+ * Creates an array of middleware handlers for Stripe webhook verification
54
+ *
55
+ * Returns an array containing:
56
+ * 1. body-parser middleware to parse raw body
57
+ * 2. Stripe signature verification middleware
58
+ *
59
+ * @returns Array of Express request handlers
60
+ */
61
+ create(): RequestHandler[];
62
+ }
63
+ /**
64
+ * Creates Stripe webhook verification middleware
65
+ *
66
+ * This is a convenience function that creates a factory and returns the middleware
67
+ *
68
+ * @param endpointSecret - Stripe webhook secret key (starts with `whsec_`)
69
+ * @param client - Stripe SDK client instance
70
+ * @param options - Optional configuration
71
+ * @returns Array of Express request handlers
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * import Stripe from 'stripe';
76
+ * import express from 'express';
77
+ * import { createStripeWebhookMiddleware } from 'express-stripe-webhook-middleware';
78
+ *
79
+ * const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
80
+ * const app = express();
81
+ *
82
+ * app.post(
83
+ * '/webhook',
84
+ * ...createStripeWebhookMiddleware(process.env.STRIPE_WEBHOOK_SECRET, stripe),
85
+ * (req, res) => {
86
+ * const event = req.body as Stripe.Event;
87
+ * res.json({ received: true });
88
+ * }
89
+ * );
90
+ * ```
91
+ */
92
+ export declare function createStripeWebhookMiddleware(endpointSecret: string, client: Stripe, options?: StripeWebhookMiddlewareOptions): RequestHandler[];
93
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,22 +1,93 @@
1
- import Stripe from 'stripe';
2
- import { NextFunction, Request, Response } from 'express';
3
- export declare type Logger = (message?: any, ...optionalParams: any[]) => void;
4
- export interface StripeWebhookMiddlewareBuilderOptions {
5
- logger?: Logger;
6
- }
7
- export declare class StripeWebhookMiddlewareFactory {
8
- /**
9
- * Stripe Webhook secret key (start from `whsec_`)
10
- */
11
- private readonly endpointSecret;
12
- /**
13
- * Stripe SDK client
14
- */
15
- private readonly stripe;
16
- /**
17
- * Logging function
18
- */
19
- private readonly log;
20
- constructor(endpointSecret: string, client: Stripe, options?: StripeWebhookMiddlewareBuilderOptions);
21
- create(): (req: Request, res: Response, next: NextFunction) => void;
22
- }
1
+ import { default as Stripe } from 'stripe';
2
+ import { Request, RequestHandler, Response } from 'express';
3
+ export type Logger = (message?: unknown, ...optionalParams: unknown[]) => void;
4
+ export interface StripeWebhookMiddlewareOptions {
5
+ /**
6
+ * Custom logger function for error logging
7
+ * @default console.error
8
+ */
9
+ logger?: Logger;
10
+ /**
11
+ * Custom error handler function
12
+ * If not provided, sends a 400 response with the error message
13
+ */
14
+ onError?: (error: Error, req: Request, res: Response) => void;
15
+ }
16
+ /**
17
+ * Factory class for creating Express middleware that verifies Stripe webhook signatures
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * import Stripe from 'stripe';
22
+ * import express from 'express';
23
+ * import { StripeWebhookMiddlewareFactory } from 'express-stripe-webhook-middleware';
24
+ *
25
+ * const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
26
+ * const factory = new StripeWebhookMiddlewareFactory(
27
+ * process.env.STRIPE_WEBHOOK_SECRET,
28
+ * stripe
29
+ * );
30
+ *
31
+ * const app = express();
32
+ * app.post('/webhook', ...factory.create(), (req, res) => {
33
+ * const event = req.body as Stripe.Event;
34
+ * console.log('Received event:', event.type);
35
+ * res.json({ received: true });
36
+ * });
37
+ * ```
38
+ */
39
+ export declare class StripeWebhookMiddlewareFactory {
40
+ private readonly endpointSecret;
41
+ private readonly stripe;
42
+ private readonly log;
43
+ private readonly onError?;
44
+ /**
45
+ * Creates a new StripeWebhookMiddlewareFactory instance
46
+ *
47
+ * @param endpointSecret - Stripe webhook secret key (starts with `whsec_`)
48
+ * @param client - Stripe SDK client instance
49
+ * @param options - Optional configuration
50
+ */
51
+ constructor(endpointSecret: string, client: Stripe, options?: StripeWebhookMiddlewareOptions);
52
+ /**
53
+ * Creates an array of middleware handlers for Stripe webhook verification
54
+ *
55
+ * Returns an array containing:
56
+ * 1. body-parser middleware to parse raw body
57
+ * 2. Stripe signature verification middleware
58
+ *
59
+ * @returns Array of Express request handlers
60
+ */
61
+ create(): RequestHandler[];
62
+ }
63
+ /**
64
+ * Creates Stripe webhook verification middleware
65
+ *
66
+ * This is a convenience function that creates a factory and returns the middleware
67
+ *
68
+ * @param endpointSecret - Stripe webhook secret key (starts with `whsec_`)
69
+ * @param client - Stripe SDK client instance
70
+ * @param options - Optional configuration
71
+ * @returns Array of Express request handlers
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * import Stripe from 'stripe';
76
+ * import express from 'express';
77
+ * import { createStripeWebhookMiddleware } from 'express-stripe-webhook-middleware';
78
+ *
79
+ * const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
80
+ * const app = express();
81
+ *
82
+ * app.post(
83
+ * '/webhook',
84
+ * ...createStripeWebhookMiddleware(process.env.STRIPE_WEBHOOK_SECRET, stripe),
85
+ * (req, res) => {
86
+ * const event = req.body as Stripe.Event;
87
+ * res.json({ received: true });
88
+ * }
89
+ * );
90
+ * ```
91
+ */
92
+ export declare function createStripeWebhookMiddleware(endpointSecret: string, client: Stripe, options?: StripeWebhookMiddlewareOptions): RequestHandler[];
93
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,KAAK,EAAgB,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAG/E,MAAM,MAAM,MAAM,GAAG,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,GAAG,cAAc,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;AAE/E,MAAM,WAAW,8BAA8B;IAC7C;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,KAAK,IAAI,CAAC;CAC/D;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,8BAA8B;IACzC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAsD;IAE/E;;;;;;OAMG;gBAED,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,8BAA8B;IAQ1C;;;;;;;;OAQG;IACI,MAAM,IAAI,cAAc,EAAE;CA4ClC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,6BAA6B,CAC3C,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,8BAA8B,GACvC,cAAc,EAAE,CAOlB"}
package/dist/index.js CHANGED
@@ -1,8 +1,80 @@
1
-
2
- 'use strict'
3
-
4
- if (process.env.NODE_ENV === 'production') {
5
- module.exports = require('./express-stripe-webhook-middleware.cjs.production.min.js')
6
- } else {
7
- module.exports = require('./express-stripe-webhook-middleware.cjs.development.js')
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ import { raw } from "body-parser";
5
+ class StripeWebhookMiddlewareFactory {
6
+ /**
7
+ * Creates a new StripeWebhookMiddlewareFactory instance
8
+ *
9
+ * @param endpointSecret - Stripe webhook secret key (starts with `whsec_`)
10
+ * @param client - Stripe SDK client instance
11
+ * @param options - Optional configuration
12
+ */
13
+ constructor(endpointSecret, client, options) {
14
+ __publicField(this, "endpointSecret");
15
+ __publicField(this, "stripe");
16
+ __publicField(this, "log");
17
+ __publicField(this, "onError");
18
+ this.endpointSecret = endpointSecret;
19
+ this.stripe = client;
20
+ this.log = (options == null ? void 0 : options.logger) ?? console.error;
21
+ this.onError = options == null ? void 0 : options.onError;
22
+ }
23
+ /**
24
+ * Creates an array of middleware handlers for Stripe webhook verification
25
+ *
26
+ * Returns an array containing:
27
+ * 1. body-parser middleware to parse raw body
28
+ * 2. Stripe signature verification middleware
29
+ *
30
+ * @returns Array of Express request handlers
31
+ */
32
+ create() {
33
+ const { endpointSecret, stripe, log, onError } = this;
34
+ const rawBodyParser = raw({ type: "application/json" });
35
+ const verifySignature = (req, res, next) => {
36
+ const sig = req.headers["stripe-signature"];
37
+ if (!sig) {
38
+ const error = new Error("Missing stripe-signature header");
39
+ log(error);
40
+ if (onError) {
41
+ onError(error, req, res);
42
+ return;
43
+ }
44
+ res.status(400).send(`Webhook Error: ${error.message}`);
45
+ return;
46
+ }
47
+ try {
48
+ const event = stripe.webhooks.constructEvent(
49
+ req.body,
50
+ sig,
51
+ endpointSecret
52
+ );
53
+ req.body = event;
54
+ next();
55
+ } catch (err) {
56
+ const error = err instanceof Error ? err : new Error(String(err));
57
+ log(error);
58
+ if (onError) {
59
+ onError(error, req, res);
60
+ return;
61
+ }
62
+ res.status(400).send(`Webhook Error: ${error.message}`);
63
+ }
64
+ };
65
+ return [rawBodyParser, verifySignature];
66
+ }
8
67
  }
68
+ function createStripeWebhookMiddleware(endpointSecret, client, options) {
69
+ const factory = new StripeWebhookMiddlewareFactory(
70
+ endpointSecret,
71
+ client,
72
+ options
73
+ );
74
+ return factory.create();
75
+ }
76
+ export {
77
+ StripeWebhookMiddlewareFactory,
78
+ createStripeWebhookMiddleware
79
+ };
80
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import type Stripe from 'stripe';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { raw } from 'body-parser';\n\nexport type Logger = (message?: unknown, ...optionalParams: unknown[]) => void;\n\nexport interface StripeWebhookMiddlewareOptions {\n /**\n * Custom logger function for error logging\n * @default console.error\n */\n logger?: Logger;\n\n /**\n * Custom error handler function\n * If not provided, sends a 400 response with the error message\n */\n onError?: (error: Error, req: Request, res: Response) => void;\n}\n\n/**\n * Factory class for creating Express middleware that verifies Stripe webhook signatures\n *\n * @example\n * ```typescript\n * import Stripe from 'stripe';\n * import express from 'express';\n * import { StripeWebhookMiddlewareFactory } from 'express-stripe-webhook-middleware';\n *\n * const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);\n * const factory = new StripeWebhookMiddlewareFactory(\n * process.env.STRIPE_WEBHOOK_SECRET,\n * stripe\n * );\n *\n * const app = express();\n * app.post('/webhook', ...factory.create(), (req, res) => {\n * const event = req.body as Stripe.Event;\n * console.log('Received event:', event.type);\n * res.json({ received: true });\n * });\n * ```\n */\nexport class StripeWebhookMiddlewareFactory {\n private readonly endpointSecret: string;\n private readonly stripe: Stripe;\n private readonly log: Logger;\n private readonly onError?: (error: Error, req: Request, res: Response) => void;\n\n /**\n * Creates a new StripeWebhookMiddlewareFactory instance\n *\n * @param endpointSecret - Stripe webhook secret key (starts with `whsec_`)\n * @param client - Stripe SDK client instance\n * @param options - Optional configuration\n */\n constructor(\n endpointSecret: string,\n client: Stripe,\n options?: StripeWebhookMiddlewareOptions\n ) {\n this.endpointSecret = endpointSecret;\n this.stripe = client;\n this.log = options?.logger ?? console.error;\n this.onError = options?.onError;\n }\n\n /**\n * Creates an array of middleware handlers for Stripe webhook verification\n *\n * Returns an array containing:\n * 1. body-parser middleware to parse raw body\n * 2. Stripe signature verification middleware\n *\n * @returns Array of Express request handlers\n */\n public create(): RequestHandler[] {\n const { endpointSecret, stripe, log, onError } = this;\n\n const rawBodyParser = raw({ type: 'application/json' });\n\n const verifySignature: RequestHandler = (\n req: Request,\n res: Response,\n next: NextFunction\n ): void => {\n const sig = req.headers['stripe-signature'];\n\n if (!sig) {\n const error = new Error('Missing stripe-signature header');\n log(error);\n if (onError) {\n onError(error, req, res);\n return;\n }\n res.status(400).send(`Webhook Error: ${error.message}`);\n return;\n }\n\n try {\n const event = stripe.webhooks.constructEvent(\n req.body as Buffer,\n sig,\n endpointSecret\n );\n req.body = event;\n next();\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n log(error);\n if (onError) {\n onError(error, req, res);\n return;\n }\n res.status(400).send(`Webhook Error: ${error.message}`);\n }\n };\n\n return [rawBodyParser, verifySignature];\n }\n}\n\n/**\n * Creates Stripe webhook verification middleware\n *\n * This is a convenience function that creates a factory and returns the middleware\n *\n * @param endpointSecret - Stripe webhook secret key (starts with `whsec_`)\n * @param client - Stripe SDK client instance\n * @param options - Optional configuration\n * @returns Array of Express request handlers\n *\n * @example\n * ```typescript\n * import Stripe from 'stripe';\n * import express from 'express';\n * import { createStripeWebhookMiddleware } from 'express-stripe-webhook-middleware';\n *\n * const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);\n * const app = express();\n *\n * app.post(\n * '/webhook',\n * ...createStripeWebhookMiddleware(process.env.STRIPE_WEBHOOK_SECRET, stripe),\n * (req, res) => {\n * const event = req.body as Stripe.Event;\n * res.json({ received: true });\n * }\n * );\n * ```\n */\nexport function createStripeWebhookMiddleware(\n endpointSecret: string,\n client: Stripe,\n options?: StripeWebhookMiddlewareOptions\n): RequestHandler[] {\n const factory = new StripeWebhookMiddlewareFactory(\n endpointSecret,\n client,\n options\n );\n return factory.create();\n}\n"],"names":[],"mappings":";;;;AA2CO,MAAM,+BAA+B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAa1C,YACE,gBACA,QACA,SACA;AAhBe;AACA;AACA;AACA;AAcf,SAAK,iBAAiB;AACtB,SAAK,SAAS;AACd,SAAK,OAAM,mCAAS,WAAU,QAAQ;AACtC,SAAK,UAAU,mCAAS;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWO,SAA2B;AAChC,UAAM,EAAE,gBAAgB,QAAQ,KAAK,YAAY;AAEjD,UAAM,gBAAgB,IAAI,EAAE,MAAM,oBAAoB;AAEtD,UAAM,kBAAkC,CACtC,KACA,KACA,SACS;AACT,YAAM,MAAM,IAAI,QAAQ,kBAAkB;AAE1C,UAAI,CAAC,KAAK;AACR,cAAM,QAAQ,IAAI,MAAM,iCAAiC;AACzD,YAAI,KAAK;AACT,YAAI,SAAS;AACX,kBAAQ,OAAO,KAAK,GAAG;AACvB;AAAA,QACF;AACA,YAAI,OAAO,GAAG,EAAE,KAAK,kBAAkB,MAAM,OAAO,EAAE;AACtD;AAAA,MACF;AAEA,UAAI;AACF,cAAM,QAAQ,OAAO,SAAS;AAAA,UAC5B,IAAI;AAAA,UACJ;AAAA,UACA;AAAA,QAAA;AAEF,YAAI,OAAO;AACX,aAAA;AAAA,MACF,SAAS,KAAK;AACZ,cAAM,QAAQ,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAChE,YAAI,KAAK;AACT,YAAI,SAAS;AACX,kBAAQ,OAAO,KAAK,GAAG;AACvB;AAAA,QACF;AACA,YAAI,OAAO,GAAG,EAAE,KAAK,kBAAkB,MAAM,OAAO,EAAE;AAAA,MACxD;AAAA,IACF;AAEA,WAAO,CAAC,eAAe,eAAe;AAAA,EACxC;AACF;AA+BO,SAAS,8BACd,gBACA,QACA,SACkB;AAClB,QAAM,UAAU,IAAI;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEF,SAAO,QAAQ,OAAA;AACjB;"}
package/package.json CHANGED
@@ -1,27 +1,85 @@
1
1
  {
2
- "version": "0.1.0",
2
+ "name": "express-stripe-webhook-middleware",
3
+ "version": "1.0.1",
4
+ "description": "Express middleware for Stripe webhook signature verification",
3
5
  "license": "MIT",
4
- "main": "dist/index.js",
5
- "typings": "dist/index.d.ts",
6
+ "author": "Hidetaka Okamoto",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/hideokamoto/express-stripe-webhook-middleware.git"
10
+ },
11
+ "homepage": "https://github.com/hideokamoto/express-stripe-webhook-middleware#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/hideokamoto/express-stripe-webhook-middleware/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.cjs",
17
+ "module": "./dist/index.js",
18
+ "types": "./dist/index.d.cts",
19
+ "exports": {
20
+ ".": {
21
+ "import": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ },
25
+ "require": {
26
+ "types": "./dist/index.d.cts",
27
+ "default": "./dist/index.cjs"
28
+ }
29
+ }
30
+ },
6
31
  "files": [
7
- "dist",
8
- "src"
32
+ "dist"
9
33
  ],
10
34
  "engines": {
11
- "node": ">=10"
35
+ "node": ">=18"
12
36
  },
13
37
  "scripts": {
14
- "start": "tsdx watch",
15
- "build": "tsdx build",
16
- "test": "tsdx test",
17
- "lint": "tsdx lint",
18
- "prepare": "tsdx build"
19
- },
20
- "peerDependencies": {},
21
- "husky": {
22
- "hooks": {
23
- "pre-commit": "tsdx lint"
24
- }
38
+ "dev": "vite build --watch",
39
+ "build": "tsc && vite build",
40
+ "test": "vitest run",
41
+ "test:watch": "vitest",
42
+ "test:coverage": "vitest run --coverage",
43
+ "lint": "eslint src --ext .ts",
44
+ "lint:fix": "eslint src --ext .ts --fix",
45
+ "typecheck": "tsc --noEmit",
46
+ "prepare": "npm run build",
47
+ "prepublishOnly": "npm run lint && npm run typecheck && npm run test",
48
+ "release": "np"
49
+ },
50
+ "keywords": [
51
+ "stripe",
52
+ "webhook",
53
+ "express",
54
+ "middleware",
55
+ "signature",
56
+ "verification"
57
+ ],
58
+ "dependencies": {
59
+ "body-parser": "^1.20.3"
60
+ },
61
+ "peerDependencies": {
62
+ "express": "^4.18.0 || ^5.0.0",
63
+ "stripe": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
64
+ },
65
+ "devDependencies": {
66
+ "@eslint/js": "^9.39.1",
67
+ "@types/body-parser": "^1.19.5",
68
+ "@types/express": "^5.0.0",
69
+ "@types/node": "^22.10.2",
70
+ "@types/supertest": "^6.0.2",
71
+ "@typescript-eslint/eslint-plugin": "^8.18.2",
72
+ "@typescript-eslint/parser": "^8.18.2",
73
+ "@vitest/coverage-v8": "^2.1.8",
74
+ "eslint": "^9.17.0",
75
+ "express": "^4.21.2",
76
+ "np": "^10.2.0",
77
+ "stripe": "^17.5.0",
78
+ "supertest": "^7.0.0",
79
+ "typescript": "^5.7.2",
80
+ "vite": "^6.0.3",
81
+ "vite-plugin-dts": "^4.3.0",
82
+ "vitest": "^2.1.8"
25
83
  },
26
84
  "prettier": {
27
85
  "printWidth": 80,
@@ -29,21 +87,11 @@
29
87
  "singleQuote": true,
30
88
  "trailingComma": "es5"
31
89
  },
32
- "name": "express-stripe-webhook-middleware",
33
- "author": "Hidetaka Okamoto",
34
- "module": "dist/express-stripe-webhook-middleware.esm.js",
35
- "devDependencies": {
36
- "@types/express": "^4.17.13",
37
- "@types/supertest": "^2.0.11",
38
- "husky": "^7.0.1",
39
- "middleware-supertest": "^0.8.9",
40
- "supertest": "^6.1.3",
41
- "tsdx": "^0.14.1",
42
- "tslib": "^2.3.0",
43
- "typescript": "^4.3.5"
90
+ "np": {
91
+ "yarn": false,
92
+ "contents": ".",
93
+ "tests": true,
94
+ "2fa": true
44
95
  },
45
- "dependencies": {
46
- "express": "^4.17.1",
47
- "stripe": "^8.160.0"
48
- }
96
+ "packageManager": "pnpm@10.34.9"
49
97
  }
@@ -1,44 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var StripeWebhookMiddlewareFactory = /*#__PURE__*/function () {
6
- function StripeWebhookMiddlewareFactory(endpointSecret, client, options) {
7
- this.endpointSecret = endpointSecret;
8
- this.stripe = client;
9
- this.log = options && options.logger ? options.logger : console.log;
10
- }
11
-
12
- var _proto = StripeWebhookMiddlewareFactory.prototype;
13
-
14
- _proto.create = function create() {
15
- var endpointSecret = this.endpointSecret,
16
- stripe = this.stripe,
17
- log = this.log;
18
- return function (req, res, next) {
19
- var data = '';
20
- req.setEncoding('utf8');
21
- req.on('data', function (chunk) {
22
- data += chunk;
23
- });
24
- req.on('end', function () {
25
- req.body = data;
26
- var payload = req.body;
27
- var sig = req.headers['stripe-signature'];
28
-
29
- try {
30
- req.body = stripe.webhooks.constructEvent(payload, sig, endpointSecret);
31
- next();
32
- } catch (err) {
33
- log(err);
34
- res.status(400).send("Webhook Error: " + err.message);
35
- }
36
- });
37
- };
38
- };
39
-
40
- return StripeWebhookMiddlewareFactory;
41
- }();
42
-
43
- exports.StripeWebhookMiddlewareFactory = StripeWebhookMiddlewareFactory;
44
- //# sourceMappingURL=express-stripe-webhook-middleware.cjs.development.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"express-stripe-webhook-middleware.cjs.development.js","sources":["../src/index.ts"],"sourcesContent":["import Stripe from 'stripe';\nimport { NextFunction, Request, Response } from 'express';\n\nexport type Logger = (message?: any, ...optionalParams: any[]) => void;\nexport interface StripeWebhookMiddlewareBuilderOptions {\n logger?: Logger;\n}\n\nexport class StripeWebhookMiddlewareFactory {\n /**\n * Stripe Webhook secret key (start from `whsec_`)\n */\n private readonly endpointSecret: string;\n\n /**\n * Stripe SDK client\n */\n private readonly stripe: Stripe;\n\n /**\n * Logging function\n */\n private readonly log: Logger;\n\n constructor(\n endpointSecret: string,\n client: Stripe,\n options?: StripeWebhookMiddlewareBuilderOptions\n ) {\n this.endpointSecret = endpointSecret;\n this.stripe = client;\n this.log = options && options.logger ? options.logger : console.log;\n }\n\n public create() {\n const { endpointSecret, stripe, log } = this;\n return (req: Request, res: Response, next: NextFunction) => {\n var data = '';\n req.setEncoding('utf8');\n req.on('data', function(chunk) {\n data += chunk;\n });\n\n req.on('end', function() {\n req.body = data;\n const payload = req.body;\n const sig = req.headers['stripe-signature'];\n try {\n req.body = stripe.webhooks.constructEvent(\n payload,\n sig as string,\n endpointSecret\n );\n next();\n } catch (err) {\n log(err);\n res.status(400).send(`Webhook Error: ${err.message}`);\n }\n });\n };\n }\n}\n"],"names":["StripeWebhookMiddlewareFactory","endpointSecret","client","options","stripe","log","logger","console","create","req","res","next","data","setEncoding","on","chunk","body","payload","sig","headers","webhooks","constructEvent","err","status","send","message"],"mappings":";;;;IAQaA,8BAAb;AAgBE,0CACEC,cADF,EAEEC,MAFF,EAGEC,OAHF;AAKE,SAAKF,cAAL,GAAsBA,cAAtB;AACA,SAAKG,MAAL,GAAcF,MAAd;AACA,SAAKG,GAAL,GAAWF,OAAO,IAAIA,OAAO,CAACG,MAAnB,GAA4BH,OAAO,CAACG,MAApC,GAA6CC,OAAO,CAACF,GAAhE;AACD;;AAxBH;;AAAA,SA0BSG,MA1BT,GA0BS;AACL,QAAQP,cAAR,GAAwC,IAAxC,CAAQA,cAAR;AAAA,QAAwBG,MAAxB,GAAwC,IAAxC,CAAwBA,MAAxB;AAAA,QAAgCC,GAAhC,GAAwC,IAAxC,CAAgCA,GAAhC;AACA,WAAO,UAACI,GAAD,EAAeC,GAAf,EAA8BC,IAA9B;AACL,UAAIC,IAAI,GAAG,EAAX;AACAH,MAAAA,GAAG,CAACI,WAAJ,CAAgB,MAAhB;AACAJ,MAAAA,GAAG,CAACK,EAAJ,CAAO,MAAP,EAAe,UAASC,KAAT;AACbH,QAAAA,IAAI,IAAIG,KAAR;AACD,OAFD;AAIAN,MAAAA,GAAG,CAACK,EAAJ,CAAO,KAAP,EAAc;AACZL,QAAAA,GAAG,CAACO,IAAJ,GAAWJ,IAAX;AACA,YAAMK,OAAO,GAAGR,GAAG,CAACO,IAApB;AACA,YAAME,GAAG,GAAGT,GAAG,CAACU,OAAJ,CAAY,kBAAZ,CAAZ;;AACA,YAAI;AACFV,UAAAA,GAAG,CAACO,IAAJ,GAAWZ,MAAM,CAACgB,QAAP,CAAgBC,cAAhB,CACTJ,OADS,EAETC,GAFS,EAGTjB,cAHS,CAAX;AAKAU,UAAAA,IAAI;AACL,SAPD,CAOE,OAAOW,GAAP,EAAY;AACZjB,UAAAA,GAAG,CAACiB,GAAD,CAAH;AACAZ,UAAAA,GAAG,CAACa,MAAJ,CAAW,GAAX,EAAgBC,IAAhB,qBAAuCF,GAAG,CAACG,OAA3C;AACD;AACF,OAfD;AAgBD,KAvBD;AAwBD,GApDH;;AAAA;AAAA;;;;"}
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StripeWebhookMiddlewareFactory=function(){function t(t,e,o){this.endpointSecret=t,this.stripe=e,this.log=o&&o.logger?o.logger:console.log}return t.prototype.create=function(){var t=this.endpointSecret,e=this.stripe,o=this.log;return function(r,n,s){var i="";r.setEncoding("utf8"),r.on("data",(function(t){i+=t})),r.on("end",(function(){r.body=i;var c=r.body,u=r.headers["stripe-signature"];try{r.body=e.webhooks.constructEvent(c,u,t),s()}catch(t){o(t),n.status(400).send("Webhook Error: "+t.message)}}))}},t}();
2
- //# sourceMappingURL=express-stripe-webhook-middleware.cjs.production.min.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"express-stripe-webhook-middleware.cjs.production.min.js","sources":["../src/index.ts"],"sourcesContent":["import Stripe from 'stripe';\nimport { NextFunction, Request, Response } from 'express';\n\nexport type Logger = (message?: any, ...optionalParams: any[]) => void;\nexport interface StripeWebhookMiddlewareBuilderOptions {\n logger?: Logger;\n}\n\nexport class StripeWebhookMiddlewareFactory {\n /**\n * Stripe Webhook secret key (start from `whsec_`)\n */\n private readonly endpointSecret: string;\n\n /**\n * Stripe SDK client\n */\n private readonly stripe: Stripe;\n\n /**\n * Logging function\n */\n private readonly log: Logger;\n\n constructor(\n endpointSecret: string,\n client: Stripe,\n options?: StripeWebhookMiddlewareBuilderOptions\n ) {\n this.endpointSecret = endpointSecret;\n this.stripe = client;\n this.log = options && options.logger ? options.logger : console.log;\n }\n\n public create() {\n const { endpointSecret, stripe, log } = this;\n return (req: Request, res: Response, next: NextFunction) => {\n var data = '';\n req.setEncoding('utf8');\n req.on('data', function(chunk) {\n data += chunk;\n });\n\n req.on('end', function() {\n req.body = data;\n const payload = req.body;\n const sig = req.headers['stripe-signature'];\n try {\n req.body = stripe.webhooks.constructEvent(\n payload,\n sig as string,\n endpointSecret\n );\n next();\n } catch (err) {\n log(err);\n res.status(400).send(`Webhook Error: ${err.message}`);\n }\n });\n };\n }\n}\n"],"names":["endpointSecret","client","options","stripe","log","logger","console","create","this","req","res","next","data","setEncoding","on","chunk","body","payload","sig","headers","webhooks","constructEvent","err","status","send","message"],"mappings":"iIAyBIA,EACAC,EACAC,QAEKF,eAAiBA,OACjBG,OAASF,OACTG,IAAMF,GAAWA,EAAQG,OAASH,EAAQG,OAASC,QAAQF,uBAG3DG,OAAA,eACGP,EAAgCQ,KAAhCR,eAAgBG,EAAgBK,KAAhBL,OAAQC,EAAQI,KAARJ,WACzB,SAACK,EAAcC,EAAeC,OAC/BC,EAAO,GACXH,EAAII,YAAY,QAChBJ,EAAIK,GAAG,QAAQ,SAASC,GACtBH,GAAQG,KAGVN,EAAIK,GAAG,OAAO,WACZL,EAAIO,KAAOJ,MACLK,EAAUR,EAAIO,KACdE,EAAMT,EAAIU,QAAQ,wBAEtBV,EAAIO,KAAOb,EAAOiB,SAASC,eACzBJ,EACAC,EACAlB,GAEFW,IACA,MAAOW,GACPlB,EAAIkB,GACJZ,EAAIa,OAAO,KAAKC,uBAAuBF,EAAIG"}
@@ -1,40 +0,0 @@
1
- var StripeWebhookMiddlewareFactory = /*#__PURE__*/function () {
2
- function StripeWebhookMiddlewareFactory(endpointSecret, client, options) {
3
- this.endpointSecret = endpointSecret;
4
- this.stripe = client;
5
- this.log = options && options.logger ? options.logger : console.log;
6
- }
7
-
8
- var _proto = StripeWebhookMiddlewareFactory.prototype;
9
-
10
- _proto.create = function create() {
11
- var endpointSecret = this.endpointSecret,
12
- stripe = this.stripe,
13
- log = this.log;
14
- return function (req, res, next) {
15
- var data = '';
16
- req.setEncoding('utf8');
17
- req.on('data', function (chunk) {
18
- data += chunk;
19
- });
20
- req.on('end', function () {
21
- req.body = data;
22
- var payload = req.body;
23
- var sig = req.headers['stripe-signature'];
24
-
25
- try {
26
- req.body = stripe.webhooks.constructEvent(payload, sig, endpointSecret);
27
- next();
28
- } catch (err) {
29
- log(err);
30
- res.status(400).send("Webhook Error: " + err.message);
31
- }
32
- });
33
- };
34
- };
35
-
36
- return StripeWebhookMiddlewareFactory;
37
- }();
38
-
39
- export { StripeWebhookMiddlewareFactory };
40
- //# sourceMappingURL=express-stripe-webhook-middleware.esm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"express-stripe-webhook-middleware.esm.js","sources":["../src/index.ts"],"sourcesContent":["import Stripe from 'stripe';\nimport { NextFunction, Request, Response } from 'express';\n\nexport type Logger = (message?: any, ...optionalParams: any[]) => void;\nexport interface StripeWebhookMiddlewareBuilderOptions {\n logger?: Logger;\n}\n\nexport class StripeWebhookMiddlewareFactory {\n /**\n * Stripe Webhook secret key (start from `whsec_`)\n */\n private readonly endpointSecret: string;\n\n /**\n * Stripe SDK client\n */\n private readonly stripe: Stripe;\n\n /**\n * Logging function\n */\n private readonly log: Logger;\n\n constructor(\n endpointSecret: string,\n client: Stripe,\n options?: StripeWebhookMiddlewareBuilderOptions\n ) {\n this.endpointSecret = endpointSecret;\n this.stripe = client;\n this.log = options && options.logger ? options.logger : console.log;\n }\n\n public create() {\n const { endpointSecret, stripe, log } = this;\n return (req: Request, res: Response, next: NextFunction) => {\n var data = '';\n req.setEncoding('utf8');\n req.on('data', function(chunk) {\n data += chunk;\n });\n\n req.on('end', function() {\n req.body = data;\n const payload = req.body;\n const sig = req.headers['stripe-signature'];\n try {\n req.body = stripe.webhooks.constructEvent(\n payload,\n sig as string,\n endpointSecret\n );\n next();\n } catch (err) {\n log(err);\n res.status(400).send(`Webhook Error: ${err.message}`);\n }\n });\n };\n }\n}\n"],"names":["StripeWebhookMiddlewareFactory","endpointSecret","client","options","stripe","log","logger","console","create","req","res","next","data","setEncoding","on","chunk","body","payload","sig","headers","webhooks","constructEvent","err","status","send","message"],"mappings":"IAQaA,8BAAb;AAgBE,0CACEC,cADF,EAEEC,MAFF,EAGEC,OAHF;AAKE,SAAKF,cAAL,GAAsBA,cAAtB;AACA,SAAKG,MAAL,GAAcF,MAAd;AACA,SAAKG,GAAL,GAAWF,OAAO,IAAIA,OAAO,CAACG,MAAnB,GAA4BH,OAAO,CAACG,MAApC,GAA6CC,OAAO,CAACF,GAAhE;AACD;;AAxBH;;AAAA,SA0BSG,MA1BT,GA0BS;AACL,QAAQP,cAAR,GAAwC,IAAxC,CAAQA,cAAR;AAAA,QAAwBG,MAAxB,GAAwC,IAAxC,CAAwBA,MAAxB;AAAA,QAAgCC,GAAhC,GAAwC,IAAxC,CAAgCA,GAAhC;AACA,WAAO,UAACI,GAAD,EAAeC,GAAf,EAA8BC,IAA9B;AACL,UAAIC,IAAI,GAAG,EAAX;AACAH,MAAAA,GAAG,CAACI,WAAJ,CAAgB,MAAhB;AACAJ,MAAAA,GAAG,CAACK,EAAJ,CAAO,MAAP,EAAe,UAASC,KAAT;AACbH,QAAAA,IAAI,IAAIG,KAAR;AACD,OAFD;AAIAN,MAAAA,GAAG,CAACK,EAAJ,CAAO,KAAP,EAAc;AACZL,QAAAA,GAAG,CAACO,IAAJ,GAAWJ,IAAX;AACA,YAAMK,OAAO,GAAGR,GAAG,CAACO,IAApB;AACA,YAAME,GAAG,GAAGT,GAAG,CAACU,OAAJ,CAAY,kBAAZ,CAAZ;;AACA,YAAI;AACFV,UAAAA,GAAG,CAACO,IAAJ,GAAWZ,MAAM,CAACgB,QAAP,CAAgBC,cAAhB,CACTJ,OADS,EAETC,GAFS,EAGTjB,cAHS,CAAX;AAKAU,UAAAA,IAAI;AACL,SAPD,CAOE,OAAOW,GAAP,EAAY;AACZjB,UAAAA,GAAG,CAACiB,GAAD,CAAH;AACAZ,UAAAA,GAAG,CAACa,MAAJ,CAAW,GAAX,EAAgBC,IAAhB,qBAAuCF,GAAG,CAACG,OAA3C;AACD;AACF,OAfD;AAgBD,KAvBD;AAwBD,GApDH;;AAAA;AAAA;;;;"}
package/src/index.ts DELETED
@@ -1,62 +0,0 @@
1
- import Stripe from 'stripe';
2
- import { NextFunction, Request, Response } from 'express';
3
-
4
- export type Logger = (message?: any, ...optionalParams: any[]) => void;
5
- export interface StripeWebhookMiddlewareBuilderOptions {
6
- logger?: Logger;
7
- }
8
-
9
- export class StripeWebhookMiddlewareFactory {
10
- /**
11
- * Stripe Webhook secret key (start from `whsec_`)
12
- */
13
- private readonly endpointSecret: string;
14
-
15
- /**
16
- * Stripe SDK client
17
- */
18
- private readonly stripe: Stripe;
19
-
20
- /**
21
- * Logging function
22
- */
23
- private readonly log: Logger;
24
-
25
- constructor(
26
- endpointSecret: string,
27
- client: Stripe,
28
- options?: StripeWebhookMiddlewareBuilderOptions
29
- ) {
30
- this.endpointSecret = endpointSecret;
31
- this.stripe = client;
32
- this.log = options && options.logger ? options.logger : console.log;
33
- }
34
-
35
- public create() {
36
- const { endpointSecret, stripe, log } = this;
37
- return (req: Request, res: Response, next: NextFunction) => {
38
- var data = '';
39
- req.setEncoding('utf8');
40
- req.on('data', function(chunk) {
41
- data += chunk;
42
- });
43
-
44
- req.on('end', function() {
45
- req.body = data;
46
- const payload = req.body;
47
- const sig = req.headers['stripe-signature'];
48
- try {
49
- req.body = stripe.webhooks.constructEvent(
50
- payload,
51
- sig as string,
52
- endpointSecret
53
- );
54
- next();
55
- } catch (err) {
56
- log(err);
57
- res.status(400).send(`Webhook Error: ${err.message}`);
58
- }
59
- });
60
- };
61
- }
62
- }