@paykit-sdk/stripe 1.1.7 → 1.1.92

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
@@ -5,7 +5,7 @@ Stripe provider for PayKit
5
5
  ## Quick Start
6
6
 
7
7
  ```typescript
8
- import { PayKit } from '@paykit-sdk/core';
8
+ import { createEndpointHandlers, PayKit } from '@paykit-sdk/core';
9
9
  import { stripe, createStripe } from '@paykit-sdk/stripe';
10
10
 
11
11
  // Method 1: Using environment variables
@@ -17,138 +17,168 @@ const provider = createStripe({
17
17
  apiVersion: '2024-12-18.acacia',
18
18
  });
19
19
 
20
- const paykit = new PayKit(provider);
21
-
22
- // Create checkout
23
- const checkout = await paykit.checkouts.create({
24
- customer_id: 'cus_123',
25
- item_id: 'price_123',
26
- session_type: 'one_time',
27
- metadata: { plan: 'pro' },
28
- provider_metadata: {
29
- ui_mode: 'hosted',
30
- success_url: 'https://your-app.com/success',
31
- },
32
- });
33
-
34
- // Handle webhooks
35
- paykit.webhooks
36
- .setup({ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET })
37
- .on('$checkoutCreated', async event => {
38
- console.log('Checkout created:', event.data);
39
- })
40
- .on('$invoicePaid', async event => {
41
- console.log('Payment received:', event.data);
42
- });
20
+ export const paykit = new PayKit(provider);
21
+ export const endpoints = createEndpointHandlers(paykit);
43
22
  ```
44
23
 
45
- ## Webhook Implementation
24
+ ### Next.js Catch All API Route (/api/paykit/[...endpoint]/route.ts)
25
+
26
+ ```typescript
27
+ import { paykit } from '@/lib/paykit';
28
+ import { EndpointPath } from '@paykit-sdk/core';
29
+
30
+ export async function POST(
31
+ request: NextRequest,
32
+ { params }: { params: { endpoint: string[] } },
33
+ ) {
34
+ try {
35
+ // Construct the endpoint path with full type safety
36
+ const endpoint = ('/' + params.endpoint.join('/')) as EndpointPath;
37
+ const handler = endpoints[endpoint];
38
+
39
+ if (!handler) {
40
+ return NextResponse.json({ message: 'Endpoint not found' }, { status: 404 });
41
+ }
42
+
43
+ // Parse request body
44
+ const body = await request.json();
45
+ const { args } = body;
46
+
47
+ const result = await handler(...args);
48
+
49
+ return NextResponse.json({ result });
50
+ } catch (error) {
51
+ console.error('PayKit API Error:', error);
52
+ return NextResponse.json(
53
+ { message: error instanceof Error ? error.message : 'Internal server error' },
54
+ { status: 500 },
55
+ );
56
+ }
57
+ }
58
+ ```
46
59
 
47
- ### Next.js API Route
60
+ ### Next.js Webhooks (/api/paykit/webhooks/route.ts)
48
61
 
49
62
  ```typescript
50
63
  import { paykit } from '@/lib/paykit';
51
- import { NextRequest, NextResponse } from 'next/server';
64
+ import { NextRequest } from 'next/server';
52
65
 
53
66
  export async function POST(request: NextRequest) {
54
- console.log('Stripe webhook received');
67
+ const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
68
+
69
+ if (!webhookSecret) {
70
+ return NextResponse.json({ error: 'Webhook secret not configured' }, { status: 500 });
71
+ }
55
72
 
56
73
  const webhook = paykit.webhooks
57
- .setup({ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET! })
58
- .on('$checkoutCreated', async event => {
59
- console.log('Checkout created:', event.data);
60
- // Handle checkout creation
61
- })
62
- .on('$customerCreated', async event => {
74
+ .setup({ webhookSecret })
75
+ .on('customer.created', async event => {
63
76
  console.log('Customer created:', event.data);
64
- // Handle customer creation
65
- })
66
- .on('$customerUpdated', async event => {
67
- console.log('Customer updated:', event.data);
68
- // Handle customer updates
69
- })
70
- .on('$subscriptionCreated', async event => {
77
+ });
78
+ .on('subscription.created', async event => {
71
79
  console.log('Subscription created:', event.data);
72
- // Handle subscription creation
73
- })
74
- .on('$subscriptionUpdated', async event => {
75
- console.log('Subscription updated:', event.data);
76
- // Handle subscription updates
77
- })
78
- .on('$subscriptionCancelled', async event => {
79
- console.log('Subscription cancelled:', event.data);
80
- // Handle subscription cancellation
81
- })
82
- .on('$invoicePaid', async event => {
83
- console.log('Payment received:', event.data);
84
- // Handle successful payment
80
+ });
81
+ .on('payment.created', async event => {
82
+ console.log('Payment created:', event.data);
83
+ });
84
+ .on('refund.created', async event => {
85
+ console.log('Refund created:', event.data);
86
+ });
87
+ .on('invoice.generated', async event => {
88
+ console.log('Invoice generated:', event.data);
85
89
  });
86
90
 
87
- const headers = Object.fromEntries(request.headers.entries());
88
91
  const body = await request.text();
89
- await webhook.handle({ body, headers });
92
+ const headers = Object.fromEntries(request.headers.entries());
93
+ const url = request.url
94
+ await webhook.handle({ body, headers, fullUrl: url });
90
95
 
96
+ // Return immediately, processing happens in background
91
97
  return NextResponse.json({ success: true });
92
98
  }
93
99
  ```
