@stripe-sdk/core 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.
@@ -0,0 +1,450 @@
1
+ 'use strict';
2
+
3
+ require('stripe');
4
+
5
+ // src/server/stripe-client.ts
6
+ function getStripe() {
7
+ {
8
+ throw new Error(
9
+ "[@stripe-sdk/core] Stripe not initialized. Call initStripe({ secretKey, publishableKey }) first."
10
+ );
11
+ }
12
+ }
13
+ function getConfig() {
14
+ {
15
+ throw new Error(
16
+ "[@stripe-sdk/core] Stripe not initialized. Call initStripe({ secretKey, publishableKey }) first."
17
+ );
18
+ }
19
+ }
20
+
21
+ // src/server/webhooks/index.ts
22
+ var MAX_BODY_SIZE = 1024 * 1024;
23
+ function createWebhookHandler(config) {
24
+ const webhookSecret = config.secret ?? getConfig().webhookSecret;
25
+ if (!webhookSecret) {
26
+ throw new Error(
27
+ "[@stripe-sdk/core] Webhook secret is required. Pass it via config.secret or initStripe({ webhookSecret })."
28
+ );
29
+ }
30
+ return async function handleWebhook(body, signature) {
31
+ const stripe = getStripe();
32
+ let event;
33
+ try {
34
+ event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
35
+ } catch (err) {
36
+ const verificationError = err instanceof Error ? err : new Error("Webhook signature verification failed");
37
+ if (config.onError) {
38
+ await config.onError(verificationError);
39
+ }
40
+ throw verificationError;
41
+ }
42
+ const handler = config.handlers[event.type];
43
+ if (handler) {
44
+ try {
45
+ await handler(event);
46
+ } catch (error) {
47
+ if (config.onError) {
48
+ await config.onError(error instanceof Error ? error : new Error(String(error)), event);
49
+ } else {
50
+ throw error;
51
+ }
52
+ }
53
+ } else if (config.onUnhandledEvent) {
54
+ await config.onUnhandledEvent(event);
55
+ }
56
+ return { received: true, type: event.type };
57
+ };
58
+ }
59
+ function createNextWebhookHandler(config) {
60
+ const handler = createWebhookHandler(config);
61
+ return async function POST(request) {
62
+ try {
63
+ const contentLength = request.headers.get("content-length");
64
+ if (contentLength && parseInt(contentLength, 10) > MAX_BODY_SIZE) {
65
+ return new Response(JSON.stringify({ error: "Webhook body too large" }), {
66
+ status: 413,
67
+ headers: { "Content-Type": "application/json" }
68
+ });
69
+ }
70
+ const body = await request.text();
71
+ const signature = request.headers.get("stripe-signature");
72
+ if (!signature) {
73
+ return new Response(JSON.stringify({ error: "Missing stripe-signature header" }), {
74
+ status: 400,
75
+ headers: { "Content-Type": "application/json" }
76
+ });
77
+ }
78
+ const result = await handler(body, signature);
79
+ return new Response(JSON.stringify(result), {
80
+ status: 200,
81
+ headers: { "Content-Type": "application/json" }
82
+ });
83
+ } catch (error) {
84
+ const message = error instanceof Error ? error.message : "Webhook handler failed";
85
+ return new Response(JSON.stringify({ error: message }), {
86
+ status: 400,
87
+ headers: { "Content-Type": "application/json" }
88
+ });
89
+ }
90
+ };
91
+ }
92
+ function createPagesWebhookHandler(webhookConfig) {
93
+ const handler = createWebhookHandler(webhookConfig);
94
+ return async function webhookRoute(req, res) {
95
+ if (req.method !== "POST") {
96
+ res.status(405).end();
97
+ return;
98
+ }
99
+ try {
100
+ const body = await getRawBody(req);
101
+ const signature = req.headers["stripe-signature"];
102
+ if (!signature) {
103
+ res.status(400).json({ error: "Missing stripe-signature header" });
104
+ return;
105
+ }
106
+ const result = await handler(body, signature);
107
+ res.status(200).json(result);
108
+ } catch (error) {
109
+ const message = error instanceof Error ? error.message : "Webhook handler failed";
110
+ res.status(400).json({ error: message });
111
+ }
112
+ };
113
+ }
114
+ function getRawBody(req) {
115
+ return new Promise((resolve, reject) => {
116
+ if (typeof req.body === "string") {
117
+ if (req.body.length > MAX_BODY_SIZE) {
118
+ reject(new Error("Webhook body too large"));
119
+ return;
120
+ }
121
+ resolve(req.body);
122
+ return;
123
+ }
124
+ if (Buffer.isBuffer(req.body)) {
125
+ if (req.body.length > MAX_BODY_SIZE) {
126
+ reject(new Error("Webhook body too large"));
127
+ return;
128
+ }
129
+ resolve(req.body.toString("utf8"));
130
+ return;
131
+ }
132
+ if (!req.on) {
133
+ reject(new Error("Cannot read raw body from request"));
134
+ return;
135
+ }
136
+ const chunks = [];
137
+ let totalLength = 0;
138
+ req.on("data", (chunk) => {
139
+ const buf = Buffer.from(chunk);
140
+ totalLength += buf.length;
141
+ if (totalLength > MAX_BODY_SIZE) {
142
+ reject(new Error("Webhook body too large"));
143
+ return;
144
+ }
145
+ chunks.push(buf);
146
+ });
147
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
148
+ req.on("error", reject);
149
+ });
150
+ }
151
+
152
+ // src/utils/errors.ts
153
+ function handleStripeError(error) {
154
+ if (error?.type) {
155
+ const stripeError = error;
156
+ return {
157
+ data: null,
158
+ error: {
159
+ message: stripeError.message,
160
+ type: stripeError.type,
161
+ code: stripeError.code,
162
+ statusCode: stripeError.statusCode
163
+ }
164
+ };
165
+ }
166
+ return {
167
+ data: null,
168
+ error: {
169
+ message: error instanceof Error ? error.message : "An unknown error occurred",
170
+ type: "sdk_error"
171
+ }
172
+ };
173
+ }
174
+ function success(data) {
175
+ return { data, error: null };
176
+ }
177
+
178
+ // src/server/payments/index.ts
179
+ async function createPaymentIntent(input) {
180
+ try {
181
+ const stripe = getStripe();
182
+ const paymentIntent = await stripe.paymentIntents.create({
183
+ amount: input.amount,
184
+ currency: input.currency,
185
+ customer: input.customerId,
186
+ payment_method: input.paymentMethodId,
187
+ metadata: input.metadata,
188
+ description: input.description,
189
+ receipt_email: input.receiptEmail,
190
+ setup_future_usage: input.setupFutureUsage,
191
+ automatic_payment_methods: input.automaticPaymentMethods === false || input.paymentMethodId ? void 0 : { enabled: true },
192
+ return_url: input.returnUrl
193
+ });
194
+ return success(paymentIntent);
195
+ } catch (error) {
196
+ return handleStripeError(error);
197
+ }
198
+ }
199
+ async function createCheckoutSession(input) {
200
+ try {
201
+ const stripe = getStripe();
202
+ const session = await stripe.checkout.sessions.create({
203
+ mode: input.mode,
204
+ line_items: input.lineItems.map((item) => ({
205
+ price: item.priceId,
206
+ quantity: item.quantity
207
+ })),
208
+ success_url: input.successUrl,
209
+ cancel_url: input.cancelUrl,
210
+ customer: input.customerId,
211
+ customer_email: input.customerEmail,
212
+ metadata: input.metadata,
213
+ allow_promotion_codes: input.allowPromotionCodes,
214
+ shipping_address_collection: input.shippingAddressCollection ? { allowed_countries: input.shippingAddressCollection.allowedCountries } : void 0,
215
+ billing_address_collection: input.billingAddressCollection,
216
+ subscription_data: input.trialPeriodDays ? { trial_period_days: input.trialPeriodDays } : void 0,
217
+ tax_id_collection: input.taxIdCollection ? { enabled: true } : void 0,
218
+ automatic_tax: input.automaticTax ? { enabled: true } : void 0,
219
+ locale: input.locale
220
+ });
221
+ return success(session);
222
+ } catch (error) {
223
+ return handleStripeError(error);
224
+ }
225
+ }
226
+ async function createSetupIntent(input) {
227
+ try {
228
+ const stripe = getStripe();
229
+ const setupIntent = await stripe.setupIntents.create({
230
+ customer: input.customerId,
231
+ payment_method_types: input.paymentMethodTypes,
232
+ usage: input.usage,
233
+ metadata: input.metadata
234
+ });
235
+ return success(setupIntent);
236
+ } catch (error) {
237
+ return handleStripeError(error);
238
+ }
239
+ }
240
+
241
+ // src/server/customers/index.ts
242
+ async function createCustomer(input) {
243
+ try {
244
+ const stripe = getStripe();
245
+ const customer = await stripe.customers.create({
246
+ email: input.email,
247
+ name: input.name,
248
+ phone: input.phone,
249
+ description: input.description,
250
+ metadata: input.metadata,
251
+ payment_method: input.paymentMethodId,
252
+ invoice_settings: input.paymentMethodId ? { default_payment_method: input.paymentMethodId } : void 0,
253
+ address: input.address ? {
254
+ line1: input.address.line1,
255
+ line2: input.address.line2,
256
+ city: input.address.city,
257
+ state: input.address.state,
258
+ postal_code: input.address.postalCode,
259
+ country: input.address.country
260
+ } : void 0
261
+ });
262
+ return success(customer);
263
+ } catch (error) {
264
+ return handleStripeError(error);
265
+ }
266
+ }
267
+ async function createPortalSession(input) {
268
+ try {
269
+ const stripe = getStripe();
270
+ const session = await stripe.billingPortal.sessions.create({
271
+ customer: input.customerId,
272
+ return_url: input.returnUrl,
273
+ configuration: input.configuration
274
+ });
275
+ return success(session);
276
+ } catch (error) {
277
+ return handleStripeError(error);
278
+ }
279
+ }
280
+
281
+ // src/server/subscriptions/index.ts
282
+ async function createSubscription(input) {
283
+ try {
284
+ const stripe = getStripe();
285
+ const items = input.items ? input.items.map((item) => ({ price: item.priceId, quantity: item.quantity })) : [{ price: input.priceId, quantity: input.quantity ?? 1 }];
286
+ const subscription = await stripe.subscriptions.create({
287
+ customer: input.customerId,
288
+ items,
289
+ metadata: input.metadata,
290
+ trial_period_days: input.trialPeriodDays,
291
+ coupon: input.couponId,
292
+ promotion_code: input.promotionCodeId,
293
+ payment_behavior: input.paymentBehavior ?? "default_incomplete",
294
+ cancel_at_period_end: input.cancelAtPeriodEnd,
295
+ billing_cycle_anchor: input.billingCycleAnchor,
296
+ proration_behavior: input.prorationBehavior,
297
+ expand: ["latest_invoice.payment_intent"]
298
+ });
299
+ return success(subscription);
300
+ } catch (error) {
301
+ return handleStripeError(error);
302
+ }
303
+ }
304
+ async function cancelSubscription(input) {
305
+ try {
306
+ const stripe = getStripe();
307
+ if (input.cancelAtPeriodEnd) {
308
+ const subscription2 = await stripe.subscriptions.update(input.subscriptionId, {
309
+ cancel_at_period_end: true,
310
+ cancellation_details: input.cancellationDetails ? {
311
+ comment: input.cancellationDetails.comment,
312
+ feedback: input.cancellationDetails.feedback
313
+ } : void 0
314
+ });
315
+ return success(subscription2);
316
+ }
317
+ const subscription = await stripe.subscriptions.cancel(input.subscriptionId, {
318
+ cancellation_details: input.cancellationDetails ? {
319
+ comment: input.cancellationDetails.comment,
320
+ feedback: input.cancellationDetails.feedback
321
+ } : void 0
322
+ });
323
+ return success(subscription);
324
+ } catch (error) {
325
+ return handleStripeError(error);
326
+ }
327
+ }
328
+ async function resumeSubscription(subscriptionId) {
329
+ try {
330
+ const stripe = getStripe();
331
+ const subscription = await stripe.subscriptions.update(subscriptionId, {
332
+ cancel_at_period_end: false
333
+ });
334
+ return success(subscription);
335
+ } catch (error) {
336
+ return handleStripeError(error);
337
+ }
338
+ }
339
+
340
+ // src/next/index.ts
341
+ var actions = {
342
+ createPaymentIntent: async (input) => {
343
+ return createPaymentIntent(input);
344
+ },
345
+ createCheckoutSession: async (input) => {
346
+ return createCheckoutSession(input);
347
+ },
348
+ createSetupIntent: async (input) => {
349
+ return createSetupIntent(input);
350
+ },
351
+ createCustomer: async (input) => {
352
+ return createCustomer(input);
353
+ },
354
+ createPortalSession: async (input) => {
355
+ return createPortalSession(input);
356
+ },
357
+ createSubscription: async (input) => {
358
+ return createSubscription(input);
359
+ },
360
+ cancelSubscription: async (input) => {
361
+ return cancelSubscription(input);
362
+ },
363
+ resumeSubscription: async (subscriptionId) => {
364
+ return resumeSubscription(subscriptionId);
365
+ }
366
+ };
367
+ function createPaymentIntentRoute(options) {
368
+ return async function POST(request) {
369
+ try {
370
+ let input = await request.json();
371
+ if (options?.beforeCreate) {
372
+ input = await options.beforeCreate(input, request);
373
+ }
374
+ const result = await createPaymentIntent(input);
375
+ if (result.error) {
376
+ return new Response(JSON.stringify(result.error), {
377
+ status: 400,
378
+ headers: { "Content-Type": "application/json" }
379
+ });
380
+ }
381
+ return new Response(
382
+ JSON.stringify({ clientSecret: result.data.client_secret, id: result.data.id }),
383
+ { status: 200, headers: { "Content-Type": "application/json" } }
384
+ );
385
+ } catch (error) {
386
+ return new Response(
387
+ JSON.stringify({ error: error instanceof Error ? error.message : "Internal error" }),
388
+ { status: 500, headers: { "Content-Type": "application/json" } }
389
+ );
390
+ }
391
+ };
392
+ }
393
+ function createCheckoutSessionRoute(options) {
394
+ return async function POST(request) {
395
+ try {
396
+ let input = await request.json();
397
+ if (options?.beforeCreate) {
398
+ input = await options.beforeCreate(input, request);
399
+ }
400
+ const result = await createCheckoutSession(input);
401
+ if (result.error) {
402
+ return new Response(JSON.stringify(result.error), {
403
+ status: 400,
404
+ headers: { "Content-Type": "application/json" }
405
+ });
406
+ }
407
+ return new Response(
408
+ JSON.stringify({ sessionId: result.data.id, url: result.data.url }),
409
+ { status: 200, headers: { "Content-Type": "application/json" } }
410
+ );
411
+ } catch (error) {
412
+ return new Response(
413
+ JSON.stringify({ error: error instanceof Error ? error.message : "Internal error" }),
414
+ { status: 500, headers: { "Content-Type": "application/json" } }
415
+ );
416
+ }
417
+ };
418
+ }
419
+ function createPortalSessionRoute() {
420
+ return async function POST(request) {
421
+ try {
422
+ const input = await request.json();
423
+ const result = await createPortalSession(input);
424
+ if (result.error) {
425
+ return new Response(JSON.stringify(result.error), {
426
+ status: 400,
427
+ headers: { "Content-Type": "application/json" }
428
+ });
429
+ }
430
+ return new Response(
431
+ JSON.stringify({ url: result.data.url }),
432
+ { status: 200, headers: { "Content-Type": "application/json" } }
433
+ );
434
+ } catch (error) {
435
+ return new Response(
436
+ JSON.stringify({ error: error instanceof Error ? error.message : "Internal error" }),
437
+ { status: 500, headers: { "Content-Type": "application/json" } }
438
+ );
439
+ }
440
+ };
441
+ }
442
+
443
+ exports.actions = actions;
444
+ exports.createCheckoutSessionRoute = createCheckoutSessionRoute;
445
+ exports.createNextWebhookHandler = createNextWebhookHandler;
446
+ exports.createPagesWebhookHandler = createPagesWebhookHandler;
447
+ exports.createPaymentIntentRoute = createPaymentIntentRoute;
448
+ exports.createPortalSessionRoute = createPortalSessionRoute;
449
+ //# sourceMappingURL=index.js.map
450
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/server/stripe-client.ts","../../src/server/webhooks/index.ts","../../src/utils/errors.ts","../../src/server/payments/index.ts","../../src/server/customers/index.ts","../../src/server/subscriptions/index.ts","../../src/next/index.ts"],"names":["subscription"],"mappings":";;;;;AAkBO,SAAS,SAAA,GAAoB;AAClC,EAAqB;AACnB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEF;AAEO,SAAS,SAAA,GAA6B;AAC3C,EAAoB;AAClB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA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,SAAS,EAAE,cAAA,EAAgB,oBAAmB;AAAE,OACjE;AAAA,IACF;AAAA,EACF,CAAA;AACF","file":"index.js","sourcesContent":["import Stripe from 'stripe';\nimport type { StripeSDKConfig } from '../types';\n\nlet stripeInstance: Stripe | null = null;\nlet currentConfig: StripeSDKConfig | null = null;\n\nexport function initStripe(config: StripeSDKConfig): Stripe {\n currentConfig = config;\n stripeInstance = new Stripe(config.secretKey, {\n apiVersion: config.apiVersion ?? '2025-01-27.acacia' as Stripe.LatestApiVersion,\n appInfo: config.appInfo ?? {\n name: '@stripe-sdk/core',\n version: '1.0.0',\n },\n });\n return stripeInstance;\n}\n\nexport function getStripe(): Stripe {\n if (!stripeInstance) {\n throw new Error(\n '[@stripe-sdk/core] Stripe not initialized. Call initStripe({ secretKey, publishableKey }) first.'\n );\n }\n return stripeInstance;\n}\n\nexport function getConfig(): StripeSDKConfig {\n if (!currentConfig) {\n throw new Error(\n '[@stripe-sdk/core] Stripe not initialized. Call initStripe({ secretKey, publishableKey }) first.'\n );\n }\n return currentConfig;\n}\n","import type Stripe from 'stripe';\nimport { getStripe, getConfig } from '../stripe-client';\nimport type { WebhookHandlerMap, WebhookHandler } from '../../types';\n\nconst MAX_BODY_SIZE = 1024 * 1024; // 1 MB\n\nexport interface WebhookConfig {\n secret?: string;\n handlers: WebhookHandlerMap;\n onError?: (error: Error, event?: Stripe.Event) => void | Promise<void>;\n onUnhandledEvent?: (event: Stripe.Event) => void | Promise<void>;\n}\n\nexport function createWebhookHandler(config: WebhookConfig) {\n const webhookSecret = config.secret ?? getConfig().webhookSecret;\n\n if (!webhookSecret) {\n throw new Error(\n '[@stripe-sdk/core] Webhook secret is required. Pass it via config.secret or initStripe({ webhookSecret }).'\n );\n }\n\n return async function handleWebhook(\n body: string | Buffer,\n signature: string\n ): Promise<{ received: true; type: string }> {\n const stripe = getStripe();\n\n let event: Stripe.Event;\n try {\n event = stripe.webhooks.constructEvent(body, signature, webhookSecret);\n } catch (err) {\n const verificationError = err instanceof Error ? err : new Error('Webhook signature verification failed');\n if (config.onError) {\n await config.onError(verificationError);\n }\n throw verificationError;\n }\n\n const handler: WebhookHandler | undefined = config.handlers[event.type];\n\n if (handler) {\n try {\n await handler(event);\n } catch (error) {\n if (config.onError) {\n await config.onError(error instanceof Error ? error : new Error(String(error)), event);\n } else {\n throw error;\n }\n }\n } else if (config.onUnhandledEvent) {\n await config.onUnhandledEvent(event);\n }\n\n return { received: true, type: event.type };\n };\n}\n\n/**\n * Helper for Next.js App Router webhook route\n *\n * Usage in app/api/webhooks/stripe/route.ts:\n *\n * ```ts\n * import { createNextWebhookHandler } from '@stripe-sdk/core/webhooks';\n *\n * export const POST = createNextWebhookHandler({\n * handlers: {\n * 'payment_intent.succeeded': async (event) => { ... },\n * 'customer.subscription.created': async (event) => { ... },\n * },\n * });\n * ```\n */\nexport function createNextWebhookHandler(config: WebhookConfig) {\n const handler = createWebhookHandler(config);\n\n return async function POST(request: Request): Promise<Response> {\n try {\n const contentLength = request.headers.get('content-length');\n if (contentLength && parseInt(contentLength, 10) > MAX_BODY_SIZE) {\n return new Response(JSON.stringify({ error: 'Webhook body too large' }), {\n status: 413,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n const body = await request.text();\n const signature = request.headers.get('stripe-signature');\n\n if (!signature) {\n return new Response(JSON.stringify({ error: 'Missing stripe-signature header' }), {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n const result = await handler(body, signature);\n\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Webhook handler failed';\n\n return new Response(JSON.stringify({ error: message }), {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n}\n\n/**\n * Helper for Next.js Pages Router webhook route\n *\n * Usage in pages/api/webhooks/stripe.ts:\n *\n * ```ts\n * import { createPagesWebhookHandler } from '@stripe-sdk/core/webhooks';\n *\n * export const config = { api: { bodyParser: false } };\n *\n * export default createPagesWebhookHandler({\n * handlers: {\n * 'payment_intent.succeeded': async (event) => { ... },\n * },\n * });\n * ```\n */\nexport function createPagesWebhookHandler(webhookConfig: WebhookConfig) {\n const handler = createWebhookHandler(webhookConfig);\n\n return async function webhookRoute(\n req: { method?: string; headers: Record<string, string | string[] | undefined>; body?: unknown; on?: (event: string, cb: (...args: unknown[]) => void) => void },\n res: { status: (code: number) => { json: (data: unknown) => void; end: () => void } }\n ): Promise<void> {\n if (req.method !== 'POST') {\n res.status(405).end();\n return;\n }\n\n try {\n const body = await getRawBody(req);\n const signature = req.headers['stripe-signature'] as string;\n\n if (!signature) {\n res.status(400).json({ error: 'Missing stripe-signature header' });\n return;\n }\n\n const result = await handler(body, signature);\n res.status(200).json(result);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Webhook handler failed';\n res.status(400).json({ error: message });\n }\n };\n}\n\nfunction getRawBody(req: { on?: (event: string, cb: (...args: unknown[]) => void) => void; body?: unknown }): Promise<string> {\n return new Promise((resolve, reject) => {\n if (typeof req.body === 'string') {\n if (req.body.length > MAX_BODY_SIZE) {\n reject(new Error('Webhook body too large'));\n return;\n }\n resolve(req.body);\n return;\n }\n if (Buffer.isBuffer(req.body)) {\n if (req.body.length > MAX_BODY_SIZE) {\n reject(new Error('Webhook body too large'));\n return;\n }\n resolve(req.body.toString('utf8'));\n return;\n }\n if (!req.on) {\n reject(new Error('Cannot read raw body from request'));\n return;\n }\n const chunks: Buffer[] = [];\n let totalLength = 0;\n req.on('data', (chunk: unknown) => {\n const buf = Buffer.from(chunk as Uint8Array);\n totalLength += buf.length;\n if (totalLength > MAX_BODY_SIZE) {\n reject(new Error('Webhook body too large'));\n return;\n }\n chunks.push(buf);\n });\n req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));\n req.on('error', reject);\n });\n}\n","import type Stripe from 'stripe';\nimport type { SDKResult } from '../types';\n\nexport function handleStripeError<T>(error: unknown): SDKResult<T> {\n if ((error as Stripe.errors.StripeError)?.type) {\n const stripeError = error as Stripe.errors.StripeError;\n return {\n data: null,\n error: {\n message: stripeError.message,\n type: stripeError.type,\n code: stripeError.code,\n statusCode: stripeError.statusCode,\n },\n };\n }\n\n return {\n data: null,\n error: {\n message: error instanceof Error ? error.message : 'An unknown error occurred',\n type: 'sdk_error',\n },\n };\n}\n\nexport function success<T>(data: T): SDKResult<T> {\n return { data, error: null };\n}\n","import type Stripe from 'stripe';\nimport { getStripe } from '../stripe-client';\nimport { handleStripeError, success } from '../../utils/errors';\nimport type {\n CreatePaymentIntentInput,\n ConfirmPaymentInput,\n CreateCheckoutSessionInput,\n CreatePaymentLinkInput,\n CreateSetupIntentInput,\n PaginationInput,\n SDKResult,\n} from '../../types';\n\n// ─── Payment Intents ─────────────────────────────────────────────────\n\nexport async function createPaymentIntent(\n input: CreatePaymentIntentInput\n): Promise<SDKResult<Stripe.PaymentIntent>> {\n try {\n const stripe = getStripe();\n const paymentIntent = await stripe.paymentIntents.create({\n amount: input.amount,\n currency: input.currency,\n customer: input.customerId,\n payment_method: input.paymentMethodId,\n metadata: input.metadata,\n description: input.description,\n receipt_email: input.receiptEmail,\n setup_future_usage: input.setupFutureUsage,\n automatic_payment_methods:\n input.automaticPaymentMethods === false || input.paymentMethodId\n ? undefined\n : { enabled: true },\n return_url: input.returnUrl,\n });\n return success(paymentIntent);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function retrievePaymentIntent(\n paymentIntentId: string\n): Promise<SDKResult<Stripe.PaymentIntent>> {\n try {\n const stripe = getStripe();\n const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);\n return success(paymentIntent);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function confirmPaymentIntent(\n input: ConfirmPaymentInput\n): Promise<SDKResult<Stripe.PaymentIntent>> {\n try {\n const stripe = getStripe();\n const paymentIntent = await stripe.paymentIntents.confirm(input.paymentIntentId, {\n payment_method: input.paymentMethodId,\n return_url: input.returnUrl,\n });\n return success(paymentIntent);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function cancelPaymentIntent(\n paymentIntentId: string\n): Promise<SDKResult<Stripe.PaymentIntent>> {\n try {\n const stripe = getStripe();\n const paymentIntent = await stripe.paymentIntents.cancel(paymentIntentId);\n return success(paymentIntent);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function listPaymentIntents(\n input?: PaginationInput & { customerId?: string }\n): Promise<SDKResult<Stripe.ApiList<Stripe.PaymentIntent>>> {\n try {\n const stripe = getStripe();\n const paymentIntents = await stripe.paymentIntents.list({\n limit: input?.limit ?? 10,\n starting_after: input?.startingAfter,\n ending_before: input?.endingBefore,\n customer: input?.customerId,\n });\n return success(paymentIntents);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\n// ─── Checkout Sessions ───────────────────────────────────────────────\n\nexport async function createCheckoutSession(\n input: CreateCheckoutSessionInput\n): Promise<SDKResult<Stripe.Checkout.Session>> {\n try {\n const stripe = getStripe();\n const session = await stripe.checkout.sessions.create({\n mode: input.mode,\n line_items: input.lineItems.map((item) => ({\n price: item.priceId,\n quantity: item.quantity,\n })),\n success_url: input.successUrl,\n cancel_url: input.cancelUrl,\n customer: input.customerId,\n customer_email: input.customerEmail,\n metadata: input.metadata,\n allow_promotion_codes: input.allowPromotionCodes,\n shipping_address_collection: input.shippingAddressCollection\n ? { allowed_countries: input.shippingAddressCollection.allowedCountries as Stripe.Checkout.SessionCreateParams.ShippingAddressCollection.AllowedCountry[] }\n : undefined,\n billing_address_collection: input.billingAddressCollection,\n subscription_data: input.trialPeriodDays\n ? { trial_period_days: input.trialPeriodDays }\n : undefined,\n tax_id_collection: input.taxIdCollection ? { enabled: true } : undefined,\n automatic_tax: input.automaticTax ? { enabled: true } : undefined,\n locale: input.locale as Stripe.Checkout.SessionCreateParams.Locale,\n });\n return success(session);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function retrieveCheckoutSession(\n sessionId: string\n): Promise<SDKResult<Stripe.Checkout.Session>> {\n try {\n const stripe = getStripe();\n const session = await stripe.checkout.sessions.retrieve(sessionId, {\n expand: ['line_items', 'payment_intent', 'subscription'],\n });\n return success(session);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function listCheckoutSessions(\n input?: PaginationInput\n): Promise<SDKResult<Stripe.ApiList<Stripe.Checkout.Session>>> {\n try {\n const stripe = getStripe();\n const sessions = await stripe.checkout.sessions.list({\n limit: input?.limit ?? 10,\n starting_after: input?.startingAfter,\n ending_before: input?.endingBefore,\n });\n return success(sessions);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\n// ─── Payment Links ───────────────────────────────────────────────────\n\nexport async function createPaymentLink(\n input: CreatePaymentLinkInput\n): Promise<SDKResult<Stripe.PaymentLink>> {\n try {\n const stripe = getStripe();\n const paymentLink = await stripe.paymentLinks.create({\n line_items: input.lineItems.map((item) => ({\n price: item.priceId,\n quantity: item.quantity,\n adjustable_quantity: item.adjustableQuantity\n ? {\n enabled: item.adjustableQuantity.enabled,\n minimum: item.adjustableQuantity.minimum,\n maximum: item.adjustableQuantity.maximum,\n }\n : undefined,\n })),\n metadata: input.metadata,\n after_completion: input.afterCompletion\n ? {\n type: input.afterCompletion.type,\n redirect: input.afterCompletion.redirectUrl\n ? { url: input.afterCompletion.redirectUrl }\n : undefined,\n }\n : undefined,\n allow_promotion_codes: input.allowPromotionCodes,\n automatic_tax: input.automaticTax ? { enabled: true } : undefined,\n billing_address_collection: input.billingAddressCollection,\n shipping_address_collection: input.shippingAddressCollection\n ? { allowed_countries: input.shippingAddressCollection.allowedCountries as Stripe.PaymentLinkCreateParams.ShippingAddressCollection.AllowedCountry[] }\n : undefined,\n });\n return success(paymentLink);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function retrievePaymentLink(\n paymentLinkId: string\n): Promise<SDKResult<Stripe.PaymentLink>> {\n try {\n const stripe = getStripe();\n const paymentLink = await stripe.paymentLinks.retrieve(paymentLinkId);\n return success(paymentLink);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\n// ─── Setup Intents ───────────────────────────────────────────────────\n\nexport async function createSetupIntent(\n input: CreateSetupIntentInput\n): Promise<SDKResult<Stripe.SetupIntent>> {\n try {\n const stripe = getStripe();\n const setupIntent = await stripe.setupIntents.create({\n customer: input.customerId,\n payment_method_types: input.paymentMethodTypes,\n usage: input.usage,\n metadata: input.metadata,\n });\n return success(setupIntent);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function retrieveSetupIntent(\n setupIntentId: string\n): Promise<SDKResult<Stripe.SetupIntent>> {\n try {\n const stripe = getStripe();\n const setupIntent = await stripe.setupIntents.retrieve(setupIntentId);\n return success(setupIntent);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\n// ─── Payment Methods ─────────────────────────────────────────────────\n\nexport async function listPaymentMethods(\n customerId: string,\n type?: Stripe.PaymentMethodListParams.Type\n): Promise<SDKResult<Stripe.ApiList<Stripe.PaymentMethod>>> {\n try {\n const stripe = getStripe();\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customerId,\n type: type ?? 'card',\n });\n return success(paymentMethods);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function attachPaymentMethod(\n paymentMethodId: string,\n customerId: string\n): Promise<SDKResult<Stripe.PaymentMethod>> {\n try {\n const stripe = getStripe();\n const paymentMethod = await stripe.paymentMethods.attach(paymentMethodId, {\n customer: customerId,\n });\n return success(paymentMethod);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function detachPaymentMethod(\n paymentMethodId: string\n): Promise<SDKResult<Stripe.PaymentMethod>> {\n try {\n const stripe = getStripe();\n const paymentMethod = await stripe.paymentMethods.detach(paymentMethodId);\n return success(paymentMethod);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n","import type Stripe from 'stripe';\nimport { getStripe } from '../stripe-client';\nimport { handleStripeError, success } from '../../utils/errors';\nimport type {\n CreateCustomerInput,\n UpdateCustomerInput,\n ListCustomersInput,\n CreatePortalSessionInput,\n SDKResult,\n} from '../../types';\n\nexport async function createCustomer(\n input: CreateCustomerInput\n): Promise<SDKResult<Stripe.Customer>> {\n try {\n const stripe = getStripe();\n const customer = await stripe.customers.create({\n email: input.email,\n name: input.name,\n phone: input.phone,\n description: input.description,\n metadata: input.metadata,\n payment_method: input.paymentMethodId,\n invoice_settings: input.paymentMethodId\n ? { default_payment_method: input.paymentMethodId }\n : undefined,\n address: input.address\n ? {\n line1: input.address.line1,\n line2: input.address.line2,\n city: input.address.city,\n state: input.address.state,\n postal_code: input.address.postalCode,\n country: input.address.country,\n }\n : undefined,\n });\n return success(customer);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function retrieveCustomer(\n customerId: string\n): Promise<SDKResult<Stripe.Customer>> {\n try {\n const stripe = getStripe();\n const customer = await stripe.customers.retrieve(customerId, {\n expand: ['subscriptions', 'sources'],\n });\n if (customer.deleted) {\n return {\n data: null,\n error: { message: 'Customer has been deleted', type: 'invalid_request_error' },\n };\n }\n return success(customer as Stripe.Customer);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function updateCustomer(\n input: UpdateCustomerInput\n): Promise<SDKResult<Stripe.Customer>> {\n try {\n const stripe = getStripe();\n const customer = await stripe.customers.update(input.customerId, {\n email: input.email,\n name: input.name,\n phone: input.phone,\n description: input.description,\n metadata: input.metadata,\n invoice_settings: input.defaultPaymentMethodId\n ? { default_payment_method: input.defaultPaymentMethodId }\n : undefined,\n address: input.address\n ? {\n line1: input.address.line1,\n line2: input.address.line2,\n city: input.address.city,\n state: input.address.state,\n postal_code: input.address.postalCode,\n country: input.address.country,\n }\n : undefined,\n });\n return success(customer);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function deleteCustomer(\n customerId: string\n): Promise<SDKResult<Stripe.DeletedCustomer>> {\n try {\n const stripe = getStripe();\n const deleted = await stripe.customers.del(customerId);\n return success(deleted);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function listCustomers(\n input?: ListCustomersInput\n): Promise<SDKResult<Stripe.ApiList<Stripe.Customer>>> {\n try {\n const stripe = getStripe();\n const customers = await stripe.customers.list({\n limit: input?.limit ?? 10,\n starting_after: input?.startingAfter,\n ending_before: input?.endingBefore,\n email: input?.email,\n });\n return success(customers);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function searchCustomers(\n query: string,\n limit?: number\n): Promise<SDKResult<Stripe.ApiSearchResult<Stripe.Customer>>> {\n try {\n const stripe = getStripe();\n const customers = await stripe.customers.search({\n query,\n limit: limit ?? 10,\n });\n return success(customers);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function createPortalSession(\n input: CreatePortalSessionInput\n): Promise<SDKResult<Stripe.BillingPortal.Session>> {\n try {\n const stripe = getStripe();\n const session = await stripe.billingPortal.sessions.create({\n customer: input.customerId,\n return_url: input.returnUrl,\n configuration: input.configuration,\n });\n return success(session);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n","import type Stripe from 'stripe';\nimport { getStripe } from '../stripe-client';\nimport { handleStripeError, success } from '../../utils/errors';\nimport type {\n CreateSubscriptionInput,\n UpdateSubscriptionInput,\n CancelSubscriptionInput,\n PaginationInput,\n SDKResult,\n} from '../../types';\n\nexport async function createSubscription(\n input: CreateSubscriptionInput\n): Promise<SDKResult<Stripe.Subscription>> {\n try {\n const stripe = getStripe();\n\n const items = input.items\n ? input.items.map((item) => ({ price: item.priceId, quantity: item.quantity }))\n : [{ price: input.priceId, quantity: input.quantity ?? 1 }];\n\n const subscription = await stripe.subscriptions.create({\n customer: input.customerId,\n items,\n metadata: input.metadata,\n trial_period_days: input.trialPeriodDays,\n coupon: input.couponId,\n promotion_code: input.promotionCodeId,\n payment_behavior: input.paymentBehavior ?? 'default_incomplete',\n cancel_at_period_end: input.cancelAtPeriodEnd,\n billing_cycle_anchor: input.billingCycleAnchor,\n proration_behavior: input.prorationBehavior,\n expand: ['latest_invoice.payment_intent'],\n });\n return success(subscription);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function retrieveSubscription(\n subscriptionId: string\n): Promise<SDKResult<Stripe.Subscription>> {\n try {\n const stripe = getStripe();\n const subscription = await stripe.subscriptions.retrieve(subscriptionId, {\n expand: ['latest_invoice.payment_intent', 'default_payment_method'],\n });\n return success(subscription);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function updateSubscription(\n input: UpdateSubscriptionInput\n): Promise<SDKResult<Stripe.Subscription>> {\n try {\n const stripe = getStripe();\n\n const params: Stripe.SubscriptionUpdateParams = {\n metadata: input.metadata,\n cancel_at_period_end: input.cancelAtPeriodEnd,\n proration_behavior: input.prorationBehavior,\n coupon: input.couponId,\n };\n\n if (input.items) {\n params.items = input.items.map((item) => ({\n id: item.id,\n price: item.priceId,\n quantity: item.quantity,\n }));\n }\n\n const subscription = await stripe.subscriptions.update(input.subscriptionId, params);\n return success(subscription);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function cancelSubscription(\n input: CancelSubscriptionInput\n): Promise<SDKResult<Stripe.Subscription>> {\n try {\n const stripe = getStripe();\n\n if (input.cancelAtPeriodEnd) {\n const subscription = await stripe.subscriptions.update(input.subscriptionId, {\n cancel_at_period_end: true,\n cancellation_details: input.cancellationDetails\n ? {\n comment: input.cancellationDetails.comment,\n feedback: input.cancellationDetails.feedback,\n }\n : undefined,\n });\n return success(subscription);\n }\n\n const subscription = await stripe.subscriptions.cancel(input.subscriptionId, {\n cancellation_details: input.cancellationDetails\n ? {\n comment: input.cancellationDetails.comment,\n feedback: input.cancellationDetails.feedback,\n }\n : undefined,\n });\n return success(subscription);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function resumeSubscription(\n subscriptionId: string\n): Promise<SDKResult<Stripe.Subscription>> {\n try {\n const stripe = getStripe();\n const subscription = await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n return success(subscription);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n\nexport async function listSubscriptions(\n input?: PaginationInput & { customerId?: string; status?: Stripe.SubscriptionListParams.Status }\n): Promise<SDKResult<Stripe.ApiList<Stripe.Subscription>>> {\n try {\n const stripe = getStripe();\n const subscriptions = await stripe.subscriptions.list({\n limit: input?.limit ?? 10,\n starting_after: input?.startingAfter,\n ending_before: input?.endingBefore,\n customer: input?.customerId,\n status: input?.status,\n });\n return success(subscriptions);\n } catch (error) {\n return handleStripeError(error);\n }\n}\n","/**\n * Next.js specific utilities for Stripe integration.\n *\n * Provides ready-to-use Server Actions and API route helpers.\n */\n\nexport { createNextWebhookHandler, createPagesWebhookHandler } from '../server/webhooks';\n\n// ─── Server Action Helpers ───────────────────────────────────────────\n\nimport {\n createPaymentIntent as _createPaymentIntent,\n createCheckoutSession as _createCheckoutSession,\n createSetupIntent as _createSetupIntent,\n} from '../server/payments';\nimport { createCustomer as _createCustomer } from '../server/customers';\nimport { createPortalSession as _createPortalSession } from '../server/customers';\nimport {\n createSubscription as _createSubscription,\n cancelSubscription as _cancelSubscription,\n resumeSubscription as _resumeSubscription,\n} from '../server/subscriptions';\nimport type {\n CreatePaymentIntentInput,\n CreateCheckoutSessionInput,\n CreateSetupIntentInput,\n CreateCustomerInput,\n CreatePortalSessionInput,\n CreateSubscriptionInput,\n CancelSubscriptionInput,\n} from '../types';\n\n/**\n * Pre-built Server Actions for Next.js App Router.\n *\n * Usage in a Server Component or `use server` file:\n * ```ts\n * 'use server';\n * import { actions } from '@stripe-sdk/core/next';\n *\n * export const createPayment = async (amount: number, currency: string) => {\n * const result = await actions.createPaymentIntent({ amount, currency });\n * if (result.error) throw new Error(result.error.message);\n * return { clientSecret: result.data.client_secret };\n * };\n * ```\n */\nexport const actions = {\n createPaymentIntent: async (input: CreatePaymentIntentInput) => {\n return _createPaymentIntent(input);\n },\n\n createCheckoutSession: async (input: CreateCheckoutSessionInput) => {\n return _createCheckoutSession(input);\n },\n\n createSetupIntent: async (input: CreateSetupIntentInput) => {\n return _createSetupIntent(input);\n },\n\n createCustomer: async (input: CreateCustomerInput) => {\n return _createCustomer(input);\n },\n\n createPortalSession: async (input: CreatePortalSessionInput) => {\n return _createPortalSession(input);\n },\n\n createSubscription: async (input: CreateSubscriptionInput) => {\n return _createSubscription(input);\n },\n\n cancelSubscription: async (input: CancelSubscriptionInput) => {\n return _cancelSubscription(input);\n },\n\n resumeSubscription: async (subscriptionId: string) => {\n return _resumeSubscription(subscriptionId);\n },\n};\n\n// ─── API Route Helpers ───────────────────────────────────────────────\n\n/**\n * Creates a Next.js API route handler for creating payment intents.\n *\n * Usage in app/api/create-payment-intent/route.ts:\n * ```ts\n * import { createPaymentIntentRoute } from '@stripe-sdk/core/next';\n * export const POST = createPaymentIntentRoute();\n * ```\n */\nexport function createPaymentIntentRoute(\n options?: {\n beforeCreate?: (input: CreatePaymentIntentInput, request: Request) => Promise<CreatePaymentIntentInput>;\n }\n) {\n return async function POST(request: Request): Promise<Response> {\n try {\n let input: CreatePaymentIntentInput = await request.json();\n\n if (options?.beforeCreate) {\n input = await options.beforeCreate(input, request);\n }\n\n const result = await _createPaymentIntent(input);\n\n if (result.error) {\n return new Response(JSON.stringify(result.error), {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n return new Response(\n JSON.stringify({ clientSecret: result.data.client_secret, id: result.data.id }),\n { status: 200, headers: { 'Content-Type': 'application/json' } }\n );\n } catch (error) {\n return new Response(\n JSON.stringify({ error: error instanceof Error ? error.message : 'Internal error' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n };\n}\n\n/**\n * Creates a Next.js API route handler for creating checkout sessions.\n *\n * Usage in app/api/create-checkout-session/route.ts:\n * ```ts\n * import { createCheckoutSessionRoute } from '@stripe-sdk/core/next';\n * export const POST = createCheckoutSessionRoute();\n * ```\n */\nexport function createCheckoutSessionRoute(\n options?: {\n beforeCreate?: (input: CreateCheckoutSessionInput, request: Request) => Promise<CreateCheckoutSessionInput>;\n }\n) {\n return async function POST(request: Request): Promise<Response> {\n try {\n let input: CreateCheckoutSessionInput = await request.json();\n\n if (options?.beforeCreate) {\n input = await options.beforeCreate(input, request);\n }\n\n const result = await _createCheckoutSession(input);\n\n if (result.error) {\n return new Response(JSON.stringify(result.error), {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n return new Response(\n JSON.stringify({ sessionId: result.data.id, url: result.data.url }),\n { status: 200, headers: { 'Content-Type': 'application/json' } }\n );\n } catch (error) {\n return new Response(\n JSON.stringify({ error: error instanceof Error ? error.message : 'Internal error' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n };\n}\n\n/**\n * Creates a Next.js API route handler for creating portal sessions.\n *\n * Usage in app/api/create-portal-session/route.ts:\n * ```ts\n * import { createPortalSessionRoute } from '@stripe-sdk/core/next';\n * export const POST = createPortalSessionRoute();\n * ```\n */\nexport function createPortalSessionRoute() {\n return async function POST(request: Request): Promise<Response> {\n try {\n const input: CreatePortalSessionInput = await request.json();\n const result = await _createPortalSession(input);\n\n if (result.error) {\n return new Response(JSON.stringify(result.error), {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n return new Response(\n JSON.stringify({ url: result.data.url }),\n { status: 200, headers: { 'Content-Type': 'application/json' } }\n );\n } catch (error) {\n return new Response(\n JSON.stringify({ error: error instanceof Error ? error.message : 'Internal error' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n };\n}\n"]}