@paykit-sdk/stripe 1.1.7 → 1.1.9

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,161 @@ 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(request: NextRequest, { params }: { params: { endpoint: string[] } }) {
31
+ try {
32
+ // Construct the endpoint path with full type safety
33
+ const endpoint = ('/' + params.endpoint.join('/')) as EndpointPath;
34
+ const handler = endpoints[endpoint];
35
+
36
+ if (!handler) {
37
+ return NextResponse.json({ message: 'Endpoint not found' }, { status: 404 });
38
+ }
39
+
40
+ // Parse request body
41
+ const body = await request.json();
42
+ const { args } = body;
43
+
44
+ const result = await handler(...args);
45
+
46
+ return NextResponse.json({ result });
47
+ } catch (error) {
48
+ console.error('PayKit API Error:', error);
49
+ return NextResponse.json(
50
+ { message: error instanceof Error ? error.message : 'Internal server error' },
51
+ { status: 500 },
52
+ );
53
+ }
54
+ }
55
+ ```
46
56
 
47
- ### Next.js API Route
57
+ ### Next.js Webhooks (/api/paykit/webhooks/route.ts)
48
58
 
49
59
  ```typescript
50
60
  import { paykit } from '@/lib/paykit';
51
- import { NextRequest, NextResponse } from 'next/server';
61
+ import { NextRequest } from 'next/server';
52
62
 
53
63
  export async function POST(request: NextRequest) {
54
- console.log('Stripe webhook received');
64
+ const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
65
+
66
+ if (!webhookSecret) {
67
+ return NextResponse.json({ error: 'Webhook secret not configured' }, { status: 500 });
68
+ }
55
69
 
56
70
  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 => {
71
+ .setup({ webhookSecret })
72
+ .on('customer.created', async event => {
63
73
  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 => {
74
+ });
75
+ .on('subscription.created', async event => {
71
76
  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
77
+ });
78
+ .on('payment.created', async event => {
79
+ console.log('Payment created:', event.data);
80
+ });
81
+ .on('refund.created', async event => {
82
+ console.log('Refund created:', event.data);
83
+ });
84
+ .on('invoice.generated', async event => {
85
+ console.log('Invoice generated:', event.data);
85
86
  });
86
87
 
87
- const headers = Object.fromEntries(request.headers.entries());
88
88
  const body = await request.text();
89
- await webhook.handle({ body, headers });
89
+ const headers = Object.fromEntries(request.headers.entries());
90
+ const url = request.url
91
+ await webhook.handle({ body, headers, fullUrl: url });
90
92
 
93
+ // Return immediately, processing happens in background
91
94
  return NextResponse.json({ success: true });
92
95
  }
93
96
  ```
94
97
 
95
- ### Express.js Route
98
+ ### Express.js with Webhook Handler
96
99
 
97
100
  ```typescript
98
- import { paykit } from '@/lib/paykit';
101
+ import { paykit, endpoints } from '@/lib/paykit';
102
+ import { createEndpointHandlers, EndpointPath } from '@paykit-sdk/core';
99
103
  import express from 'express';
100
104
 
101
105
  const app = express();
102
- app.use(express.raw({ type: 'application/json' }));
103
-
104
- app.post('/api/webhooks/stripe', async (req, res) => {
105
- console.log('Stripe webhook received');
106
106
 
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);
107
+ // IMPORTANT: Webhook route must come BEFORE express.json() middleware
108
+ // This ensures we get the raw body for signature verification
109
+ app.post('/api/webhooks/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
110
+ try {
111
+ const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
112
+
113
+ if (!webhookSecret) {
114
+ return res.status(500).json({ error: 'Webhook secret not configured' });
115
+ }
116
+
117
+ const webhook = paykit.webhooks
118
+ .setup({ webhookSecret })
119
+ .on('customer.created', async event => {
120
+ console.log('Customer created:', event.data);
121
+ })
122
+ .on('subscription.created', async event => {
123
+ console.log('Subscription created:', event.data);
124
+ })
125
+ .on('payment.created', async event => {
126
+ console.log('Payment created:', event.data);
127
+ })
128
+ .on('refund.created', async event => {
129
+ console.log('Refund created:', event.data);
130
+ })
131
+ .on('invoice.generated', async event => {
132
+ console.log('Invoice generated:', event.data);
133
+ });
134
+
135
+ const body = req.body; // Raw buffer from express.raw()
136
+ const headers = req.headers;
137
+ const url = request.url;
138
+ await webhook.handle({ body, headers, fullUrl: url });
139
+
140
+ // Return immediately, processing happens in background
141
+ res.json({ success: true });
142
+ } catch (error) {
143
+ console.error('Webhook error:', error);
144
+ res.status(500).json({
145
+ message: error instanceof Error ? error.message : 'Webhook processing failed',
117
146
  });
118
-
119
- const headers = req.headers;
120
- const body = req.body;
121
- await webhook.handle({ body, headers });
122
-
123
- res.json({ success: true });
147
+ }
124
148
  });
125
- ```
126
149
 
127
- ### Vite.js
150
+ // Regular API routes use JSON middleware
151
+ app.use(express.json());
128
152
 
129
- ```typescript
130
- import { paykit } from '@/lib/paykit';
153
+ app.post('/api/paykit/*', async (req, res) => {
154
+ try {
155
+ const endpoint = req.path.replace('/api/paykit', '') as EndpointPath;
156
+ const handler = endpoints[endpoint];
131
157
 
132
- export default defineEventHandler(async event => {
133
- console.log('Stripe webhook received');
158
+ if (!handler) {
159
+ return res.status(404).json({ message: 'Endpoint not found' });
160
+ }
134
161
 
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);
145
- });
162
+ const { args } = req.body;
163
+ const result = await handler(...args);
146
164
 
147
- const headers = getHeaders(event);
148
- const body = await readBody(event);
149
- await webhook.handle({ body, headers });
165
+ res.json({ result });
166
+ } catch (error) {
167
+ res.status(500).json({
168
+ message: error instanceof Error ? error.message : 'Internal server error',
169
+ });
170
+ }
171
+ });
150
172
 
151
- return { success: true };
173
+ app.listen(3000, () => {
174
+ console.log('Server running on port 3000');
152
175
  });
153
176
  ```
154
177
 
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 };