94
100
 
95
- ### Express.js Route
101
+ ### Express.js with Webhook Handler
96
102
 
97
103
  ```typescript
98
- import { paykit } from '@/lib/paykit';
104
+ import { paykit, endpoints } from '@/lib/paykit';
105
+ import { createEndpointHandlers, EndpointPath } from '@paykit-sdk/core';
99
106
  import express from 'express';
100
107
 
101
108
  const app = express();
102
- app.use(express.raw({ type: 'application/json' }));
103
109
 
104
- app.post('/api/webhooks/stripe', async (req, res) => {
105
- console.log('Stripe webhook received');
110
+ // IMPORTANT: Webhook route must come BEFORE express.json() middleware
111
+ // This ensures we get the raw body for signature verification
112
+ app.post(
113
+ '/api/webhooks/stripe',
114
+ express.raw({ type: 'application/json' }),
115
+ async (req, res) => {
116
+ try {
117
+ const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
118
+
119
+ if (!webhookSecret) {
120
+ return res.status(500).json({ error: 'Webhook secret not configured' });
121
+ }
122
+
123
+ const webhook = paykit.webhooks
124
+ .setup({ webhookSecret })
125
+ .on('customer.created', async event => {
126
+ console.log('Customer created:', event.data);
127
+ })
128
+ .on('subscription.created', async event => {
129
+ console.log('Subscription created:', event.data);
130
+ })
131
+ .on('payment.created', async event => {
132
+ console.log('Payment created:', event.data);
133
+ })
134
+ .on('refund.created', async event => {
135
+ console.log('Refund created:', event.data);
136
+ })
137
+ .on('invoice.generated', async event => {
138
+ console.log('Invoice generated:', event.data);
139
+ });
140
+
141
+ const body = req.body; // Raw buffer from express.raw()
142
+ const headers = req.headers;
143
+ const url = request.url;
144
+ await webhook.handle({ body, headers, fullUrl: url });
145
+
146
+ // Return immediately, processing happens in background
147
+ res.json({ success: true });
148
+ } catch (error) {
149
+ console.error('Webhook error:', error);
150
+ res.status(500).json({
151
+ message: error instanceof Error ? error.message : 'Webhook processing failed',
152
+ });
153
+ }
154
+ },
155
+ );
106
156
 
107
- const webhook = paykit.webhooks
108
- .setup({ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET! })
109
- .on('$checkoutCreated', async event => {
110
- console.log('Checkout created:', event.data);
111
- })
112
- .on('$customerCreated', async event => {
113
- console.log('Customer created:', event.data);
114
- })
115
- .on('$invoicePaid', async event => {
116
- console.log('Payment received:', event.data);
117
- });
157
+ // Regular API routes use JSON middleware
158
+ app.use(express.json());
118
159
 
119
- const headers = req.headers;
120
- const body = req.body;
121
- await webhook.handle({ body, headers });
160
+ app.post('/api/paykit/*', async (req, res) => {
161
+ try {
162
+ const endpoint = req.path.replace('/api/paykit', '') as EndpointPath;
163
+ const handler = endpoints[endpoint];
122
164
 
123
- res.json({ success: true });
124
- });
125
- ```
165
+ if (!handler) {
166
+ return res.status(404).json({ message: 'Endpoint not found' });
167
+ }
126
168
 
127
- ### Vite.js
169
+ const { args } = req.body;
170
+ const result = await handler(...args);
128
171
 
129
- ```typescript
130
- import { paykit } from '@/lib/paykit';
131
-
132
- export default defineEventHandler(async event => {
133
- console.log('Stripe webhook received');
134
-
135
- const webhook = paykit.webhooks
136
- .setup({ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET! })
137
- .on('$checkoutCreated', async event => {
138
- console.log('Checkout created:', event.data);
139
- })
140
- .on('$customerCreated', async event => {
141
- console.log('Customer created:', event.data);
142
- })
143
- .on('$invoicePaid', async event => {
144
- console.log('Payment received:', event.data);
172
+ res.json({ result });
173
+ } catch (error) {
174
+ res.status(500).json({
175
+ message: error instanceof Error ? error.message : 'Internal server error',
145
176
  });
177
+ }
178
+ });
146
179
 
147
- const headers = getHeaders(event);
148
- const body = await readBody(event);
149
- await webhook.handle({ body, headers });
150
-
151
- return { success: true };
180
+ app.listen(3000, () => {
181
+ console.log('Server running on port 3000');
152
182
  });
153
183
  ```
