express-stripe-webhook-middleware 0.1.0 โ 1.0.0
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 +231 -152
- package/dist/index.cjs +80 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +93 -22
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +79 -7
- package/dist/index.js.map +1 -0
- package/package.json +65 -32
- package/dist/express-stripe-webhook-middleware.cjs.development.js +0 -44
- package/dist/express-stripe-webhook-middleware.cjs.development.js.map +0 -1
- package/dist/express-stripe-webhook-middleware.cjs.production.min.js +0 -2
- package/dist/express-stripe-webhook-middleware.cjs.production.min.js.map +0 -1
- package/dist/express-stripe-webhook-middleware.esm.js +0 -40
- package/dist/express-stripe-webhook-middleware.esm.js.map +0 -1
- package/src/index.ts +0 -62
package/README.md
CHANGED
|
@@ -1,224 +1,303 @@
|
|
|
1
1
|
# Express Stripe Webhook Middleware
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/express-stripe-webhook-middleware)
|
|
4
|
+
[](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
|
-
##
|
|
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
|
-
|
|
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
|
|
10
25
|
```
|
|
11
26
|
|
|
12
|
-
##
|
|
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'));
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### JavaScript (CommonJS)
|
|
13
65
|
|
|
14
66
|
```javascript
|
|
15
67
|
const Stripe = require('stripe');
|
|
16
68
|
const express = require('express');
|
|
17
|
-
const {
|
|
18
|
-
|
|
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
|
|
21
|
-
|
|
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
|
-
|
|
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
|
-
|
|
128
|
+
### Custom Logger
|
|
53
129
|
|
|
54
|
-
|
|
55
|
-
|
|
130
|
+
```typescript
|
|
131
|
+
import pino from 'pino';
|
|
56
132
|
|
|
57
|
-
|
|
133
|
+
const logger = pino();
|
|
58
134
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
73
|
-
|
|
148
|
+
### Without This Package
|
|
149
|
+
|
|
150
|
+
Following Stripe's official example, you need to manually set up body parsing and signature verification:
|
|
74
151
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
152
|
+
```javascript
|
|
153
|
+
const stripe = require('stripe')('sk_test_...');
|
|
154
|
+
const bodyParser = require('body-parser');
|
|
155
|
+
const app = require('express')();
|
|
78
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(
|
|
83
|
-
}
|
|
84
|
-
|
|
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
|
-
|
|
92
|
-
console.log('PaymentIntent was successful!');
|
|
170
|
+
console.log('PaymentIntent succeeded!');
|
|
93
171
|
break;
|
|
94
|
-
|
|
95
|
-
const paymentMethod = event.data.object;
|
|
96
|
-
console.log('PaymentMethod was attached to a Customer!');
|
|
97
|
-
break;
|
|
98
|
-
// ... handle other event types
|
|
99
|
-
default:
|
|
100
|
-
console.log(`Unhandled event type ${event.type}`);
|
|
172
|
+
// ... more cases
|
|
101
173
|
}
|
|
102
174
|
|
|
103
|
-
|
|
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
|
-
|
|
179
|
+
### With This Package
|
|
111
180
|
|
|
112
|
-
|
|
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
|
-
|
|
119
|
-
|
|
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
|
-
|
|
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
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
app.listen(4242, () => console.log('Running on port 4242'));
|
|
197
|
+
|
|
198
|
+
res.json({ received: true });
|
|
199
|
+
}
|
|
200
|
+
);
|
|
146
201
|
```
|
|
147
202
|
|
|
148
|
-
##
|
|
203
|
+
## API Reference
|
|
149
204
|
|
|
150
|
-
|
|
205
|
+
### `createStripeWebhookMiddleware(endpointSecret, stripe, options?)`
|
|
151
206
|
|
|
152
|
-
|
|
207
|
+
Convenience function that creates and returns the middleware array.
|
|
153
208
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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
|
-
|
|
216
|
+
**Returns:** `RequestHandler[]` - Array of Express middleware
|
|
161
217
|
|
|
162
|
-
|
|
218
|
+
### `StripeWebhookMiddlewareFactory`
|
|
163
219
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
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
|
-
|
|
231
|
+
**Methods:**
|
|
232
|
+
- `create()`: Returns `RequestHandler[]`
|
|
170
233
|
|
|
171
|
-
|
|
234
|
+
## Testing Your Webhooks
|
|
172
235
|
|
|
173
|
-
|
|
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
|
-
|
|
238
|
+
1. Install [Stripe CLI](https://stripe.com/docs/stripe-cli)
|
|
180
239
|
|
|
181
|
-
|
|
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
|
-
|
|
247
|
+
stripe trigger payment_intent.succeeded
|
|
185
248
|
```
|
|
186
249
|
|
|
187
|
-
###
|
|
250
|
+
### Example Test Server
|
|
188
251
|
|
|
189
|
-
|
|
252
|
+
```typescript
|
|
253
|
+
import Stripe from 'stripe';
|
|
254
|
+
import express from 'express';
|
|
255
|
+
import { createStripeWebhookMiddleware } from 'express-stripe-webhook-middleware';
|
|
190
256
|
|
|
191
|
-
|
|
192
|
-
|
|
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
|
-
|
|
275
|
+
## Requirements
|
|
196
276
|
|
|
197
|
-
|
|
277
|
+
- Node.js >= 18
|
|
278
|
+
- Express ^4.18.0 || ^5.0.0
|
|
279
|
+
- Stripe SDK ^14.0.0 || newer
|
|
198
280
|
|
|
199
|
-
|
|
200
|
-
$ stripe trigger payment_intent.created
|
|
201
|
-
```
|
|
281
|
+
## Contributing
|
|
202
282
|
|
|
203
|
-
|
|
283
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
204
284
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
```
|
|
285
|
+
## License
|
|
286
|
+
|
|
287
|
+
MIT ยฉ [Hidetaka Okamoto](https://github.com/hideokamoto)
|
|
288
|
+
|
|
289
|
+
## Changelog
|
|
290
|
+
|
|
291
|
+
### v0.2.0
|
|
292
|
+
- ๐ Migrated from TSDX to Vite
|
|
293
|
+
- ๐ฆ Updated to latest dependencies (Stripe SDK v17+, TypeScript 5.7)
|
|
294
|
+
- โจ Added `createStripeWebhookMiddleware` helper function
|
|
295
|
+
- ๐ง Added custom error handler support via `onError` option
|
|
296
|
+
- ๐ฏ Improved type safety with strict TypeScript settings
|
|
297
|
+
- โ
Enhanced test coverage with Vitest
|
|
298
|
+
- ๐ Comprehensive JSDoc documentation
|
|
299
|
+
- โก Better error handling for missing signatures
|
|
300
|
+
- ๐ Now exports both ESM and CommonJS formats
|
|
301
|
+
|
|
302
|
+
### v0.1.0
|
|
303
|
+
- 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;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,22 +1,93 @@
|
|
|
1
|
-
import Stripe from 'stripe';
|
|
2
|
-
import {
|
|
3
|
-
export
|
|
4
|
-
export interface
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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,71 @@
|
|
|
1
1
|
{
|
|
2
|
-
"
|
|
2
|
+
"name": "express-stripe-webhook-middleware",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Express middleware for Stripe webhook signature verification",
|
|
3
5
|
"license": "MIT",
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
+
"author": "Hidetaka Okamoto",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/index.cjs",
|
|
9
|
+
"module": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js",
|
|
15
|
+
"require": "./dist/index.cjs"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
6
18
|
"files": [
|
|
7
|
-
"dist"
|
|
8
|
-
"src"
|
|
19
|
+
"dist"
|
|
9
20
|
],
|
|
10
21
|
"engines": {
|
|
11
|
-
"node": ">=
|
|
22
|
+
"node": ">=18"
|
|
12
23
|
},
|
|
13
24
|
"scripts": {
|
|
14
|
-
"
|
|
15
|
-
"build": "
|
|
16
|
-
"test": "
|
|
17
|
-
"
|
|
18
|
-
"
|
|
25
|
+
"dev": "vite build --watch",
|
|
26
|
+
"build": "tsc && vite build",
|
|
27
|
+
"test": "vitest run",
|
|
28
|
+
"test:watch": "vitest",
|
|
29
|
+
"test:coverage": "vitest run --coverage",
|
|
30
|
+
"lint": "eslint src --ext .ts",
|
|
31
|
+
"lint:fix": "eslint src --ext .ts --fix",
|
|
32
|
+
"type-check": "tsc --noEmit",
|
|
33
|
+
"prepare": "npm run build",
|
|
34
|
+
"prepublishOnly": "npm run lint && npm run type-check && npm run test",
|
|
35
|
+
"release": "np"
|
|
19
36
|
},
|
|
20
|
-
"
|
|
21
|
-
|
|
22
|
-
"
|
|
23
|
-
|
|
24
|
-
|
|
37
|
+
"keywords": [
|
|
38
|
+
"stripe",
|
|
39
|
+
"webhook",
|
|
40
|
+
"express",
|
|
41
|
+
"middleware",
|
|
42
|
+
"signature",
|
|
43
|
+
"verification"
|
|
44
|
+
],
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"body-parser": "^1.20.3"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"express": "^4.18.0 || ^5.0.0",
|
|
50
|
+
"stripe": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@types/body-parser": "^1.19.5",
|
|
54
|
+
"@types/express": "^5.0.0",
|
|
55
|
+
"@types/node": "^22.10.2",
|
|
56
|
+
"@types/supertest": "^6.0.2",
|
|
57
|
+
"@typescript-eslint/eslint-plugin": "^8.18.2",
|
|
58
|
+
"@typescript-eslint/parser": "^8.18.2",
|
|
59
|
+
"@vitest/coverage-v8": "^2.1.8",
|
|
60
|
+
"eslint": "^9.17.0",
|
|
61
|
+
"express": "^4.21.2",
|
|
62
|
+
"np": "^10.2.0",
|
|
63
|
+
"stripe": "^17.5.0",
|
|
64
|
+
"supertest": "^7.0.0",
|
|
65
|
+
"typescript": "^5.7.2",
|
|
66
|
+
"vite": "^6.0.3",
|
|
67
|
+
"vite-plugin-dts": "^4.3.0",
|
|
68
|
+
"vitest": "^2.1.8"
|
|
25
69
|
},
|
|
26
70
|
"prettier": {
|
|
27
71
|
"printWidth": 80,
|
|
@@ -29,21 +73,10 @@
|
|
|
29
73
|
"singleQuote": true,
|
|
30
74
|
"trailingComma": "es5"
|
|
31
75
|
},
|
|
32
|
-
"
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
"
|
|
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"
|
|
44
|
-
},
|
|
45
|
-
"dependencies": {
|
|
46
|
-
"express": "^4.17.1",
|
|
47
|
-
"stripe": "^8.160.0"
|
|
76
|
+
"np": {
|
|
77
|
+
"yarn": false,
|
|
78
|
+
"contents": ".",
|
|
79
|
+
"tests": true,
|
|
80
|
+
"2fa": true
|
|
48
81
|
}
|
|
49
82
|
}
|
|
@@ -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
|
-
}
|