154
184
 
@@ -177,4 +207,4 @@ STRIPE_WEBHOOK_SECRET=whsec_...
177
207
 
178
208
  ## License
179
209
 
180
- GPL-3.0
210
+ ISC
package/dist/index.d.mts CHANGED
@@ -1,37 +1,8 @@
1
- import { PaykitProviderOptions, PayKitProvider, CreateCheckoutParams, Checkout, CreateCustomerParams, Customer, UpdateCustomerParams, UpdateSubscriptionParams, Subscription, HandleWebhookParams, WebhookEventPayload } from '@paykit-sdk/core';
2
- import Stripe from 'stripe';
1
+ import { StripeOptions, StripeProvider } from './stripe-provider.mjs';
2
+ import '@paykit-sdk/core';
3
+ import 'stripe';
3
4
 
4
- interface StripeConfig extends PaykitProviderOptions<Stripe.StripeConfig> {
5
- apiKey: string;
6
- }
7
- declare class StripeProvider implements PayKitProvider {
8
- private stripe;
9
- constructor(config: StripeConfig);
10
- /**
11
- * Checkout management
12
- */
13
- createCheckout: (params: CreateCheckoutParams) => Promise<Checkout>;
14
- retrieveCheckout: (id: string) => Promise<Checkout>;
15
- /**
16
- * Customer management
17
- */
18
- createCustomer: (params: CreateCustomerParams) => Promise<Customer>;
19
- updateCustomer: (id: string, params: UpdateCustomerParams) => Promise<Customer>;
20
- deleteCustomer: (id: string) => Promise<null>;
21
- retrieveCustomer: (id: string) => Promise<Customer | null>;
22
- /**
23
- * Subscription management
24
- */
25
- cancelSubscription: (id: string) => Promise<null>;
26
- updateSubscription: (id: string, params: UpdateSubscriptionParams) => Promise<Subscription>;
27
- retrieveSubscription: (id: string) => Promise<Subscription>;
28
- /**
29
- * Webhook management
30
- */
31
- handleWebhook: (params: HandleWebhookParams) => Promise<WebhookEventPayload>;
32
- }
33
-
34
- declare const createStripe: (config: StripeConfig) => StripeProvider;
5
+ declare const createStripe: (config: StripeOptions) => StripeProvider;
35
6
  declare const stripe: () => StripeProvider;
36
7
 
37
8
  export { createStripe, stripe };
package/dist/index.d.ts CHANGED
@@ -1,37 +1,8 @@
1
- import { PaykitProviderOptions, PayKitProvider, CreateCheckoutParams, Checkout, CreateCustomerParams, Customer, UpdateCustomerParams, UpdateSubscriptionParams, Subscription, HandleWebhookParams, WebhookEventPayload } from '@paykit-sdk/core';
2
- import Stripe from 'stripe';
1
+ import { StripeOptions, StripeProvider } from './stripe-provider.js';
2
+ import '@paykit-sdk/core';
3
+ import 'stripe';
3
4
 
4
- interface StripeConfig extends PaykitProviderOptions<Stripe.StripeConfig> {
5
- apiKey: string;
6
- }
7
- declare class StripeProvider implements PayKitProvider {
8
- private stripe;
9
- constructor(config: StripeConfig);
10
- /**
11
- * Checkout management
12
- */
13
- createCheckout: (params: CreateCheckoutParams) => Promise<Checkout>;
14
- retrieveCheckout: (id: string) => Promise<Checkout>;
15
- /**
16
- * Customer management
17
- */
18
- createCustomer: (params: CreateCustomerParams) => Promise<Customer>;
19
- updateCustomer: (id: string, params: UpdateCustomerParams) => Promise<Customer>;
20
- deleteCustomer: (id: string) => Promise<null>;
21
- retrieveCustomer: (id: string) => Promise<Customer | null>;
22
- /**
23
- * Subscription management
24
- */
25
- cancelSubscription: (id: string) => Promise<null>;
26
- updateSubscription: (id: string, params: UpdateSubscriptionParams) => Promise<Subscription>;
27
- retrieveSubscription: (id: string) => Promise<Subscription>;
28
- /**
29
- * Webhook management
30
- */
31
- handleWebhook: (params: HandleWebhookParams) => Promise<WebhookEventPayload>;
32
- }
33
-
34
- declare const createStripe: (config: StripeConfig) => StripeProvider;
5
+ declare const createStripe: (config: StripeOptions) => StripeProvider;
35
6
  declare const stripe: () => StripeProvider;
36
7
 
37
8
  export { createStripe, stripe };