@digilogiclabs/saas-factory-payments 0.2.1 → 0.3.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/dist/server.d.mts +67 -1
- package/dist/server.d.ts +67 -1
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +1 -1
- package/dist/server.mjs.map +1 -1
- package/dist/web.d.mts +89 -9
- package/dist/web.d.ts +89 -9
- package/dist/web.js +9 -9
- package/dist/web.js.map +1 -1
- package/dist/web.mjs +9 -9
- package/dist/web.mjs.map +1 -1
- package/package.json +2 -1
package/dist/server.d.mts
CHANGED
|
@@ -122,4 +122,70 @@ declare const createStripeWebhookHandler: (secretKey: string, handlers?: Webhook
|
|
|
122
122
|
declare const createStripeWebhookMiddleware: (secretKey: string, webhookSecret: string, handlers?: WebhookHandlers) => (req: Request, res: Response) => Promise<Response<any, Record<string, any>> | undefined>;
|
|
123
123
|
declare const createNextJSWebhookHandler: (secretKey: string, webhookSecret: string, handlers?: WebhookHandlers) => (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
|
|
124
124
|
|
|
125
|
-
|
|
125
|
+
interface CreateCheckoutSessionOptions {
|
|
126
|
+
priceId: string;
|
|
127
|
+
customerId?: string;
|
|
128
|
+
successUrl: string;
|
|
129
|
+
cancelUrl: string;
|
|
130
|
+
mode?: 'payment' | 'subscription' | 'setup';
|
|
131
|
+
metadata?: Record<string, string>;
|
|
132
|
+
}
|
|
133
|
+
interface ProcessPaymentOptions {
|
|
134
|
+
amount: number;
|
|
135
|
+
currency: string;
|
|
136
|
+
paymentMethodId: string;
|
|
137
|
+
customerId?: string;
|
|
138
|
+
description?: string;
|
|
139
|
+
metadata?: Record<string, string>;
|
|
140
|
+
}
|
|
141
|
+
interface CreateSubscriptionOptions {
|
|
142
|
+
customerId: string;
|
|
143
|
+
priceId: string;
|
|
144
|
+
paymentMethodId?: string;
|
|
145
|
+
trialPeriodDays?: number;
|
|
146
|
+
metadata?: Record<string, string>;
|
|
147
|
+
}
|
|
148
|
+
interface UpdateSubscriptionOptions {
|
|
149
|
+
subscriptionId: string;
|
|
150
|
+
priceId?: string;
|
|
151
|
+
quantity?: number;
|
|
152
|
+
metadata?: Record<string, string>;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Create a Stripe checkout session
|
|
156
|
+
*/
|
|
157
|
+
declare const createStripeCheckoutSession: (stripe: Stripe, options: CreateCheckoutSessionOptions) => Promise<Stripe.Checkout.Session>;
|
|
158
|
+
/**
|
|
159
|
+
* Process a one-time payment
|
|
160
|
+
*/
|
|
161
|
+
declare const processPayment: (stripe: Stripe, options: ProcessPaymentOptions) => Promise<Stripe.PaymentIntent>;
|
|
162
|
+
/**
|
|
163
|
+
* Create a subscription
|
|
164
|
+
*/
|
|
165
|
+
declare const createSubscription: (stripe: Stripe, options: CreateSubscriptionOptions) => Promise<Stripe.Subscription>;
|
|
166
|
+
/**
|
|
167
|
+
* Update a subscription
|
|
168
|
+
*/
|
|
169
|
+
declare const updateSubscription: (stripe: Stripe, options: UpdateSubscriptionOptions) => Promise<Stripe.Subscription>;
|
|
170
|
+
/**
|
|
171
|
+
* Cancel a subscription
|
|
172
|
+
*/
|
|
173
|
+
declare const cancelSubscription: (stripe: Stripe, subscriptionId: string, cancelAtPeriodEnd?: boolean) => Promise<Stripe.Subscription>;
|
|
174
|
+
/**
|
|
175
|
+
* Validate Stripe webhook signature
|
|
176
|
+
*/
|
|
177
|
+
declare const validateStripeSignature: (payload: string | Buffer, signature: string, endpointSecret: string) => Stripe.Event;
|
|
178
|
+
/**
|
|
179
|
+
* Handle common Stripe webhook events
|
|
180
|
+
*/
|
|
181
|
+
declare const handleStripeWebhook: (event: Stripe.Event, handlers: {
|
|
182
|
+
onPaymentSucceeded?: (paymentIntent: Stripe.PaymentIntent) => Promise<void>;
|
|
183
|
+
onPaymentFailed?: (paymentIntent: Stripe.PaymentIntent) => Promise<void>;
|
|
184
|
+
onSubscriptionCreated?: (subscription: Stripe.Subscription) => Promise<void>;
|
|
185
|
+
onSubscriptionUpdated?: (subscription: Stripe.Subscription) => Promise<void>;
|
|
186
|
+
onSubscriptionDeleted?: (subscription: Stripe.Subscription) => Promise<void>;
|
|
187
|
+
onInvoicePaid?: (invoice: Stripe.Invoice) => Promise<void>;
|
|
188
|
+
onInvoicePaymentFailed?: (invoice: Stripe.Invoice) => Promise<void>;
|
|
189
|
+
}) => Promise<void>;
|
|
190
|
+
|
|
191
|
+
export { type CreateCheckoutSessionOptions, type CreateSubscriptionOptions, type ProcessPaymentOptions, StripeServerAPI, StripeWebhookHandler, type UpdateSubscriptionOptions, type WebhookHandlers, cancelSubscription, createNextJSWebhookHandler, createStripeCheckoutSession, createStripeWebhookHandler, createStripeWebhookMiddleware, createSubscription, handleStripeWebhook, processPayment, updateSubscription, validateStripeSignature };
|
package/dist/server.d.ts
CHANGED
|
@@ -122,4 +122,70 @@ declare const createStripeWebhookHandler: (secretKey: string, handlers?: Webhook
|
|
|
122
122
|
declare const createStripeWebhookMiddleware: (secretKey: string, webhookSecret: string, handlers?: WebhookHandlers) => (req: Request, res: Response) => Promise<Response<any, Record<string, any>> | undefined>;
|
|
123
123
|
declare const createNextJSWebhookHandler: (secretKey: string, webhookSecret: string, handlers?: WebhookHandlers) => (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
|
|
124
124
|
|
|
125
|
-
|
|
125
|
+
interface CreateCheckoutSessionOptions {
|
|
126
|
+
priceId: string;
|
|
127
|
+
customerId?: string;
|
|
128
|
+
successUrl: string;
|
|
129
|
+
cancelUrl: string;
|
|
130
|
+
mode?: 'payment' | 'subscription' | 'setup';
|
|
131
|
+
metadata?: Record<string, string>;
|
|
132
|
+
}
|
|
133
|
+
interface ProcessPaymentOptions {
|
|
134
|
+
amount: number;
|
|
135
|
+
currency: string;
|
|
136
|
+
paymentMethodId: string;
|
|
137
|
+
customerId?: string;
|
|
138
|
+
description?: string;
|
|
139
|
+
metadata?: Record<string, string>;
|
|
140
|
+
}
|
|
141
|
+
interface CreateSubscriptionOptions {
|
|
142
|
+
customerId: string;
|
|
143
|
+
priceId: string;
|
|
144
|
+
paymentMethodId?: string;
|
|
145
|
+
trialPeriodDays?: number;
|
|
146
|
+
metadata?: Record<string, string>;
|
|
147
|
+
}
|
|
148
|
+
interface UpdateSubscriptionOptions {
|
|
149
|
+
subscriptionId: string;
|
|
150
|
+
priceId?: string;
|
|
151
|
+
quantity?: number;
|
|
152
|
+
metadata?: Record<string, string>;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Create a Stripe checkout session
|
|
156
|
+
*/
|
|
157
|
+
declare const createStripeCheckoutSession: (stripe: Stripe, options: CreateCheckoutSessionOptions) => Promise<Stripe.Checkout.Session>;
|
|
158
|
+
/**
|
|
159
|
+
* Process a one-time payment
|
|
160
|
+
*/
|
|
161
|
+
declare const processPayment: (stripe: Stripe, options: ProcessPaymentOptions) => Promise<Stripe.PaymentIntent>;
|
|
162
|
+
/**
|
|
163
|
+
* Create a subscription
|
|
164
|
+
*/
|
|
165
|
+
declare const createSubscription: (stripe: Stripe, options: CreateSubscriptionOptions) => Promise<Stripe.Subscription>;
|
|
166
|
+
/**
|
|
167
|
+
* Update a subscription
|
|
168
|
+
*/
|
|
169
|
+
declare const updateSubscription: (stripe: Stripe, options: UpdateSubscriptionOptions) => Promise<Stripe.Subscription>;
|
|
170
|
+
/**
|
|
171
|
+
* Cancel a subscription
|
|
172
|
+
*/
|
|
173
|
+
declare const cancelSubscription: (stripe: Stripe, subscriptionId: string, cancelAtPeriodEnd?: boolean) => Promise<Stripe.Subscription>;
|
|
174
|
+
/**
|
|
175
|
+
* Validate Stripe webhook signature
|
|
176
|
+
*/
|
|
177
|
+
declare const validateStripeSignature: (payload: string | Buffer, signature: string, endpointSecret: string) => Stripe.Event;
|
|
178
|
+
/**
|
|
179
|
+
* Handle common Stripe webhook events
|
|
180
|
+
*/
|
|
181
|
+
declare const handleStripeWebhook: (event: Stripe.Event, handlers: {
|
|
182
|
+
onPaymentSucceeded?: (paymentIntent: Stripe.PaymentIntent) => Promise<void>;
|
|
183
|
+
onPaymentFailed?: (paymentIntent: Stripe.PaymentIntent) => Promise<void>;
|
|
184
|
+
onSubscriptionCreated?: (subscription: Stripe.Subscription) => Promise<void>;
|
|
185
|
+
onSubscriptionUpdated?: (subscription: Stripe.Subscription) => Promise<void>;
|
|
186
|
+
onSubscriptionDeleted?: (subscription: Stripe.Subscription) => Promise<void>;
|
|
187
|
+
onInvoicePaid?: (invoice: Stripe.Invoice) => Promise<void>;
|
|
188
|
+
onInvoicePaymentFailed?: (invoice: Stripe.Invoice) => Promise<void>;
|
|
189
|
+
}) => Promise<void>;
|
|
190
|
+
|
|
191
|
+
export { type CreateCheckoutSessionOptions, type CreateSubscriptionOptions, type ProcessPaymentOptions, StripeServerAPI, StripeWebhookHandler, type UpdateSubscriptionOptions, type WebhookHandlers, cancelSubscription, createNextJSWebhookHandler, createStripeCheckoutSession, createStripeWebhookHandler, createStripeWebhookMiddleware, createSubscription, handleStripeWebhook, processPayment, updateSubscription, validateStripeSignature };
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var P=Object.create;var p=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var C=(r,e)=>{for(var t in e)p(r,t,{get:e[t],enumerable:!0})},l=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of b(e))!_.call(r,s)&&s!==t&&p(r,s,{get:()=>e[s],enumerable:!(n=E(e,s))||n.enumerable});return r};var T=(r,e,t)=>(t=r!=null?P(g(r)):{},l(e||!r||!r.__esModule?p(t,"default",{value:r,enumerable:!0}):t,r)),v=r=>l(p({},"__esModule",{value:!0}),r);var f={};C(f,{StripeServerAPI:()=>d,StripeWebhookHandler:()=>c,createNextJSWebhookHandler:()=>I,createStripeWebhookHandler:()=>S,createStripeWebhookMiddleware:()=>y});module.exports=v(f);var h=T(require("stripe"));var m="2023-10-16";var a={CUSTOMER_SUBSCRIPTION_CREATED:"customer.subscription.created",CUSTOMER_SUBSCRIPTION_UPDATED:"customer.subscription.updated",CUSTOMER_SUBSCRIPTION_DELETED:"customer.subscription.deleted",INVOICE_PAYMENT_SUCCEEDED:"invoice.payment_succeeded",INVOICE_PAYMENT_FAILED:"invoice.payment_failed",CHECKOUT_SESSION_COMPLETED:"checkout.session.completed",PAYMENT_INTENT_SUCCEEDED:"payment_intent.succeeded",PAYMENT_INTENT_PAYMENT_FAILED:"payment_intent.payment_failed"};var d=class{stripe;constructor(e,t){this.stripe=new h.default(e,{apiVersion:t?.apiVersion||m,typescript:!0})}async createCustomer(e){return this.stripe.customers.create({email:e.email,name:e.name,phone:e.phone,metadata:e.metadata})}async getCustomer(e){return this.stripe.customers.retrieve(e)}async updateCustomer(e,t){return this.stripe.customers.update(e,t)}async deleteCustomer(e){return this.stripe.customers.del(e)}async createSubscription(e){return this.stripe.subscriptions.create({customer:e.customerId,items:[{price:e.priceId,quantity:e.quantity||1}],trial_period_days:e.trialPeriodDays,metadata:e.metadata,payment_behavior:e.paymentBehavior||"default_incomplete",payment_settings:{save_default_payment_method:"on_subscription"},expand:["latest_invoice.payment_intent"]})}async getSubscription(e){return this.stripe.subscriptions.retrieve(e,{expand:["default_payment_method"]})}async updateSubscription(e,t){let n={};if(t.priceId){let i=(await this.getSubscription(e)).items.data[0];n.items=[{id:i.id,price:t.priceId,quantity:t.quantity||i.quantity}]}return t.metadata&&(n.metadata=t.metadata),typeof t.cancelAtPeriodEnd=="boolean"&&(n.cancel_at_period_end=t.cancelAtPeriodEnd),this.stripe.subscriptions.update(e,n)}async cancelSubscription(e,t=!1){return t?this.stripe.subscriptions.cancel(e):this.stripe.subscriptions.update(e,{cancel_at_period_end:!0})}async reactivateSubscription(e){return this.stripe.subscriptions.update(e,{cancel_at_period_end:!1})}async getCustomerSubscriptions(e){return this.stripe.subscriptions.list({customer:e,expand:["data.default_payment_method"]})}async createCheckoutSession(e){let t={payment_method_types:["card"],line_items:[{price:e.priceId,quantity:1}],mode:e.mode||"subscription",success_url:e.successUrl,cancel_url:e.cancelUrl,allow_promotion_codes:e.allowPromotionCodes,billing_address_collection:e.billingAddressCollection,metadata:e.metadata};return e.customerId?t.customer=e.customerId:e.customerEmail&&(t.customer_email=e.customerEmail),e.mode==="subscription"&&e.trialPeriodDays&&(t.subscription_data={trial_period_days:e.trialPeriodDays}),this.stripe.checkout.sessions.create(t)}async getPaymentIntent(e){return this.stripe.paymentIntents.retrieve(e)}async createPaymentIntent(e){return this.stripe.paymentIntents.create({amount:e.amount,currency:e.currency,customer:e.customerId,payment_method_types:e.paymentMethodTypes||["card"],metadata:e.metadata,description:e.description})}async confirmPaymentIntent(e,t){return this.stripe.paymentIntents.confirm(e,{payment_method:t?.paymentMethod})}async createSetupIntent(e){return this.stripe.setupIntents.create({customer:e.customerId,payment_method_types:e.paymentMethodTypes||["card"],metadata:e.metadata,usage:"off_session"})}async createPortalSession(e){return this.stripe.billingPortal.sessions.create({customer:e.customerId,return_url:e.returnUrl})}async getCustomerPaymentMethods(e,t="card"){return this.stripe.paymentMethods.list({customer:e,type:t})}async attachPaymentMethod(e,t){return this.stripe.paymentMethods.attach(e,{customer:t})}async detachPaymentMethod(e){return this.stripe.paymentMethods.detach(e)}async setDefaultPaymentMethod(e,t){return this.stripe.customers.update(e,{invoice_settings:{default_payment_method:t}})}async getCustomerInvoices(e,t=10){return this.stripe.invoices.list({customer:e,limit:t})}async getInvoice(e){return this.stripe.invoices.retrieve(e)}constructWebhookEvent(e,t,n){return this.stripe.webhooks.constructEvent(e,t,n)}async getPrice(e){return this.stripe.prices.retrieve(e,{expand:["product"]})}async getPrices(e){return this.stripe.prices.list({active:e?.active,limit:e?.limit||10,product:e?.product,expand:["data.product"]})}async getProduct(e){return this.stripe.products.retrieve(e)}async createEphemeralKey(e,t){return this.stripe.ephemeralKeys.create({customer:e},{apiVersion:t})}};var c=class{stripeAPI;handlers;constructor(e,t={}){this.stripeAPI=new d(e),this.handlers=t}async handleWebhook(e,t,n){try{let s=this.stripeAPI.constructWebhookEvent(e,t,n);return console.log(`Received webhook event: ${s.type}`),await this.processEvent(s),{success:!0}}catch(s){let i=s instanceof Error?s.message:"Unknown webhook error";return console.error("Webhook error:",i),{success:!1,error:i}}}async processEvent(e){switch(e.type){case a.CUSTOMER_SUBSCRIPTION_CREATED:await this.handleSubscriptionCreated(e.data.object);break;case a.CUSTOMER_SUBSCRIPTION_UPDATED:await this.handleSubscriptionUpdated(e.data.object);break;case a.CUSTOMER_SUBSCRIPTION_DELETED:await this.handleSubscriptionDeleted(e.data.object);break;case a.INVOICE_PAYMENT_SUCCEEDED:await this.handleInvoicePaymentSucceeded(e.data.object);break;case a.INVOICE_PAYMENT_FAILED:await this.handleInvoicePaymentFailed(e.data.object);break;case a.CHECKOUT_SESSION_COMPLETED:await this.handleCheckoutSessionCompleted(e.data.object);break;case a.PAYMENT_INTENT_SUCCEEDED:await this.handlePaymentIntentSucceeded(e.data.object);break;case a.PAYMENT_INTENT_PAYMENT_FAILED:await this.handlePaymentIntentFailed(e.data.object);break;default:console.log(`Unhandled event type: ${e.type}`)}}async handleSubscriptionCreated(e){console.log(`Subscription created: ${e.id}`),this.handlers.onCustomerSubscriptionCreated&&await this.handlers.onCustomerSubscriptionCreated(e),console.log(`Customer ${e.customer} subscribed to ${e.items.data[0]?.price.id}`)}async handleSubscriptionUpdated(e){console.log(`Subscription updated: ${e.id}`),this.handlers.onCustomerSubscriptionUpdated&&await this.handlers.onCustomerSubscriptionUpdated(e),console.log(`Subscription ${e.id} status: ${e.status}`)}async handleSubscriptionDeleted(e){console.log(`Subscription deleted: ${e.id}`),this.handlers.onCustomerSubscriptionDeleted&&await this.handlers.onCustomerSubscriptionDeleted(e),console.log(`Customer ${e.customer} cancelled subscription ${e.id}`)}async handleInvoicePaymentSucceeded(e){console.log(`Invoice payment succeeded: ${e.id}`),this.handlers.onInvoicePaymentSucceeded&&await this.handlers.onInvoicePaymentSucceeded(e);let t=e.subscription;t&&console.log(`Payment succeeded for subscription ${t}`)}async handleInvoicePaymentFailed(e){console.log(`Invoice payment failed: ${e.id}`),this.handlers.onInvoicePaymentFailed&&await this.handlers.onInvoicePaymentFailed(e);let t=e.subscription;t&&console.log(`Payment failed for subscription ${t}`)}async handleCheckoutSessionCompleted(e){console.log(`Checkout session completed: ${e.id}`),this.handlers.onCheckoutSessionCompleted&&await this.handlers.onCheckoutSessionCompleted(e),e.mode==="subscription"?console.log(`Subscription checkout completed for customer ${e.customer}`):console.log(`Payment checkout completed for customer ${e.customer}`)}async handlePaymentIntentSucceeded(e){console.log(`Payment intent succeeded: ${e.id}`),this.handlers.onPaymentIntentSucceeded&&await this.handlers.onPaymentIntentSucceeded(e),console.log(`Payment of ${e.amount} ${e.currency} succeeded`)}async handlePaymentIntentFailed(e){console.log(`Payment intent failed: ${e.id}`),this.handlers.onPaymentIntentPaymentFailed&&await this.handlers.onPaymentIntentPaymentFailed(e),console.log(`Payment of ${e.amount} ${e.currency} failed`)}},S=(r,e={})=>new c(r,e),y=(r,e,t={})=>{let n=new c(r,t);return async(s,i)=>{try{let o=s.headers["stripe-signature"];if(!o)return i.status(400).json({error:"Missing stripe-signature header"});let u=await n.handleWebhook(s.body,Array.isArray(o)?o[0]:o,e);u.success?i.status(200).json({received:!0}):i.status(400).json({error:u.error})}catch(o){console.error("Webhook middleware error:",o),i.status(500).json({error:"Internal server error"})}}},I=(r,e,t={})=>{let n=new c(r,t);return async(s,i)=>{if(s.method!=="POST")return i.setHeader("Allow","POST"),i.status(405).json({error:"Method not allowed"});try{let o=s.headers["stripe-signature"];if(!o)return i.status(400).json({error:"Missing stripe-signature header"});let u=await n.handleWebhook(s.body,Array.isArray(o)?o[0]:o,e);u.success?i.status(200).json({received:!0}):i.status(400).json({error:u.error})}catch(o){console.error("Webhook handler error:",o),i.status(500).json({error:"Internal server error"})}}};0&&(module.exports={StripeServerAPI,StripeWebhookHandler,createNextJSWebhookHandler,createStripeWebhookHandler,createStripeWebhookMiddleware});
|
|
1
|
+
"use strict";var k=Object.create;var m=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var A=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty;var R=(i,e)=>{for(var t in e)m(i,t,{get:e[t],enumerable:!0})},l=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of O(e))!U.call(i,r)&&r!==t&&m(i,r,{get:()=>e[r],enumerable:!(s=N(e,r))||s.enumerable});return i};var S=(i,e,t)=>(t=i!=null?k(A(i)):{},l(e||!i||!i.__esModule?m(t,"default",{value:i,enumerable:!0}):t,i)),w=i=>l(m({},"__esModule",{value:!0}),i);var M={};R(M,{StripeServerAPI:()=>u,StripeWebhookHandler:()=>p,cancelSubscription:()=>f,createNextJSWebhookHandler:()=>I,createStripeCheckoutSession:()=>_,createStripeWebhookHandler:()=>h,createStripeWebhookMiddleware:()=>P,createSubscription:()=>C,handleStripeWebhook:()=>D,processPayment:()=>E,updateSubscription:()=>v,validateStripeSignature:()=>T});module.exports=w(M);var b=S(require("stripe"));var y="2023-10-16";var c={CUSTOMER_SUBSCRIPTION_CREATED:"customer.subscription.created",CUSTOMER_SUBSCRIPTION_UPDATED:"customer.subscription.updated",CUSTOMER_SUBSCRIPTION_DELETED:"customer.subscription.deleted",INVOICE_PAYMENT_SUCCEEDED:"invoice.payment_succeeded",INVOICE_PAYMENT_FAILED:"invoice.payment_failed",CHECKOUT_SESSION_COMPLETED:"checkout.session.completed",PAYMENT_INTENT_SUCCEEDED:"payment_intent.succeeded",PAYMENT_INTENT_PAYMENT_FAILED:"payment_intent.payment_failed"};var u=class{stripe;constructor(e,t){this.stripe=new b.default(e,{apiVersion:t?.apiVersion||y,typescript:!0})}async createCustomer(e){return this.stripe.customers.create({email:e.email,name:e.name,phone:e.phone,metadata:e.metadata})}async getCustomer(e){return this.stripe.customers.retrieve(e)}async updateCustomer(e,t){return this.stripe.customers.update(e,t)}async deleteCustomer(e){return this.stripe.customers.del(e)}async createSubscription(e){return this.stripe.subscriptions.create({customer:e.customerId,items:[{price:e.priceId,quantity:e.quantity||1}],trial_period_days:e.trialPeriodDays,metadata:e.metadata,payment_behavior:e.paymentBehavior||"default_incomplete",payment_settings:{save_default_payment_method:"on_subscription"},expand:["latest_invoice.payment_intent"]})}async getSubscription(e){return this.stripe.subscriptions.retrieve(e,{expand:["default_payment_method"]})}async updateSubscription(e,t){let s={};if(t.priceId){let n=(await this.getSubscription(e)).items.data[0];s.items=[{id:n.id,price:t.priceId,quantity:t.quantity||n.quantity}]}return t.metadata&&(s.metadata=t.metadata),typeof t.cancelAtPeriodEnd=="boolean"&&(s.cancel_at_period_end=t.cancelAtPeriodEnd),this.stripe.subscriptions.update(e,s)}async cancelSubscription(e,t=!1){return t?this.stripe.subscriptions.cancel(e):this.stripe.subscriptions.update(e,{cancel_at_period_end:!0})}async reactivateSubscription(e){return this.stripe.subscriptions.update(e,{cancel_at_period_end:!1})}async getCustomerSubscriptions(e){return this.stripe.subscriptions.list({customer:e,expand:["data.default_payment_method"]})}async createCheckoutSession(e){let t={payment_method_types:["card"],line_items:[{price:e.priceId,quantity:1}],mode:e.mode||"subscription",success_url:e.successUrl,cancel_url:e.cancelUrl,allow_promotion_codes:e.allowPromotionCodes,billing_address_collection:e.billingAddressCollection,metadata:e.metadata};return e.customerId?t.customer=e.customerId:e.customerEmail&&(t.customer_email=e.customerEmail),e.mode==="subscription"&&e.trialPeriodDays&&(t.subscription_data={trial_period_days:e.trialPeriodDays}),this.stripe.checkout.sessions.create(t)}async getPaymentIntent(e){return this.stripe.paymentIntents.retrieve(e)}async createPaymentIntent(e){return this.stripe.paymentIntents.create({amount:e.amount,currency:e.currency,customer:e.customerId,payment_method_types:e.paymentMethodTypes||["card"],metadata:e.metadata,description:e.description})}async confirmPaymentIntent(e,t){return this.stripe.paymentIntents.confirm(e,{payment_method:t?.paymentMethod})}async createSetupIntent(e){return this.stripe.setupIntents.create({customer:e.customerId,payment_method_types:e.paymentMethodTypes||["card"],metadata:e.metadata,usage:"off_session"})}async createPortalSession(e){return this.stripe.billingPortal.sessions.create({customer:e.customerId,return_url:e.returnUrl})}async getCustomerPaymentMethods(e,t="card"){return this.stripe.paymentMethods.list({customer:e,type:t})}async attachPaymentMethod(e,t){return this.stripe.paymentMethods.attach(e,{customer:t})}async detachPaymentMethod(e){return this.stripe.paymentMethods.detach(e)}async setDefaultPaymentMethod(e,t){return this.stripe.customers.update(e,{invoice_settings:{default_payment_method:t}})}async getCustomerInvoices(e,t=10){return this.stripe.invoices.list({customer:e,limit:t})}async getInvoice(e){return this.stripe.invoices.retrieve(e)}constructWebhookEvent(e,t,s){return this.stripe.webhooks.constructEvent(e,t,s)}async getPrice(e){return this.stripe.prices.retrieve(e,{expand:["product"]})}async getPrices(e){return this.stripe.prices.list({active:e?.active,limit:e?.limit||10,product:e?.product,expand:["data.product"]})}async getProduct(e){return this.stripe.products.retrieve(e)}async createEphemeralKey(e,t){return this.stripe.ephemeralKeys.create({customer:e},{apiVersion:t})}};var p=class{stripeAPI;handlers;constructor(e,t={}){this.stripeAPI=new u(e),this.handlers=t}async handleWebhook(e,t,s){try{let r=this.stripeAPI.constructWebhookEvent(e,t,s);return console.log(`Received webhook event: ${r.type}`),await this.processEvent(r),{success:!0}}catch(r){let n=r instanceof Error?r.message:"Unknown webhook error";return console.error("Webhook error:",n),{success:!1,error:n}}}async processEvent(e){switch(e.type){case c.CUSTOMER_SUBSCRIPTION_CREATED:await this.handleSubscriptionCreated(e.data.object);break;case c.CUSTOMER_SUBSCRIPTION_UPDATED:await this.handleSubscriptionUpdated(e.data.object);break;case c.CUSTOMER_SUBSCRIPTION_DELETED:await this.handleSubscriptionDeleted(e.data.object);break;case c.INVOICE_PAYMENT_SUCCEEDED:await this.handleInvoicePaymentSucceeded(e.data.object);break;case c.INVOICE_PAYMENT_FAILED:await this.handleInvoicePaymentFailed(e.data.object);break;case c.CHECKOUT_SESSION_COMPLETED:await this.handleCheckoutSessionCompleted(e.data.object);break;case c.PAYMENT_INTENT_SUCCEEDED:await this.handlePaymentIntentSucceeded(e.data.object);break;case c.PAYMENT_INTENT_PAYMENT_FAILED:await this.handlePaymentIntentFailed(e.data.object);break;default:console.log(`Unhandled event type: ${e.type}`)}}async handleSubscriptionCreated(e){console.log(`Subscription created: ${e.id}`),this.handlers.onCustomerSubscriptionCreated&&await this.handlers.onCustomerSubscriptionCreated(e),console.log(`Customer ${e.customer} subscribed to ${e.items.data[0]?.price.id}`)}async handleSubscriptionUpdated(e){console.log(`Subscription updated: ${e.id}`),this.handlers.onCustomerSubscriptionUpdated&&await this.handlers.onCustomerSubscriptionUpdated(e),console.log(`Subscription ${e.id} status: ${e.status}`)}async handleSubscriptionDeleted(e){console.log(`Subscription deleted: ${e.id}`),this.handlers.onCustomerSubscriptionDeleted&&await this.handlers.onCustomerSubscriptionDeleted(e),console.log(`Customer ${e.customer} cancelled subscription ${e.id}`)}async handleInvoicePaymentSucceeded(e){console.log(`Invoice payment succeeded: ${e.id}`),this.handlers.onInvoicePaymentSucceeded&&await this.handlers.onInvoicePaymentSucceeded(e);let t=e.subscription;t&&console.log(`Payment succeeded for subscription ${t}`)}async handleInvoicePaymentFailed(e){console.log(`Invoice payment failed: ${e.id}`),this.handlers.onInvoicePaymentFailed&&await this.handlers.onInvoicePaymentFailed(e);let t=e.subscription;t&&console.log(`Payment failed for subscription ${t}`)}async handleCheckoutSessionCompleted(e){console.log(`Checkout session completed: ${e.id}`),this.handlers.onCheckoutSessionCompleted&&await this.handlers.onCheckoutSessionCompleted(e),e.mode==="subscription"?console.log(`Subscription checkout completed for customer ${e.customer}`):console.log(`Payment checkout completed for customer ${e.customer}`)}async handlePaymentIntentSucceeded(e){console.log(`Payment intent succeeded: ${e.id}`),this.handlers.onPaymentIntentSucceeded&&await this.handlers.onPaymentIntentSucceeded(e),console.log(`Payment of ${e.amount} ${e.currency} succeeded`)}async handlePaymentIntentFailed(e){console.log(`Payment intent failed: ${e.id}`),this.handlers.onPaymentIntentPaymentFailed&&await this.handlers.onPaymentIntentPaymentFailed(e),console.log(`Payment of ${e.amount} ${e.currency} failed`)}},h=(i,e={})=>new p(i,e),P=(i,e,t={})=>{let s=new p(i,t);return async(r,n)=>{try{let o=r.headers["stripe-signature"];if(!o)return n.status(400).json({error:"Missing stripe-signature header"});let a=await s.handleWebhook(r.body,Array.isArray(o)?o[0]:o,e);a.success?n.status(200).json({received:!0}):n.status(400).json({error:a.error})}catch(o){console.error("Webhook middleware error:",o),n.status(500).json({error:"Internal server error"})}}},I=(i,e,t={})=>{let s=new p(i,t);return async(r,n)=>{if(r.method!=="POST")return n.setHeader("Allow","POST"),n.status(405).json({error:"Method not allowed"});try{let o=r.headers["stripe-signature"];if(!o)return n.status(400).json({error:"Missing stripe-signature header"});let a=await s.handleWebhook(r.body,Array.isArray(o)?o[0]:o,e);a.success?n.status(200).json({received:!0}):n.status(400).json({error:a.error})}catch(o){console.error("Webhook handler error:",o),n.status(500).json({error:"Internal server error"})}}};var g=S(require("stripe")),_=async(i,e)=>{let{priceId:t,customerId:s,successUrl:r,cancelUrl:n,mode:o="subscription",metadata:a={}}=e,d={mode:o,success_url:r,cancel_url:n,line_items:[{price:t,quantity:1}],metadata:a};return s?d.customer=s:d.customer_creation="always",o==="subscription"&&(d.subscription_data={metadata:a}),await i.checkout.sessions.create(d)},E=async(i,e)=>{let{amount:t,currency:s,paymentMethodId:r,customerId:n,description:o,metadata:a={}}=e,d={amount:t,currency:s,payment_method:r,confirmation_method:"manual",confirm:!0,return_url:"https://your-website.com/return",metadata:a};return n&&(d.customer=n),o&&(d.description=o),await i.paymentIntents.create(d)},C=async(i,e)=>{let{customerId:t,priceId:s,paymentMethodId:r,trialPeriodDays:n,metadata:o={}}=e,a={customer:t,items:[{price:s}],metadata:o};return r&&(a.default_payment_method=r),n&&(a.trial_period_days=n),await i.subscriptions.create(a)},v=async(i,e)=>{let{subscriptionId:t,priceId:s,quantity:r,metadata:n}=e,o=await i.subscriptions.retrieve(t),a={};return s&&(a.items=[{id:o.items.data[0].id,price:s,quantity:r||1}]),n&&(a.metadata=n),await i.subscriptions.update(t,a)},f=async(i,e,t=!0)=>t?await i.subscriptions.update(e,{cancel_at_period_end:!0}):await i.subscriptions.cancel(e),T=(i,e,t)=>new g.default(process.env.STRIPE_SECRET_KEY,{apiVersion:"2024-06-20"}).webhooks.constructEvent(i,e,t),D=async(i,e)=>{switch(i.type){case"payment_intent.succeeded":e.onPaymentSucceeded&&await e.onPaymentSucceeded(i.data.object);break;case"payment_intent.payment_failed":e.onPaymentFailed&&await e.onPaymentFailed(i.data.object);break;case"customer.subscription.created":e.onSubscriptionCreated&&await e.onSubscriptionCreated(i.data.object);break;case"customer.subscription.updated":e.onSubscriptionUpdated&&await e.onSubscriptionUpdated(i.data.object);break;case"customer.subscription.deleted":e.onSubscriptionDeleted&&await e.onSubscriptionDeleted(i.data.object);break;case"invoice.paid":e.onInvoicePaid&&await e.onInvoicePaid(i.data.object);break;case"invoice.payment_failed":e.onInvoicePaymentFailed&&await e.onInvoicePaymentFailed(i.data.object);break;default:console.log(`Unhandled event type: ${i.type}`)}};0&&(module.exports={StripeServerAPI,StripeWebhookHandler,cancelSubscription,createNextJSWebhookHandler,createStripeCheckoutSession,createStripeWebhookHandler,createStripeWebhookMiddleware,createSubscription,handleStripeWebhook,processPayment,updateSubscription,validateStripeSignature});
|
|
2
2
|
//# sourceMappingURL=server.js.map
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/index.ts","../src/server/api/stripe-server.ts","../src/shared/constants.ts","../src/server/webhooks/stripe.ts"],"sourcesContent":["// API\nexport { StripeServerAPI } from './api/stripe-server';\n\n// Webhooks\nexport {\n StripeWebhookHandler,\n createStripeWebhookHandler,\n createStripeWebhookMiddleware,\n createNextJSWebhookHandler,\n type WebhookHandlers,\n} from './webhooks/stripe';\n","import Stripe from 'stripe';\nimport { STRIPE_API_VERSION } from '../../shared/constants';\n\nexport class StripeServerAPI {\n private stripe: Stripe;\n\n constructor(\n secretKey: string,\n options?: {\n apiVersion?: string;\n typescript?: boolean;\n }\n ) {\n this.stripe = new Stripe(secretKey, {\n apiVersion:\n (options?.apiVersion as Stripe.LatestApiVersion) || STRIPE_API_VERSION,\n typescript: true,\n });\n }\n\n // Customer methods\n async createCustomer(params: {\n email: string;\n name?: string;\n phone?: string;\n metadata?: Record<string, string>;\n }) {\n return this.stripe.customers.create({\n email: params.email,\n name: params.name,\n phone: params.phone,\n metadata: params.metadata,\n });\n }\n\n async getCustomer(customerId: string) {\n return this.stripe.customers.retrieve(customerId);\n }\n\n async updateCustomer(\n customerId: string,\n params: {\n email?: string;\n name?: string;\n phone?: string;\n metadata?: Record<string, string>;\n }\n ) {\n return this.stripe.customers.update(customerId, params);\n }\n\n async deleteCustomer(customerId: string) {\n return this.stripe.customers.del(customerId);\n }\n\n // Subscription methods\n async createSubscription(params: {\n customerId: string;\n priceId: string;\n quantity?: number;\n trialPeriodDays?: number;\n metadata?: Record<string, string>;\n paymentBehavior?:\n | 'default_incomplete'\n | 'error_if_incomplete'\n | 'allow_incomplete';\n }) {\n return this.stripe.subscriptions.create({\n customer: params.customerId,\n items: [\n {\n price: params.priceId,\n quantity: params.quantity || 1,\n },\n ],\n trial_period_days: params.trialPeriodDays,\n metadata: params.metadata,\n payment_behavior: params.paymentBehavior || 'default_incomplete',\n payment_settings: {\n save_default_payment_method: 'on_subscription',\n },\n expand: ['latest_invoice.payment_intent'],\n });\n }\n\n async getSubscription(subscriptionId: string) {\n return this.stripe.subscriptions.retrieve(subscriptionId, {\n expand: ['default_payment_method'],\n });\n }\n\n async updateSubscription(\n subscriptionId: string,\n params: {\n priceId?: string;\n quantity?: number;\n metadata?: Record<string, string>;\n cancelAtPeriodEnd?: boolean;\n }\n ) {\n const updateData: Stripe.SubscriptionUpdateParams = {};\n\n if (params.priceId) {\n // Get current subscription to update items\n const subscription = await this.getSubscription(subscriptionId);\n const currentItem = subscription.items.data[0];\n\n updateData.items = [\n {\n id: currentItem.id,\n price: params.priceId,\n quantity: params.quantity || currentItem.quantity,\n },\n ];\n }\n\n if (params.metadata) {\n updateData.metadata = params.metadata;\n }\n\n if (typeof params.cancelAtPeriodEnd === 'boolean') {\n updateData.cancel_at_period_end = params.cancelAtPeriodEnd;\n }\n\n return this.stripe.subscriptions.update(subscriptionId, updateData);\n }\n\n async cancelSubscription(\n subscriptionId: string,\n immediately: boolean = false\n ) {\n if (immediately) {\n return this.stripe.subscriptions.cancel(subscriptionId);\n } else {\n return this.stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n }\n }\n\n async reactivateSubscription(subscriptionId: string) {\n return this.stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n }\n\n async getCustomerSubscriptions(customerId: string) {\n return this.stripe.subscriptions.list({\n customer: customerId,\n expand: ['data.default_payment_method'],\n });\n }\n\n // Checkout methods\n async createCheckoutSession(params: {\n priceId: string;\n customerId?: string;\n customerEmail?: string;\n successUrl: string;\n cancelUrl: string;\n mode?: 'payment' | 'subscription' | 'setup';\n allowPromotionCodes?: boolean;\n billingAddressCollection?: 'auto' | 'required';\n metadata?: Record<string, string>;\n trialPeriodDays?: number;\n }) {\n const sessionParams: Stripe.Checkout.SessionCreateParams = {\n payment_method_types: ['card'],\n line_items: [\n {\n price: params.priceId,\n quantity: 1,\n },\n ],\n mode: params.mode || 'subscription',\n success_url: params.successUrl,\n cancel_url: params.cancelUrl,\n allow_promotion_codes: params.allowPromotionCodes,\n billing_address_collection: params.billingAddressCollection,\n metadata: params.metadata,\n };\n\n if (params.customerId) {\n sessionParams.customer = params.customerId;\n } else if (params.customerEmail) {\n sessionParams.customer_email = params.customerEmail;\n }\n\n if (params.mode === 'subscription' && params.trialPeriodDays) {\n sessionParams.subscription_data = {\n trial_period_days: params.trialPeriodDays,\n };\n }\n\n return this.stripe.checkout.sessions.create(sessionParams);\n }\n\n // Payment Intent methods\n async getPaymentIntent(paymentIntentId: string) {\n return this.stripe.paymentIntents.retrieve(paymentIntentId);\n }\n\n async createPaymentIntent(params: {\n amount: number;\n currency: string;\n customerId?: string;\n paymentMethodTypes?: string[];\n metadata?: Record<string, string>;\n description?: string;\n }) {\n return this.stripe.paymentIntents.create({\n amount: params.amount,\n currency: params.currency,\n customer: params.customerId,\n payment_method_types: params.paymentMethodTypes || ['card'],\n metadata: params.metadata,\n description: params.description,\n });\n }\n\n async confirmPaymentIntent(\n paymentIntentId: string,\n params?: {\n paymentMethod?: string;\n }\n ) {\n return this.stripe.paymentIntents.confirm(paymentIntentId, {\n payment_method: params?.paymentMethod,\n });\n }\n\n // Setup Intent methods (for subscriptions without immediate payment)\n async createSetupIntent(params: {\n customerId: string;\n paymentMethodTypes?: string[];\n metadata?: Record<string, string>;\n }) {\n return this.stripe.setupIntents.create({\n customer: params.customerId,\n payment_method_types: params.paymentMethodTypes || ['card'],\n metadata: params.metadata,\n usage: 'off_session',\n });\n }\n\n // Customer Portal methods\n async createPortalSession(params: { customerId: string; returnUrl: string }) {\n return this.stripe.billingPortal.sessions.create({\n customer: params.customerId,\n return_url: params.returnUrl,\n });\n }\n\n // Payment Method methods\n async getCustomerPaymentMethods(\n customerId: string,\n type: Stripe.PaymentMethodListParams.Type = 'card'\n ) {\n return this.stripe.paymentMethods.list({\n customer: customerId,\n type,\n });\n }\n\n async attachPaymentMethod(paymentMethodId: string, customerId: string) {\n return this.stripe.paymentMethods.attach(paymentMethodId, {\n customer: customerId,\n });\n }\n\n async detachPaymentMethod(paymentMethodId: string) {\n return this.stripe.paymentMethods.detach(paymentMethodId);\n }\n\n async setDefaultPaymentMethod(customerId: string, paymentMethodId: string) {\n return this.stripe.customers.update(customerId, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n }\n\n // Invoice methods\n async getCustomerInvoices(customerId: string, limit: number = 10) {\n return this.stripe.invoices.list({\n customer: customerId,\n limit,\n });\n }\n\n async getInvoice(invoiceId: string) {\n return this.stripe.invoices.retrieve(invoiceId);\n }\n\n // Webhook methods\n constructWebhookEvent(\n payload: string | Buffer,\n signature: string,\n webhookSecret: string\n ) {\n return this.stripe.webhooks.constructEvent(\n payload,\n signature,\n webhookSecret\n );\n }\n\n // Price and Product methods\n async getPrice(priceId: string) {\n return this.stripe.prices.retrieve(priceId, {\n expand: ['product'],\n });\n }\n\n async getPrices(params?: {\n active?: boolean;\n limit?: number;\n product?: string;\n }) {\n return this.stripe.prices.list({\n active: params?.active,\n limit: params?.limit || 10,\n product: params?.product,\n expand: ['data.product'],\n });\n }\n\n async getProduct(productId: string) {\n return this.stripe.products.retrieve(productId);\n }\n\n // Ephemeral Key methods (for mobile)\n async createEphemeralKey(customerId: string, apiVersion: string) {\n return this.stripe.ephemeralKeys.create(\n { customer: customerId },\n { apiVersion }\n );\n }\n}\n","export const STRIPE_API_VERSION = '2023-10-16';\n\nexport const PAYMENT_METHODS = {\n CARD: 'card',\n BANK_ACCOUNT: 'bank_account',\n SEPA_DEBIT: 'sepa_debit',\n IDEAL: 'ideal',\n SOFORT: 'sofort',\n} as const;\n\nexport const SUBSCRIPTION_STATUS = {\n ACTIVE: 'active',\n CANCELED: 'canceled',\n PAST_DUE: 'past_due',\n UNPAID: 'unpaid',\n INCOMPLETE: 'incomplete',\n INCOMPLETE_EXPIRED: 'incomplete_expired',\n TRIALING: 'trialing',\n} as const;\n\nexport const INVOICE_STATUS = {\n DRAFT: 'draft',\n OPEN: 'open',\n PAID: 'paid',\n UNCOLLECTIBLE: 'uncollectible',\n VOID: 'void',\n} as const;\n\nexport const CHECKOUT_MODE = {\n PAYMENT: 'payment',\n SUBSCRIPTION: 'subscription',\n SETUP: 'setup',\n} as const;\n\nexport const BILLING_INTERVALS = {\n DAY: 'day',\n WEEK: 'week',\n MONTH: 'month',\n YEAR: 'year',\n} as const;\n\nexport const CURRENCY_SYMBOLS = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n CAD: 'C$',\n AUD: 'A$',\n CHF: 'CHF',\n CNY: '¥',\n SEK: 'kr',\n NZD: 'NZ$',\n} as const;\n\nexport const DEFAULT_CURRENCY = 'USD';\n\nexport const WEBHOOK_EVENTS = {\n CUSTOMER_SUBSCRIPTION_CREATED: 'customer.subscription.created',\n CUSTOMER_SUBSCRIPTION_UPDATED: 'customer.subscription.updated',\n CUSTOMER_SUBSCRIPTION_DELETED: 'customer.subscription.deleted',\n INVOICE_PAYMENT_SUCCEEDED: 'invoice.payment_succeeded',\n INVOICE_PAYMENT_FAILED: 'invoice.payment_failed',\n CHECKOUT_SESSION_COMPLETED: 'checkout.session.completed',\n PAYMENT_INTENT_SUCCEEDED: 'payment_intent.succeeded',\n PAYMENT_INTENT_PAYMENT_FAILED: 'payment_intent.payment_failed',\n} as const;\n\nexport const ERROR_MESSAGES = {\n PROVIDER_NOT_CONFIGURED: 'Payments provider is not properly configured',\n STRIPE_NOT_LOADED: 'Stripe has not been loaded yet',\n INVALID_PRICE_ID: 'Invalid price ID provided',\n INVALID_CUSTOMER_ID: 'Invalid customer ID provided',\n CHECKOUT_FAILED: 'Checkout session creation failed',\n PAYMENT_FAILED: 'Payment processing failed',\n SUBSCRIPTION_NOT_FOUND: 'Subscription not found',\n CUSTOMER_NOT_FOUND: 'Customer not found',\n} as const;\n","import Stripe from 'stripe';\nimport { StripeServerAPI } from '../api/stripe-server';\nimport { WEBHOOK_EVENTS } from '../../shared/constants';\nimport { Request, Response } from 'express';\nimport { NextApiRequest, NextApiResponse } from 'next';\n\nexport interface WebhookHandlers {\n onCustomerSubscriptionCreated?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onCustomerSubscriptionUpdated?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onCustomerSubscriptionDeleted?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onInvoicePaymentSucceeded?: (invoice: Stripe.Invoice) => Promise<void>;\n onInvoicePaymentFailed?: (invoice: Stripe.Invoice) => Promise<void>;\n onCheckoutSessionCompleted?: (\n session: Stripe.Checkout.Session\n ) => Promise<void>;\n onPaymentIntentSucceeded?: (\n paymentIntent: Stripe.PaymentIntent\n ) => Promise<void>;\n onPaymentIntentPaymentFailed?: (\n paymentIntent: Stripe.PaymentIntent\n ) => Promise<void>;\n}\n\nexport class StripeWebhookHandler {\n private stripeAPI: StripeServerAPI;\n private handlers: WebhookHandlers;\n\n constructor(secretKey: string, handlers: WebhookHandlers = {}) {\n this.stripeAPI = new StripeServerAPI(secretKey);\n this.handlers = handlers;\n }\n\n async handleWebhook(\n payload: string | Buffer,\n signature: string,\n webhookSecret: string\n ): Promise<{ success: boolean; error?: string }> {\n try {\n const event = this.stripeAPI.constructWebhookEvent(\n payload,\n signature,\n webhookSecret\n );\n\n console.log(`Received webhook event: ${event.type}`);\n\n await this.processEvent(event);\n\n return { success: true };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown webhook error';\n console.error('Webhook error:', errorMessage);\n return { success: false, error: errorMessage };\n }\n }\n\n private async processEvent(event: Stripe.Event): Promise<void> {\n switch (event.type) {\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_CREATED:\n await this.handleSubscriptionCreated(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_UPDATED:\n await this.handleSubscriptionUpdated(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_DELETED:\n await this.handleSubscriptionDeleted(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.INVOICE_PAYMENT_SUCCEEDED:\n await this.handleInvoicePaymentSucceeded(\n event.data.object as Stripe.Invoice\n );\n break;\n\n case WEBHOOK_EVENTS.INVOICE_PAYMENT_FAILED:\n await this.handleInvoicePaymentFailed(\n event.data.object as Stripe.Invoice\n );\n break;\n\n case WEBHOOK_EVENTS.CHECKOUT_SESSION_COMPLETED:\n await this.handleCheckoutSessionCompleted(\n event.data.object as Stripe.Checkout.Session\n );\n break;\n\n case WEBHOOK_EVENTS.PAYMENT_INTENT_SUCCEEDED:\n await this.handlePaymentIntentSucceeded(\n event.data.object as Stripe.PaymentIntent\n );\n break;\n\n case WEBHOOK_EVENTS.PAYMENT_INTENT_PAYMENT_FAILED:\n await this.handlePaymentIntentFailed(\n event.data.object as Stripe.PaymentIntent\n );\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n }\n\n private async handleSubscriptionCreated(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription created: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionCreated) {\n await this.handlers.onCustomerSubscriptionCreated(subscription);\n }\n\n // Default behavior: Log subscription details\n\n console.log(\n `Customer ${subscription.customer} subscribed to ${subscription.items.data[0]?.price.id}`\n );\n }\n\n private async handleSubscriptionUpdated(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription updated: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionUpdated) {\n await this.handlers.onCustomerSubscriptionUpdated(subscription);\n }\n\n // Default behavior: Log status changes\n\n console.log(\n `Subscription ${subscription.id} status: ${subscription.status}`\n );\n }\n\n private async handleSubscriptionDeleted(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription deleted: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionDeleted) {\n await this.handlers.onCustomerSubscriptionDeleted(subscription);\n }\n\n // Default behavior: Log cancellation\n\n console.log(\n `Customer ${subscription.customer} cancelled subscription ${subscription.id}`\n );\n }\n\n private async handleInvoicePaymentSucceeded(\n invoice: Stripe.Invoice\n ): Promise<void> {\n console.log(`Invoice payment succeeded: ${invoice.id}`);\n\n if (this.handlers.onInvoicePaymentSucceeded) {\n await this.handlers.onInvoicePaymentSucceeded(invoice);\n }\n\n // Default behavior: Log successful payment\n const subscriptionId = (\n invoice as Stripe.Invoice & { subscription?: string }\n ).subscription;\n if (subscriptionId) {\n console.log(`Payment succeeded for subscription ${subscriptionId}`);\n }\n }\n\n private async handleInvoicePaymentFailed(\n invoice: Stripe.Invoice\n ): Promise<void> {\n console.log(`Invoice payment failed: ${invoice.id}`);\n\n if (this.handlers.onInvoicePaymentFailed) {\n await this.handlers.onInvoicePaymentFailed(invoice);\n }\n\n // Default behavior: Log failed payment\n const subscriptionId = (\n invoice as Stripe.Invoice & { subscription?: string }\n ).subscription;\n if (subscriptionId) {\n console.log(`Payment failed for subscription ${subscriptionId}`);\n }\n }\n\n private async handleCheckoutSessionCompleted(\n session: Stripe.Checkout.Session\n ): Promise<void> {\n console.log(`Checkout session completed: ${session.id}`);\n\n if (this.handlers.onCheckoutSessionCompleted) {\n await this.handlers.onCheckoutSessionCompleted(session);\n }\n\n // Default behavior: Log successful checkout\n if (session.mode === 'subscription') {\n console.log(\n `Subscription checkout completed for customer ${session.customer}`\n );\n } else {\n console.log(\n `Payment checkout completed for customer ${session.customer}`\n );\n }\n }\n\n private async handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent\n ): Promise<void> {\n console.log(`Payment intent succeeded: ${paymentIntent.id}`);\n\n if (this.handlers.onPaymentIntentSucceeded) {\n await this.handlers.onPaymentIntentSucceeded(paymentIntent);\n }\n\n // Default behavior: Log successful payment\n\n console.log(\n `Payment of ${paymentIntent.amount} ${paymentIntent.currency} succeeded`\n );\n }\n\n private async handlePaymentIntentFailed(\n paymentIntent: Stripe.PaymentIntent\n ): Promise<void> {\n console.log(`Payment intent failed: ${paymentIntent.id}`);\n\n if (this.handlers.onPaymentIntentPaymentFailed) {\n await this.handlers.onPaymentIntentPaymentFailed(paymentIntent);\n }\n\n // Default behavior: Log failed payment\n\n console.log(\n `Payment of ${paymentIntent.amount} ${paymentIntent.currency} failed`\n );\n }\n}\n\n// Utility function to create a webhook handler with custom handlers\nexport const createStripeWebhookHandler = (\n secretKey: string,\n handlers: WebhookHandlers = {}\n): StripeWebhookHandler => {\n return new StripeWebhookHandler(secretKey, handlers);\n};\n\n// Express.js middleware for handling Stripe webhooks\nexport const createStripeWebhookMiddleware = (\n secretKey: string,\n webhookSecret: string,\n handlers: WebhookHandlers = {}\n) => {\n const webhookHandler = new StripeWebhookHandler(secretKey, handlers);\n\n return async (req: Request, res: Response) => {\n try {\n const signature = req.headers['stripe-signature'];\n\n if (!signature) {\n return res\n .status(400)\n .json({ error: 'Missing stripe-signature header' });\n }\n\n const result = await webhookHandler.handleWebhook(\n req.body,\n Array.isArray(signature) ? signature[0] : signature,\n webhookSecret\n );\n\n if (result.success) {\n res.status(200).json({ received: true });\n } else {\n res.status(400).json({ error: result.error });\n }\n } catch (error) {\n console.error('Webhook middleware error:', error);\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n};\n\n// Next.js API route handler\nexport const createNextJSWebhookHandler = (\n secretKey: string,\n webhookSecret: string,\n handlers: WebhookHandlers = {}\n) => {\n const webhookHandler = new StripeWebhookHandler(secretKey, handlers);\n\n return async (req: NextApiRequest, res: NextApiResponse) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST');\n return res.status(405).json({ error: 'Method not allowed' });\n }\n\n try {\n const signature = req.headers['stripe-signature'];\n\n if (!signature) {\n return res\n .status(400)\n .json({ error: 'Missing stripe-signature header' });\n }\n\n const result = await webhookHandler.handleWebhook(\n req.body,\n Array.isArray(signature) ? signature[0] : signature,\n webhookSecret\n );\n\n if (result.success) {\n res.status(200).json({ received: true });\n } else {\n res.status(400).json({ error: result.error });\n }\n } catch (error) {\n console.error('Webhook handler error:', error);\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n};\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,yBAAAC,EAAA,+BAAAC,EAAA,+BAAAC,EAAA,kCAAAC,IAAA,eAAAC,EAAAP,GCAA,IAAAQ,EAAmB,qBCAZ,IAAMC,EAAqB,aAwD3B,IA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AE,KAAK,CAAE,MAAOC,EAAO,KAAM,CAAC,CAEhD,OAASb,EAAO,CACd,QAAQ,MAAM,yBAA0BA,CAAK,EAC7CY,EAAI,OAAO,GAAG,EAAE,KAAK,CAAE,MAAO,uBAAwB,CAAC,CACzD,CACF,CACF","names":["server_exports","__export","StripeServerAPI","StripeWebhookHandler","createNextJSWebhookHandler","createStripeWebhookHandler","createStripeWebhookMiddleware","__toCommonJS","import_stripe","STRIPE_API_VERSION","WEBHOOK_EVENTS","StripeServerAPI","secretKey","options","Stripe","STRIPE_API_VERSION","params","customerId","subscriptionId","updateData","currentItem","immediately","sessionParams","paymentIntentId","type","paymentMethodId","limit","invoiceId","payload","signature","webhookSecret","priceId","productId","apiVersion","StripeWebhookHandler","secretKey","handlers","StripeServerAPI","payload","signature","webhookSecret","event","error","errorMessage","WEBHOOK_EVENTS","subscription","invoice","subscriptionId","session","paymentIntent","createStripeWebhookHandler","createStripeWebhookMiddleware","webhookHandler","req","res","result","createNextJSWebhookHandler"]}
|
|
1
|
+
{"version":3,"sources":["../src/server/index.ts","../src/server/api/stripe-server.ts","../src/shared/constants.ts","../src/server/webhooks/stripe.ts","../src/server/utils/stripe-helpers.ts"],"sourcesContent":["// API\r\nexport { StripeServerAPI } from './api/stripe-server';\r\n\r\n// Webhooks\r\nexport {\r\n StripeWebhookHandler,\r\n createStripeWebhookHandler,\r\n createStripeWebhookMiddleware,\r\n createNextJSWebhookHandler,\r\n type WebhookHandlers,\r\n} from './webhooks/stripe';\r\n\r\n// Utilities\r\nexport {\r\n createStripeCheckoutSession,\r\n processPayment,\r\n createSubscription,\r\n updateSubscription,\r\n cancelSubscription,\r\n validateStripeSignature,\r\n handleStripeWebhook,\r\n type CreateCheckoutSessionOptions,\r\n type ProcessPaymentOptions,\r\n type CreateSubscriptionOptions,\r\n type UpdateSubscriptionOptions,\r\n} from './utils/stripe-helpers';\r\n","import Stripe from 'stripe';\nimport { STRIPE_API_VERSION } from '../../shared/constants';\n\nexport class StripeServerAPI {\n private stripe: Stripe;\n\n constructor(\n secretKey: string,\n options?: {\n apiVersion?: string;\n typescript?: boolean;\n }\n ) {\n this.stripe = new Stripe(secretKey, {\n apiVersion:\n (options?.apiVersion as Stripe.LatestApiVersion) || STRIPE_API_VERSION,\n typescript: true,\n });\n }\n\n // Customer methods\n async createCustomer(params: {\n email: string;\n name?: string;\n phone?: string;\n metadata?: Record<string, string>;\n }) {\n return this.stripe.customers.create({\n email: params.email,\n name: params.name,\n phone: params.phone,\n metadata: params.metadata,\n });\n }\n\n async getCustomer(customerId: string) {\n return this.stripe.customers.retrieve(customerId);\n }\n\n async updateCustomer(\n customerId: string,\n params: {\n email?: string;\n name?: string;\n phone?: string;\n metadata?: Record<string, string>;\n }\n ) {\n return this.stripe.customers.update(customerId, params);\n }\n\n async deleteCustomer(customerId: string) {\n return this.stripe.customers.del(customerId);\n }\n\n // Subscription methods\n async createSubscription(params: {\n customerId: string;\n priceId: string;\n quantity?: number;\n trialPeriodDays?: number;\n metadata?: Record<string, string>;\n paymentBehavior?:\n | 'default_incomplete'\n | 'error_if_incomplete'\n | 'allow_incomplete';\n }) {\n return this.stripe.subscriptions.create({\n customer: params.customerId,\n items: [\n {\n price: params.priceId,\n quantity: params.quantity || 1,\n },\n ],\n trial_period_days: params.trialPeriodDays,\n metadata: params.metadata,\n payment_behavior: params.paymentBehavior || 'default_incomplete',\n payment_settings: {\n save_default_payment_method: 'on_subscription',\n },\n expand: ['latest_invoice.payment_intent'],\n });\n }\n\n async getSubscription(subscriptionId: string) {\n return this.stripe.subscriptions.retrieve(subscriptionId, {\n expand: ['default_payment_method'],\n });\n }\n\n async updateSubscription(\n subscriptionId: string,\n params: {\n priceId?: string;\n quantity?: number;\n metadata?: Record<string, string>;\n cancelAtPeriodEnd?: boolean;\n }\n ) {\n const updateData: Stripe.SubscriptionUpdateParams = {};\n\n if (params.priceId) {\n // Get current subscription to update items\n const subscription = await this.getSubscription(subscriptionId);\n const currentItem = subscription.items.data[0];\n\n updateData.items = [\n {\n id: currentItem.id,\n price: params.priceId,\n quantity: params.quantity || currentItem.quantity,\n },\n ];\n }\n\n if (params.metadata) {\n updateData.metadata = params.metadata;\n }\n\n if (typeof params.cancelAtPeriodEnd === 'boolean') {\n updateData.cancel_at_period_end = params.cancelAtPeriodEnd;\n }\n\n return this.stripe.subscriptions.update(subscriptionId, updateData);\n }\n\n async cancelSubscription(\n subscriptionId: string,\n immediately: boolean = false\n ) {\n if (immediately) {\n return this.stripe.subscriptions.cancel(subscriptionId);\n } else {\n return this.stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n }\n }\n\n async reactivateSubscription(subscriptionId: string) {\n return this.stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n }\n\n async getCustomerSubscriptions(customerId: string) {\n return this.stripe.subscriptions.list({\n customer: customerId,\n expand: ['data.default_payment_method'],\n });\n }\n\n // Checkout methods\n async createCheckoutSession(params: {\n priceId: string;\n customerId?: string;\n customerEmail?: string;\n successUrl: string;\n cancelUrl: string;\n mode?: 'payment' | 'subscription' | 'setup';\n allowPromotionCodes?: boolean;\n billingAddressCollection?: 'auto' | 'required';\n metadata?: Record<string, string>;\n trialPeriodDays?: number;\n }) {\n const sessionParams: Stripe.Checkout.SessionCreateParams = {\n payment_method_types: ['card'],\n line_items: [\n {\n price: params.priceId,\n quantity: 1,\n },\n ],\n mode: params.mode || 'subscription',\n success_url: params.successUrl,\n cancel_url: params.cancelUrl,\n allow_promotion_codes: params.allowPromotionCodes,\n billing_address_collection: params.billingAddressCollection,\n metadata: params.metadata,\n };\n\n if (params.customerId) {\n sessionParams.customer = params.customerId;\n } else if (params.customerEmail) {\n sessionParams.customer_email = params.customerEmail;\n }\n\n if (params.mode === 'subscription' && params.trialPeriodDays) {\n sessionParams.subscription_data = {\n trial_period_days: params.trialPeriodDays,\n };\n }\n\n return this.stripe.checkout.sessions.create(sessionParams);\n }\n\n // Payment Intent methods\n async getPaymentIntent(paymentIntentId: string) {\n return this.stripe.paymentIntents.retrieve(paymentIntentId);\n }\n\n async createPaymentIntent(params: {\n amount: number;\n currency: string;\n customerId?: string;\n paymentMethodTypes?: string[];\n metadata?: Record<string, string>;\n description?: string;\n }) {\n return this.stripe.paymentIntents.create({\n amount: params.amount,\n currency: params.currency,\n customer: params.customerId,\n payment_method_types: params.paymentMethodTypes || ['card'],\n metadata: params.metadata,\n description: params.description,\n });\n }\n\n async confirmPaymentIntent(\n paymentIntentId: string,\n params?: {\n paymentMethod?: string;\n }\n ) {\n return this.stripe.paymentIntents.confirm(paymentIntentId, {\n payment_method: params?.paymentMethod,\n });\n }\n\n // Setup Intent methods (for subscriptions without immediate payment)\n async createSetupIntent(params: {\n customerId: string;\n paymentMethodTypes?: string[];\n metadata?: Record<string, string>;\n }) {\n return this.stripe.setupIntents.create({\n customer: params.customerId,\n payment_method_types: params.paymentMethodTypes || ['card'],\n metadata: params.metadata,\n usage: 'off_session',\n });\n }\n\n // Customer Portal methods\n async createPortalSession(params: { customerId: string; returnUrl: string }) {\n return this.stripe.billingPortal.sessions.create({\n customer: params.customerId,\n return_url: params.returnUrl,\n });\n }\n\n // Payment Method methods\n async getCustomerPaymentMethods(\n customerId: string,\n type: Stripe.PaymentMethodListParams.Type = 'card'\n ) {\n return this.stripe.paymentMethods.list({\n customer: customerId,\n type,\n });\n }\n\n async attachPaymentMethod(paymentMethodId: string, customerId: string) {\n return this.stripe.paymentMethods.attach(paymentMethodId, {\n customer: customerId,\n });\n }\n\n async detachPaymentMethod(paymentMethodId: string) {\n return this.stripe.paymentMethods.detach(paymentMethodId);\n }\n\n async setDefaultPaymentMethod(customerId: string, paymentMethodId: string) {\n return this.stripe.customers.update(customerId, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n }\n\n // Invoice methods\n async getCustomerInvoices(customerId: string, limit: number = 10) {\n return this.stripe.invoices.list({\n customer: customerId,\n limit,\n });\n }\n\n async getInvoice(invoiceId: string) {\n return this.stripe.invoices.retrieve(invoiceId);\n }\n\n // Webhook methods\n constructWebhookEvent(\n payload: string | Buffer,\n signature: string,\n webhookSecret: string\n ) {\n return this.stripe.webhooks.constructEvent(\n payload,\n signature,\n webhookSecret\n );\n }\n\n // Price and Product methods\n async getPrice(priceId: string) {\n return this.stripe.prices.retrieve(priceId, {\n expand: ['product'],\n });\n }\n\n async getPrices(params?: {\n active?: boolean;\n limit?: number;\n product?: string;\n }) {\n return this.stripe.prices.list({\n active: params?.active,\n limit: params?.limit || 10,\n product: params?.product,\n expand: ['data.product'],\n });\n }\n\n async getProduct(productId: string) {\n return this.stripe.products.retrieve(productId);\n }\n\n // Ephemeral Key methods (for mobile)\n async createEphemeralKey(customerId: string, apiVersion: string) {\n return this.stripe.ephemeralKeys.create(\n { customer: customerId },\n { apiVersion }\n );\n }\n}\n","export const STRIPE_API_VERSION = '2023-10-16';\n\nexport const PAYMENT_METHODS = {\n CARD: 'card',\n BANK_ACCOUNT: 'bank_account',\n SEPA_DEBIT: 'sepa_debit',\n IDEAL: 'ideal',\n SOFORT: 'sofort',\n} as const;\n\nexport const SUBSCRIPTION_STATUS = {\n ACTIVE: 'active',\n CANCELED: 'canceled',\n PAST_DUE: 'past_due',\n UNPAID: 'unpaid',\n INCOMPLETE: 'incomplete',\n INCOMPLETE_EXPIRED: 'incomplete_expired',\n TRIALING: 'trialing',\n} as const;\n\nexport const INVOICE_STATUS = {\n DRAFT: 'draft',\n OPEN: 'open',\n PAID: 'paid',\n UNCOLLECTIBLE: 'uncollectible',\n VOID: 'void',\n} as const;\n\nexport const CHECKOUT_MODE = {\n PAYMENT: 'payment',\n SUBSCRIPTION: 'subscription',\n SETUP: 'setup',\n} as const;\n\nexport const BILLING_INTERVALS = {\n DAY: 'day',\n WEEK: 'week',\n MONTH: 'month',\n YEAR: 'year',\n} as const;\n\nexport const CURRENCY_SYMBOLS = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n CAD: 'C$',\n AUD: 'A$',\n CHF: 'CHF',\n CNY: '¥',\n SEK: 'kr',\n NZD: 'NZ$',\n} as const;\n\nexport const DEFAULT_CURRENCY = 'USD';\n\nexport const WEBHOOK_EVENTS = {\n CUSTOMER_SUBSCRIPTION_CREATED: 'customer.subscription.created',\n CUSTOMER_SUBSCRIPTION_UPDATED: 'customer.subscription.updated',\n CUSTOMER_SUBSCRIPTION_DELETED: 'customer.subscription.deleted',\n INVOICE_PAYMENT_SUCCEEDED: 'invoice.payment_succeeded',\n INVOICE_PAYMENT_FAILED: 'invoice.payment_failed',\n CHECKOUT_SESSION_COMPLETED: 'checkout.session.completed',\n PAYMENT_INTENT_SUCCEEDED: 'payment_intent.succeeded',\n PAYMENT_INTENT_PAYMENT_FAILED: 'payment_intent.payment_failed',\n} as const;\n\nexport const ERROR_MESSAGES = {\n PROVIDER_NOT_CONFIGURED: 'Payments provider is not properly configured',\n STRIPE_NOT_LOADED: 'Stripe has not been loaded yet',\n INVALID_PRICE_ID: 'Invalid price ID provided',\n INVALID_CUSTOMER_ID: 'Invalid customer ID provided',\n CHECKOUT_FAILED: 'Checkout session creation failed',\n PAYMENT_FAILED: 'Payment processing failed',\n SUBSCRIPTION_NOT_FOUND: 'Subscription not found',\n CUSTOMER_NOT_FOUND: 'Customer not found',\n} as const;\n","import Stripe from 'stripe';\nimport { StripeServerAPI } from '../api/stripe-server';\nimport { WEBHOOK_EVENTS } from '../../shared/constants';\nimport { Request, Response } from 'express';\nimport { NextApiRequest, NextApiResponse } from 'next';\n\nexport interface WebhookHandlers {\n onCustomerSubscriptionCreated?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onCustomerSubscriptionUpdated?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onCustomerSubscriptionDeleted?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onInvoicePaymentSucceeded?: (invoice: Stripe.Invoice) => Promise<void>;\n onInvoicePaymentFailed?: (invoice: Stripe.Invoice) => Promise<void>;\n onCheckoutSessionCompleted?: (\n session: Stripe.Checkout.Session\n ) => Promise<void>;\n onPaymentIntentSucceeded?: (\n paymentIntent: Stripe.PaymentIntent\n ) => Promise<void>;\n onPaymentIntentPaymentFailed?: (\n paymentIntent: Stripe.PaymentIntent\n ) => Promise<void>;\n}\n\nexport class StripeWebhookHandler {\n private stripeAPI: StripeServerAPI;\n private handlers: WebhookHandlers;\n\n constructor(secretKey: string, handlers: WebhookHandlers = {}) {\n this.stripeAPI = new StripeServerAPI(secretKey);\n this.handlers = handlers;\n }\n\n async handleWebhook(\n payload: string | Buffer,\n signature: string,\n webhookSecret: string\n ): Promise<{ success: boolean; error?: string }> {\n try {\n const event = this.stripeAPI.constructWebhookEvent(\n payload,\n signature,\n webhookSecret\n );\n\n console.log(`Received webhook event: ${event.type}`);\n\n await this.processEvent(event);\n\n return { success: true };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown webhook error';\n console.error('Webhook error:', errorMessage);\n return { success: false, error: errorMessage };\n }\n }\n\n private async processEvent(event: Stripe.Event): Promise<void> {\n switch (event.type) {\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_CREATED:\n await this.handleSubscriptionCreated(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_UPDATED:\n await this.handleSubscriptionUpdated(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_DELETED:\n await this.handleSubscriptionDeleted(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.INVOICE_PAYMENT_SUCCEEDED:\n await this.handleInvoicePaymentSucceeded(\n event.data.object as Stripe.Invoice\n );\n break;\n\n case WEBHOOK_EVENTS.INVOICE_PAYMENT_FAILED:\n await this.handleInvoicePaymentFailed(\n event.data.object as Stripe.Invoice\n );\n break;\n\n case WEBHOOK_EVENTS.CHECKOUT_SESSION_COMPLETED:\n await this.handleCheckoutSessionCompleted(\n event.data.object as Stripe.Checkout.Session\n );\n break;\n\n case WEBHOOK_EVENTS.PAYMENT_INTENT_SUCCEEDED:\n await this.handlePaymentIntentSucceeded(\n event.data.object as Stripe.PaymentIntent\n );\n break;\n\n case WEBHOOK_EVENTS.PAYMENT_INTENT_PAYMENT_FAILED:\n await this.handlePaymentIntentFailed(\n event.data.object as Stripe.PaymentIntent\n );\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n }\n\n private async handleSubscriptionCreated(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription created: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionCreated) {\n await this.handlers.onCustomerSubscriptionCreated(subscription);\n }\n\n // Default behavior: Log subscription details\n\n console.log(\n `Customer ${subscription.customer} subscribed to ${subscription.items.data[0]?.price.id}`\n );\n }\n\n private async handleSubscriptionUpdated(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription updated: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionUpdated) {\n await this.handlers.onCustomerSubscriptionUpdated(subscription);\n }\n\n // Default behavior: Log status changes\n\n console.log(\n `Subscription ${subscription.id} status: ${subscription.status}`\n );\n }\n\n private async handleSubscriptionDeleted(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription deleted: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionDeleted) {\n await this.handlers.onCustomerSubscriptionDeleted(subscription);\n }\n\n // Default behavior: Log cancellation\n\n console.log(\n `Customer ${subscription.customer} cancelled subscription ${subscription.id}`\n );\n }\n\n private async handleInvoicePaymentSucceeded(\n invoice: Stripe.Invoice\n ): Promise<void> {\n console.log(`Invoice payment succeeded: ${invoice.id}`);\n\n if (this.handlers.onInvoicePaymentSucceeded) {\n await this.handlers.onInvoicePaymentSucceeded(invoice);\n }\n\n // Default behavior: Log successful payment\n const subscriptionId = (\n invoice as Stripe.Invoice & { subscription?: string }\n ).subscription;\n if (subscriptionId) {\n console.log(`Payment succeeded for subscription ${subscriptionId}`);\n }\n }\n\n private async handleInvoicePaymentFailed(\n invoice: Stripe.Invoice\n ): Promise<void> {\n console.log(`Invoice payment failed: ${invoice.id}`);\n\n if (this.handlers.onInvoicePaymentFailed) {\n await this.handlers.onInvoicePaymentFailed(invoice);\n }\n\n // Default behavior: Log failed payment\n const subscriptionId = (\n invoice as Stripe.Invoice & { subscription?: string }\n ).subscription;\n if (subscriptionId) {\n console.log(`Payment failed for subscription ${subscriptionId}`);\n }\n }\n\n private async handleCheckoutSessionCompleted(\n session: Stripe.Checkout.Session\n ): Promise<void> {\n console.log(`Checkout session completed: ${session.id}`);\n\n if (this.handlers.onCheckoutSessionCompleted) {\n await this.handlers.onCheckoutSessionCompleted(session);\n }\n\n // Default behavior: Log successful checkout\n if (session.mode === 'subscription') {\n console.log(\n `Subscription checkout completed for customer ${session.customer}`\n );\n } else {\n console.log(\n `Payment checkout completed for customer ${session.customer}`\n );\n }\n }\n\n private async handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent\n ): Promise<void> {\n console.log(`Payment intent succeeded: ${paymentIntent.id}`);\n\n if (this.handlers.onPaymentIntentSucceeded) {\n await this.handlers.onPaymentIntentSucceeded(paymentIntent);\n }\n\n // Default behavior: Log successful payment\n\n console.log(\n `Payment of ${paymentIntent.amount} ${paymentIntent.currency} succeeded`\n );\n }\n\n private async handlePaymentIntentFailed(\n paymentIntent: Stripe.PaymentIntent\n ): Promise<void> {\n console.log(`Payment intent failed: ${paymentIntent.id}`);\n\n if (this.handlers.onPaymentIntentPaymentFailed) {\n await this.handlers.onPaymentIntentPaymentFailed(paymentIntent);\n }\n\n // Default behavior: Log failed payment\n\n console.log(\n `Payment of ${paymentIntent.amount} ${paymentIntent.currency} failed`\n );\n }\n}\n\n// Utility function to create a webhook handler with custom handlers\nexport const createStripeWebhookHandler = (\n secretKey: string,\n handlers: WebhookHandlers = {}\n): StripeWebhookHandler => {\n return new StripeWebhookHandler(secretKey, handlers);\n};\n\n// Express.js middleware for handling Stripe webhooks\nexport const createStripeWebhookMiddleware = (\n secretKey: string,\n webhookSecret: string,\n handlers: WebhookHandlers = {}\n) => {\n const webhookHandler = new StripeWebhookHandler(secretKey, handlers);\n\n return async (req: Request, res: Response) => {\n try {\n const signature = req.headers['stripe-signature'];\n\n if (!signature) {\n return res\n .status(400)\n .json({ error: 'Missing stripe-signature header' });\n }\n\n const result = await webhookHandler.handleWebhook(\n req.body,\n Array.isArray(signature) ? signature[0] : signature,\n webhookSecret\n );\n\n if (result.success) {\n res.status(200).json({ received: true });\n } else {\n res.status(400).json({ error: result.error });\n }\n } catch (error) {\n console.error('Webhook middleware error:', error);\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n};\n\n// Next.js API route handler\nexport const createNextJSWebhookHandler = (\n secretKey: string,\n webhookSecret: string,\n handlers: WebhookHandlers = {}\n) => {\n const webhookHandler = new StripeWebhookHandler(secretKey, handlers);\n\n return async (req: NextApiRequest, res: NextApiResponse) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST');\n return res.status(405).json({ error: 'Method not allowed' });\n }\n\n try {\n const signature = req.headers['stripe-signature'];\n\n if (!signature) {\n return res\n .status(400)\n .json({ error: 'Missing stripe-signature header' });\n }\n\n const result = await webhookHandler.handleWebhook(\n req.body,\n Array.isArray(signature) ? signature[0] : signature,\n webhookSecret\n );\n\n if (result.success) {\n res.status(200).json({ received: true });\n } else {\n res.status(400).json({ error: result.error });\n }\n } catch (error) {\n console.error('Webhook handler error:', error);\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n};\n","import Stripe from 'stripe';\r\n\r\nexport interface CreateCheckoutSessionOptions {\r\n priceId: string;\r\n customerId?: string;\r\n successUrl: string;\r\n cancelUrl: string;\r\n mode?: 'payment' | 'subscription' | 'setup';\r\n metadata?: Record<string, string>;\r\n}\r\n\r\nexport interface ProcessPaymentOptions {\r\n amount: number;\r\n currency: string;\r\n paymentMethodId: string;\r\n customerId?: string;\r\n description?: string;\r\n metadata?: Record<string, string>;\r\n}\r\n\r\nexport interface CreateSubscriptionOptions {\r\n customerId: string;\r\n priceId: string;\r\n paymentMethodId?: string;\r\n trialPeriodDays?: number;\r\n metadata?: Record<string, string>;\r\n}\r\n\r\nexport interface UpdateSubscriptionOptions {\r\n subscriptionId: string;\r\n priceId?: string;\r\n quantity?: number;\r\n metadata?: Record<string, string>;\r\n}\r\n\r\n/**\r\n * Create a Stripe checkout session\r\n */\r\nexport const createStripeCheckoutSession = async (\r\n stripe: Stripe,\r\n options: CreateCheckoutSessionOptions\r\n): Promise<Stripe.Checkout.Session> => {\r\n const {\r\n priceId,\r\n customerId,\r\n successUrl,\r\n cancelUrl,\r\n mode = 'subscription',\r\n metadata = {},\r\n } = options;\r\n\r\n const sessionParams: Stripe.Checkout.SessionCreateParams = {\r\n mode,\r\n success_url: successUrl,\r\n cancel_url: cancelUrl,\r\n line_items: [\r\n {\r\n price: priceId,\r\n quantity: 1,\r\n },\r\n ],\r\n metadata,\r\n };\r\n\r\n if (customerId) {\r\n sessionParams.customer = customerId;\r\n } else {\r\n sessionParams.customer_creation = 'always';\r\n }\r\n\r\n if (mode === 'subscription') {\r\n sessionParams.subscription_data = {\r\n metadata,\r\n };\r\n }\r\n\r\n return await stripe.checkout.sessions.create(sessionParams);\r\n};\r\n\r\n/**\r\n * Process a one-time payment\r\n */\r\nexport const processPayment = async (\r\n stripe: Stripe,\r\n options: ProcessPaymentOptions\r\n): Promise<Stripe.PaymentIntent> => {\r\n const {\r\n amount,\r\n currency,\r\n paymentMethodId,\r\n customerId,\r\n description,\r\n metadata = {},\r\n } = options;\r\n\r\n const paymentIntentParams: Stripe.PaymentIntentCreateParams = {\r\n amount,\r\n currency,\r\n payment_method: paymentMethodId,\r\n confirmation_method: 'manual',\r\n confirm: true,\r\n return_url: 'https://your-website.com/return',\r\n metadata,\r\n };\r\n\r\n if (customerId) {\r\n paymentIntentParams.customer = customerId;\r\n }\r\n\r\n if (description) {\r\n paymentIntentParams.description = description;\r\n }\r\n\r\n return await stripe.paymentIntents.create(paymentIntentParams);\r\n};\r\n\r\n/**\r\n * Create a subscription\r\n */\r\nexport const createSubscription = async (\r\n stripe: Stripe,\r\n options: CreateSubscriptionOptions\r\n): Promise<Stripe.Subscription> => {\r\n const {\r\n customerId,\r\n priceId,\r\n paymentMethodId,\r\n trialPeriodDays,\r\n metadata = {},\r\n } = options;\r\n\r\n const subscriptionParams: Stripe.SubscriptionCreateParams = {\r\n customer: customerId,\r\n items: [\r\n {\r\n price: priceId,\r\n },\r\n ],\r\n metadata,\r\n };\r\n\r\n if (paymentMethodId) {\r\n subscriptionParams.default_payment_method = paymentMethodId;\r\n }\r\n\r\n if (trialPeriodDays) {\r\n subscriptionParams.trial_period_days = trialPeriodDays;\r\n }\r\n\r\n return await stripe.subscriptions.create(subscriptionParams);\r\n};\r\n\r\n/**\r\n * Update a subscription\r\n */\r\nexport const updateSubscription = async (\r\n stripe: Stripe,\r\n options: UpdateSubscriptionOptions\r\n): Promise<Stripe.Subscription> => {\r\n const { subscriptionId, priceId, quantity, metadata } = options;\r\n\r\n const subscription = await stripe.subscriptions.retrieve(subscriptionId);\r\n \r\n const updateParams: Stripe.SubscriptionUpdateParams = {};\r\n\r\n if (priceId) {\r\n updateParams.items = [\r\n {\r\n id: subscription.items.data[0].id,\r\n price: priceId,\r\n quantity: quantity || 1,\r\n },\r\n ];\r\n }\r\n\r\n if (metadata) {\r\n updateParams.metadata = metadata;\r\n }\r\n\r\n return await stripe.subscriptions.update(subscriptionId, updateParams);\r\n};\r\n\r\n/**\r\n * Cancel a subscription\r\n */\r\nexport const cancelSubscription = async (\r\n stripe: Stripe,\r\n subscriptionId: string,\r\n cancelAtPeriodEnd: boolean = true\r\n): Promise<Stripe.Subscription> => {\r\n if (cancelAtPeriodEnd) {\r\n return await stripe.subscriptions.update(subscriptionId, {\r\n cancel_at_period_end: true,\r\n });\r\n } else {\r\n return await stripe.subscriptions.cancel(subscriptionId);\r\n }\r\n};\r\n\r\n/**\r\n * Validate Stripe webhook signature\r\n */\r\nexport const validateStripeSignature = (\r\n payload: string | Buffer,\r\n signature: string,\r\n endpointSecret: string\r\n): Stripe.Event => {\r\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {\r\n apiVersion: '2024-06-20',\r\n });\r\n\r\n return stripe.webhooks.constructEvent(payload, signature, endpointSecret);\r\n};\r\n\r\n/**\r\n * Handle common Stripe webhook events\r\n */\r\nexport const handleStripeWebhook = async (\r\n event: Stripe.Event,\r\n handlers: {\r\n onPaymentSucceeded?: (paymentIntent: Stripe.PaymentIntent) => Promise<void>;\r\n onPaymentFailed?: (paymentIntent: Stripe.PaymentIntent) => Promise<void>;\r\n onSubscriptionCreated?: (subscription: Stripe.Subscription) => Promise<void>;\r\n onSubscriptionUpdated?: (subscription: Stripe.Subscription) => Promise<void>;\r\n onSubscriptionDeleted?: (subscription: Stripe.Subscription) => Promise<void>;\r\n onInvoicePaid?: (invoice: Stripe.Invoice) => Promise<void>;\r\n onInvoicePaymentFailed?: (invoice: Stripe.Invoice) => Promise<void>;\r\n }\r\n): Promise<void> => {\r\n switch (event.type) {\r\n case 'payment_intent.succeeded':\r\n if (handlers.onPaymentSucceeded) {\r\n await handlers.onPaymentSucceeded(event.data.object as Stripe.PaymentIntent);\r\n }\r\n break;\r\n\r\n case 'payment_intent.payment_failed':\r\n if (handlers.onPaymentFailed) {\r\n await handlers.onPaymentFailed(event.data.object as Stripe.PaymentIntent);\r\n }\r\n break;\r\n\r\n case 'customer.subscription.created':\r\n if (handlers.onSubscriptionCreated) {\r\n await handlers.onSubscriptionCreated(event.data.object as Stripe.Subscription);\r\n }\r\n break;\r\n\r\n case 'customer.subscription.updated':\r\n if (handlers.onSubscriptionUpdated) {\r\n await handlers.onSubscriptionUpdated(event.data.object as Stripe.Subscription);\r\n }\r\n break;\r\n\r\n case 'customer.subscription.deleted':\r\n if (handlers.onSubscriptionDeleted) {\r\n await handlers.onSubscriptionDeleted(event.data.object as Stripe.Subscription);\r\n }\r\n break;\r\n\r\n case 'invoice.paid':\r\n if (handlers.onInvoicePaid) {\r\n await handlers.onInvoicePaid(event.data.object as Stripe.Invoice);\r\n }\r\n break;\r\n\r\n case 'invoice.payment_failed':\r\n if (handlers.onInvoicePaymentFailed) {\r\n await handlers.onInvoicePaymentFailed(event.data.object as Stripe.Invoice);\r\n }\r\n break;\r\n\r\n default:\r\n console.log(`Unhandled event type: ${event.type}`);\r\n }\r\n};\r\n\r\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,yBAAAC,EAAA,uBAAAC,EAAA,+BAAAC,EAAA,gCAAAC,EAAA,+BAAAC,EAAA,kCAAAC,EAAA,uBAAAC,EAAA,wBAAAC,EAAA,mBAAAC,EAAA,uBAAAC,EAAA,4BAAAC,IAAA,eAAAC,EAAAd,GCAA,IAAAe,EAAmB,qBCAZ,IAAMC,EAAqB,aAwD3B,IAAMC,EAAiB,CAC5B,8BAA+B,gCAC/B,8BAA+B,gCAC/B,8BAA+B,gCAC/B,0BAA2B,4BAC3B,uBAAwB,yBACxB,2BAA4B,6BAC5B,yBAA0B,2BAC1B,8BAA+B,+BACjC,ED9DO,IAAMC,EAAN,KAAsB,CACnB,OAER,YACEC,EACAC,EAIA,CACA,KAAK,OAAS,IAAI,EAAAC,QAAOF,EAAW,CAClC,WACGC,GAAS,YAA0CE,EACtD,WAAY,EACd,CAAC,CACH,CAGA,MAAM,eAAeC,EAKlB,CACD,OAAO,KAAK,OAAO,UAAU,OAAO,CAClC,MAAOA,EAAO,MACd,KAAMA,EAAO,KACb,MAAOA,EAAO,MACd,SAAUA,EAAO,QACnB,CAAC,CACH,CAEA,MAAM,YAAYC,EAAoB,CACpC,OAAO,KAAK,OAAO,UAAU,SAASA,CAAU,CAClD,CAEA,MAAM,eACJA,EACAD,EAMA,CACA,OAAO,KAAK,OAAO,UAAU,OAAOC,EAAYD,CAAM,CACxD,CAEA,MAAM,eAAeC,EAAoB,CACvC,OAAO,KAAK,O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O9CM,EAA0B,CACrCC,EACAC,EACAC,IAEe,IAAI,EAAAC,QAAO,QAAQ,IAAI,kBAAoB,CACxD,WAAY,YACd,CAAC,EAEa,SAAS,eAAeH,EAASC,EAAWC,CAAc,EAM7DE,EAAsB,MACjCC,EACAC,IASkB,CAClB,OAAQD,EAAM,KAAM,CAClB,IAAK,2BACCC,EAAS,oBACX,MAAMA,EAAS,mBAAmBD,EAAM,KAAK,MAA8B,EAE7E,MAEF,IAAK,gCACCC,EAAS,iBACX,MAAMA,EAAS,gBAAgBD,EAAM,KAAK,MAA8B,EAE1E,MAEF,IAAK,gCACCC,EAAS,uBACX,MAAMA,EAAS,sBAAsBD,EAAM,KAAK,MAA6B,EAE/E,MAEF,IAAK,gCACCC,EAAS,uBACX,MAAMA,EAAS,sBAAsBD,EAAM,KAAK,MAA6B,EAE/E,MAEF,IAAK,gCACCC,EAAS,uBACX,MAAMA,EAAS,sBAAsBD,EAAM,KAAK,MAA6B,EAE/E,MAEF,IAAK,eACCC,EAAS,eACX,MAAMA,EAAS,cAAcD,EAAM,KAAK,MAAwB,EAElE,MAEF,IAAK,yBACCC,EAAS,wBACX,MAAMA,EAAS,uBAAuBD,EAAM,KAAK,MAAwB,EAE3E,MAEF,QACE,QAAQ,IAAI,yBAAyBA,EAAM,IAAI,EAAE,CACrD,CACF","names":["server_exports","__export","StripeServerAPI","StripeWebhookHandler","cancelSubscription","createNextJSWebhookHandler","createStripeCheckoutSession","createStripeWebhookHandler","createStripeWebhookMiddleware","createSubscription","handleStripeWebhook","processPayment","updateSubscription","validateStripeSignature","__toCommonJS","import_stripe","STRIPE_API_VERSION","WEBHOOK_EVENTS","StripeServerAPI","secretKey","options","Stripe","STRIPE_API_VERSION","params","customerId","subscriptionId","updateData","currentItem","immediately","sessionParams","paymentIntentId","type","paymentMethodId","limit","invoiceId","payload","signature","webhookSecret","priceId","productId","apiVersion","StripeWebhookHandler","secretKey","handlers","StripeServerAPI","payload","signature","webhookSecret","event","error","errorMessage","WEBHOOK_EVENTS","subscription","invoice","subscriptionId","session","paymentIntent","createStripeWebhookHandler","createStripeWebhookMiddleware","webhookHandler","req","res","result","createNextJSWebhookHandler","import_stripe","createStripeCheckoutSession","stripe","options","priceId","customerId","successUrl","cancelUrl","mode","metadata","sessionParams","processPayment","amount","currency","paymentMethodId","description","paymentIntentParams","createSubscription","trialPeriodDays","subscriptionParams","updateSubscription","subscriptionId","quantity","subscription","updateParams","cancelSubscription","cancelAtPeriodEnd","validateStripeSignature","payload","signature","endpointSecret","Stripe","handleStripeWebhook","event","handlers"]}
|
package/dist/server.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import l from"stripe";var p="2023-10-16";var o={CUSTOMER_SUBSCRIPTION_CREATED:"customer.subscription.created",CUSTOMER_SUBSCRIPTION_UPDATED:"customer.subscription.updated",CUSTOMER_SUBSCRIPTION_DELETED:"customer.subscription.deleted",INVOICE_PAYMENT_SUCCEEDED:"invoice.payment_succeeded",INVOICE_PAYMENT_FAILED:"invoice.payment_failed",CHECKOUT_SESSION_COMPLETED:"checkout.session.completed",PAYMENT_INTENT_SUCCEEDED:"payment_intent.succeeded",PAYMENT_INTENT_PAYMENT_FAILED:"payment_intent.payment_failed"};var u=class{stripe;constructor(e,t){this.stripe=new l(e,{apiVersion:t?.apiVersion||p,typescript:!0})}async createCustomer(e){return this.stripe.customers.create({email:e.email,name:e.name,phone:e.phone,metadata:e.metadata})}async getCustomer(e){return this.stripe.customers.retrieve(e)}async updateCustomer(e,t){return this.stripe.customers.update(e,t)}async deleteCustomer(e){return this.stripe.customers.del(e)}async createSubscription(e){return this.stripe.subscriptions.create({customer:e.customerId,items:[{price:e.priceId,quantity:e.quantity||1}],trial_period_days:e.trialPeriodDays,metadata:e.metadata,payment_behavior:e.paymentBehavior||"default_incomplete",payment_settings:{save_default_payment_method:"on_subscription"},expand:["latest_invoice.payment_intent"]})}async getSubscription(e){return this.stripe.subscriptions.retrieve(e,{expand:["default_payment_method"]})}async updateSubscription(e,t){let n={};if(t.priceId){let r=(await this.getSubscription(e)).items.data[0];n.items=[{id:r.id,price:t.priceId,quantity:t.quantity||r.quantity}]}return t.metadata&&(n.metadata=t.metadata),typeof t.cancelAtPeriodEnd=="boolean"&&(n.cancel_at_period_end=t.cancelAtPeriodEnd),this.stripe.subscriptions.update(e,n)}async cancelSubscription(e,t=!1){return t?this.stripe.subscriptions.cancel(e):this.stripe.subscriptions.update(e,{cancel_at_period_end:!0})}async reactivateSubscription(e){return this.stripe.subscriptions.update(e,{cancel_at_period_end:!1})}async getCustomerSubscriptions(e){return this.stripe.subscriptions.list({customer:e,expand:["data.default_payment_method"]})}async createCheckoutSession(e){let t={payment_method_types:["card"],line_items:[{price:e.priceId,quantity:1}],mode:e.mode||"subscription",success_url:e.successUrl,cancel_url:e.cancelUrl,allow_promotion_codes:e.allowPromotionCodes,billing_address_collection:e.billingAddressCollection,metadata:e.metadata};return e.customerId?t.customer=e.customerId:e.customerEmail&&(t.customer_email=e.customerEmail),e.mode==="subscription"&&e.trialPeriodDays&&(t.subscription_data={trial_period_days:e.trialPeriodDays}),this.stripe.checkout.sessions.create(t)}async getPaymentIntent(e){return this.stripe.paymentIntents.retrieve(e)}async createPaymentIntent(e){return this.stripe.paymentIntents.create({amount:e.amount,currency:e.currency,customer:e.customerId,payment_method_types:e.paymentMethodTypes||["card"],metadata:e.metadata,description:e.description})}async confirmPaymentIntent(e,t){return this.stripe.paymentIntents.confirm(e,{payment_method:t?.paymentMethod})}async createSetupIntent(e){return this.stripe.setupIntents.create({customer:e.customerId,payment_method_types:e.paymentMethodTypes||["card"],metadata:e.metadata,usage:"off_session"})}async createPortalSession(e){return this.stripe.billingPortal.sessions.create({customer:e.customerId,return_url:e.returnUrl})}async getCustomerPaymentMethods(e,t="card"){return this.stripe.paymentMethods.list({customer:e,type:t})}async attachPaymentMethod(e,t){return this.stripe.paymentMethods.attach(e,{customer:t})}async detachPaymentMethod(e){return this.stripe.paymentMethods.detach(e)}async setDefaultPaymentMethod(e,t){return this.stripe.customers.update(e,{invoice_settings:{default_payment_method:t}})}async getCustomerInvoices(e,t=10){return this.stripe.invoices.list({customer:e,limit:t})}async getInvoice(e){return this.stripe.invoices.retrieve(e)}constructWebhookEvent(e,t,n){return this.stripe.webhooks.constructEvent(e,t,n)}async getPrice(e){return this.stripe.prices.retrieve(e,{expand:["product"]})}async getPrices(e){return this.stripe.prices.list({active:e?.active,limit:e?.limit||10,product:e?.product,expand:["data.product"]})}async getProduct(e){return this.stripe.products.retrieve(e)}async createEphemeralKey(e,t){return this.stripe.ephemeralKeys.create({customer:e},{apiVersion:t})}};var c=class{stripeAPI;handlers;constructor(e,t={}){this.stripeAPI=new u(e),this.handlers=t}async handleWebhook(e,t,n){try{let s=this.stripeAPI.constructWebhookEvent(e,t,n);return console.log(`Received webhook event: ${s.type}`),await this.processEvent(s),{success:!0}}catch(s){let r=s instanceof Error?s.message:"Unknown webhook error";return console.error("Webhook error:",r),{success:!1,error:r}}}async processEvent(e){switch(e.type){case o.CUSTOMER_SUBSCRIPTION_CREATED:await this.handleSubscriptionCreated(e.data.object);break;case o.CUSTOMER_SUBSCRIPTION_UPDATED:await this.handleSubscriptionUpdated(e.data.object);break;case o.CUSTOMER_SUBSCRIPTION_DELETED:await this.handleSubscriptionDeleted(e.data.object);break;case o.INVOICE_PAYMENT_SUCCEEDED:await this.handleInvoicePaymentSucceeded(e.data.object);break;case o.INVOICE_PAYMENT_FAILED:await this.handleInvoicePaymentFailed(e.data.object);break;case o.CHECKOUT_SESSION_COMPLETED:await this.handleCheckoutSessionCompleted(e.data.object);break;case o.PAYMENT_INTENT_SUCCEEDED:await this.handlePaymentIntentSucceeded(e.data.object);break;case o.PAYMENT_INTENT_PAYMENT_FAILED:await this.handlePaymentIntentFailed(e.data.object);break;default:console.log(`Unhandled event type: ${e.type}`)}}async handleSubscriptionCreated(e){console.log(`Subscription created: ${e.id}`),this.handlers.onCustomerSubscriptionCreated&&await this.handlers.onCustomerSubscriptionCreated(e),console.log(`Customer ${e.customer} subscribed to ${e.items.data[0]?.price.id}`)}async handleSubscriptionUpdated(e){console.log(`Subscription updated: ${e.id}`),this.handlers.onCustomerSubscriptionUpdated&&await this.handlers.onCustomerSubscriptionUpdated(e),console.log(`Subscription ${e.id} status: ${e.status}`)}async handleSubscriptionDeleted(e){console.log(`Subscription deleted: ${e.id}`),this.handlers.onCustomerSubscriptionDeleted&&await this.handlers.onCustomerSubscriptionDeleted(e),console.log(`Customer ${e.customer} cancelled subscription ${e.id}`)}async handleInvoicePaymentSucceeded(e){console.log(`Invoice payment succeeded: ${e.id}`),this.handlers.onInvoicePaymentSucceeded&&await this.handlers.onInvoicePaymentSucceeded(e);let t=e.subscription;t&&console.log(`Payment succeeded for subscription ${t}`)}async handleInvoicePaymentFailed(e){console.log(`Invoice payment failed: ${e.id}`),this.handlers.onInvoicePaymentFailed&&await this.handlers.onInvoicePaymentFailed(e);let t=e.subscription;t&&console.log(`Payment failed for subscription ${t}`)}async handleCheckoutSessionCompleted(e){console.log(`Checkout session completed: ${e.id}`),this.handlers.onCheckoutSessionCompleted&&await this.handlers.onCheckoutSessionCompleted(e),e.mode==="subscription"?console.log(`Subscription checkout completed for customer ${e.customer}`):console.log(`Payment checkout completed for customer ${e.customer}`)}async handlePaymentIntentSucceeded(e){console.log(`Payment intent succeeded: ${e.id}`),this.handlers.onPaymentIntentSucceeded&&await this.handlers.onPaymentIntentSucceeded(e),console.log(`Payment of ${e.amount} ${e.currency} succeeded`)}async handlePaymentIntentFailed(e){console.log(`Payment intent failed: ${e.id}`),this.handlers.onPaymentIntentPaymentFailed&&await this.handlers.onPaymentIntentPaymentFailed(e),console.log(`Payment of ${e.amount} ${e.currency} failed`)}},m=(a,e={})=>new c(a,e),h=(a,e,t={})=>{let n=new c(a,t);return async(s,r)=>{try{let i=s.headers["stripe-signature"];if(!i)return r.status(400).json({error:"Missing stripe-signature header"});let d=await n.handleWebhook(s.body,Array.isArray(i)?i[0]:i,e);d.success?r.status(200).json({received:!0}):r.status(400).json({error:d.error})}catch(i){console.error("Webhook middleware error:",i),r.status(500).json({error:"Internal server error"})}}},S=(a,e,t={})=>{let n=new c(a,t);return async(s,r)=>{if(s.method!=="POST")return r.setHeader("Allow","POST"),r.status(405).json({error:"Method not allowed"});try{let i=s.headers["stripe-signature"];if(!i)return r.status(400).json({error:"Missing stripe-signature header"});let d=await n.handleWebhook(s.body,Array.isArray(i)?i[0]:i,e);d.success?r.status(200).json({received:!0}):r.status(400).json({error:d.error})}catch(i){console.error("Webhook handler error:",i),r.status(500).json({error:"Internal server error"})}}};export{u as StripeServerAPI,c as StripeWebhookHandler,S as createNextJSWebhookHandler,m as createStripeWebhookHandler,h as createStripeWebhookMiddleware};
|
|
1
|
+
import l from"stripe";var m="2023-10-16";var c={CUSTOMER_SUBSCRIPTION_CREATED:"customer.subscription.created",CUSTOMER_SUBSCRIPTION_UPDATED:"customer.subscription.updated",CUSTOMER_SUBSCRIPTION_DELETED:"customer.subscription.deleted",INVOICE_PAYMENT_SUCCEEDED:"invoice.payment_succeeded",INVOICE_PAYMENT_FAILED:"invoice.payment_failed",CHECKOUT_SESSION_COMPLETED:"checkout.session.completed",PAYMENT_INTENT_SUCCEEDED:"payment_intent.succeeded",PAYMENT_INTENT_PAYMENT_FAILED:"payment_intent.payment_failed"};var u=class{stripe;constructor(e,t){this.stripe=new l(e,{apiVersion:t?.apiVersion||m,typescript:!0})}async createCustomer(e){return this.stripe.customers.create({email:e.email,name:e.name,phone:e.phone,metadata:e.metadata})}async getCustomer(e){return this.stripe.customers.retrieve(e)}async updateCustomer(e,t){return this.stripe.customers.update(e,t)}async deleteCustomer(e){return this.stripe.customers.del(e)}async createSubscription(e){return this.stripe.subscriptions.create({customer:e.customerId,items:[{price:e.priceId,quantity:e.quantity||1}],trial_period_days:e.trialPeriodDays,metadata:e.metadata,payment_behavior:e.paymentBehavior||"default_incomplete",payment_settings:{save_default_payment_method:"on_subscription"},expand:["latest_invoice.payment_intent"]})}async getSubscription(e){return this.stripe.subscriptions.retrieve(e,{expand:["default_payment_method"]})}async updateSubscription(e,t){let n={};if(t.priceId){let r=(await this.getSubscription(e)).items.data[0];n.items=[{id:r.id,price:t.priceId,quantity:t.quantity||r.quantity}]}return t.metadata&&(n.metadata=t.metadata),typeof t.cancelAtPeriodEnd=="boolean"&&(n.cancel_at_period_end=t.cancelAtPeriodEnd),this.stripe.subscriptions.update(e,n)}async cancelSubscription(e,t=!1){return t?this.stripe.subscriptions.cancel(e):this.stripe.subscriptions.update(e,{cancel_at_period_end:!0})}async reactivateSubscription(e){return this.stripe.subscriptions.update(e,{cancel_at_period_end:!1})}async getCustomerSubscriptions(e){return this.stripe.subscriptions.list({customer:e,expand:["data.default_payment_method"]})}async createCheckoutSession(e){let t={payment_method_types:["card"],line_items:[{price:e.priceId,quantity:1}],mode:e.mode||"subscription",success_url:e.successUrl,cancel_url:e.cancelUrl,allow_promotion_codes:e.allowPromotionCodes,billing_address_collection:e.billingAddressCollection,metadata:e.metadata};return e.customerId?t.customer=e.customerId:e.customerEmail&&(t.customer_email=e.customerEmail),e.mode==="subscription"&&e.trialPeriodDays&&(t.subscription_data={trial_period_days:e.trialPeriodDays}),this.stripe.checkout.sessions.create(t)}async getPaymentIntent(e){return this.stripe.paymentIntents.retrieve(e)}async createPaymentIntent(e){return this.stripe.paymentIntents.create({amount:e.amount,currency:e.currency,customer:e.customerId,payment_method_types:e.paymentMethodTypes||["card"],metadata:e.metadata,description:e.description})}async confirmPaymentIntent(e,t){return this.stripe.paymentIntents.confirm(e,{payment_method:t?.paymentMethod})}async createSetupIntent(e){return this.stripe.setupIntents.create({customer:e.customerId,payment_method_types:e.paymentMethodTypes||["card"],metadata:e.metadata,usage:"off_session"})}async createPortalSession(e){return this.stripe.billingPortal.sessions.create({customer:e.customerId,return_url:e.returnUrl})}async getCustomerPaymentMethods(e,t="card"){return this.stripe.paymentMethods.list({customer:e,type:t})}async attachPaymentMethod(e,t){return this.stripe.paymentMethods.attach(e,{customer:t})}async detachPaymentMethod(e){return this.stripe.paymentMethods.detach(e)}async setDefaultPaymentMethod(e,t){return this.stripe.customers.update(e,{invoice_settings:{default_payment_method:t}})}async getCustomerInvoices(e,t=10){return this.stripe.invoices.list({customer:e,limit:t})}async getInvoice(e){return this.stripe.invoices.retrieve(e)}constructWebhookEvent(e,t,n){return this.stripe.webhooks.constructEvent(e,t,n)}async getPrice(e){return this.stripe.prices.retrieve(e,{expand:["product"]})}async getPrices(e){return this.stripe.prices.list({active:e?.active,limit:e?.limit||10,product:e?.product,expand:["data.product"]})}async getProduct(e){return this.stripe.products.retrieve(e)}async createEphemeralKey(e,t){return this.stripe.ephemeralKeys.create({customer:e},{apiVersion:t})}};var p=class{stripeAPI;handlers;constructor(e,t={}){this.stripeAPI=new u(e),this.handlers=t}async handleWebhook(e,t,n){try{let o=this.stripeAPI.constructWebhookEvent(e,t,n);return console.log(`Received webhook event: ${o.type}`),await this.processEvent(o),{success:!0}}catch(o){let r=o instanceof Error?o.message:"Unknown webhook error";return console.error("Webhook error:",r),{success:!1,error:r}}}async processEvent(e){switch(e.type){case c.CUSTOMER_SUBSCRIPTION_CREATED:await this.handleSubscriptionCreated(e.data.object);break;case c.CUSTOMER_SUBSCRIPTION_UPDATED:await this.handleSubscriptionUpdated(e.data.object);break;case c.CUSTOMER_SUBSCRIPTION_DELETED:await this.handleSubscriptionDeleted(e.data.object);break;case c.INVOICE_PAYMENT_SUCCEEDED:await this.handleInvoicePaymentSucceeded(e.data.object);break;case c.INVOICE_PAYMENT_FAILED:await this.handleInvoicePaymentFailed(e.data.object);break;case c.CHECKOUT_SESSION_COMPLETED:await this.handleCheckoutSessionCompleted(e.data.object);break;case c.PAYMENT_INTENT_SUCCEEDED:await this.handlePaymentIntentSucceeded(e.data.object);break;case c.PAYMENT_INTENT_PAYMENT_FAILED:await this.handlePaymentIntentFailed(e.data.object);break;default:console.log(`Unhandled event type: ${e.type}`)}}async handleSubscriptionCreated(e){console.log(`Subscription created: ${e.id}`),this.handlers.onCustomerSubscriptionCreated&&await this.handlers.onCustomerSubscriptionCreated(e),console.log(`Customer ${e.customer} subscribed to ${e.items.data[0]?.price.id}`)}async handleSubscriptionUpdated(e){console.log(`Subscription updated: ${e.id}`),this.handlers.onCustomerSubscriptionUpdated&&await this.handlers.onCustomerSubscriptionUpdated(e),console.log(`Subscription ${e.id} status: ${e.status}`)}async handleSubscriptionDeleted(e){console.log(`Subscription deleted: ${e.id}`),this.handlers.onCustomerSubscriptionDeleted&&await this.handlers.onCustomerSubscriptionDeleted(e),console.log(`Customer ${e.customer} cancelled subscription ${e.id}`)}async handleInvoicePaymentSucceeded(e){console.log(`Invoice payment succeeded: ${e.id}`),this.handlers.onInvoicePaymentSucceeded&&await this.handlers.onInvoicePaymentSucceeded(e);let t=e.subscription;t&&console.log(`Payment succeeded for subscription ${t}`)}async handleInvoicePaymentFailed(e){console.log(`Invoice payment failed: ${e.id}`),this.handlers.onInvoicePaymentFailed&&await this.handlers.onInvoicePaymentFailed(e);let t=e.subscription;t&&console.log(`Payment failed for subscription ${t}`)}async handleCheckoutSessionCompleted(e){console.log(`Checkout session completed: ${e.id}`),this.handlers.onCheckoutSessionCompleted&&await this.handlers.onCheckoutSessionCompleted(e),e.mode==="subscription"?console.log(`Subscription checkout completed for customer ${e.customer}`):console.log(`Payment checkout completed for customer ${e.customer}`)}async handlePaymentIntentSucceeded(e){console.log(`Payment intent succeeded: ${e.id}`),this.handlers.onPaymentIntentSucceeded&&await this.handlers.onPaymentIntentSucceeded(e),console.log(`Payment of ${e.amount} ${e.currency} succeeded`)}async handlePaymentIntentFailed(e){console.log(`Payment intent failed: ${e.id}`),this.handlers.onPaymentIntentPaymentFailed&&await this.handlers.onPaymentIntentPaymentFailed(e),console.log(`Payment of ${e.amount} ${e.currency} failed`)}},S=(i,e={})=>new p(i,e),y=(i,e,t={})=>{let n=new p(i,t);return async(o,r)=>{try{let s=o.headers["stripe-signature"];if(!s)return r.status(400).json({error:"Missing stripe-signature header"});let a=await n.handleWebhook(o.body,Array.isArray(s)?s[0]:s,e);a.success?r.status(200).json({received:!0}):r.status(400).json({error:a.error})}catch(s){console.error("Webhook middleware error:",s),r.status(500).json({error:"Internal server error"})}}},b=(i,e,t={})=>{let n=new p(i,t);return async(o,r)=>{if(o.method!=="POST")return r.setHeader("Allow","POST"),r.status(405).json({error:"Method not allowed"});try{let s=o.headers["stripe-signature"];if(!s)return r.status(400).json({error:"Missing stripe-signature header"});let a=await n.handleWebhook(o.body,Array.isArray(s)?s[0]:s,e);a.success?r.status(200).json({received:!0}):r.status(400).json({error:a.error})}catch(s){console.error("Webhook handler error:",s),r.status(500).json({error:"Internal server error"})}}};import h from"stripe";var P=async(i,e)=>{let{priceId:t,customerId:n,successUrl:o,cancelUrl:r,mode:s="subscription",metadata:a={}}=e,d={mode:s,success_url:o,cancel_url:r,line_items:[{price:t,quantity:1}],metadata:a};return n?d.customer=n:d.customer_creation="always",s==="subscription"&&(d.subscription_data={metadata:a}),await i.checkout.sessions.create(d)},I=async(i,e)=>{let{amount:t,currency:n,paymentMethodId:o,customerId:r,description:s,metadata:a={}}=e,d={amount:t,currency:n,payment_method:o,confirmation_method:"manual",confirm:!0,return_url:"https://your-website.com/return",metadata:a};return r&&(d.customer=r),s&&(d.description=s),await i.paymentIntents.create(d)},g=async(i,e)=>{let{customerId:t,priceId:n,paymentMethodId:o,trialPeriodDays:r,metadata:s={}}=e,a={customer:t,items:[{price:n}],metadata:s};return o&&(a.default_payment_method=o),r&&(a.trial_period_days=r),await i.subscriptions.create(a)},_=async(i,e)=>{let{subscriptionId:t,priceId:n,quantity:o,metadata:r}=e,s=await i.subscriptions.retrieve(t),a={};return n&&(a.items=[{id:s.items.data[0].id,price:n,quantity:o||1}]),r&&(a.metadata=r),await i.subscriptions.update(t,a)},E=async(i,e,t=!0)=>t?await i.subscriptions.update(e,{cancel_at_period_end:!0}):await i.subscriptions.cancel(e),C=(i,e,t)=>new h(process.env.STRIPE_SECRET_KEY,{apiVersion:"2024-06-20"}).webhooks.constructEvent(i,e,t),v=async(i,e)=>{switch(i.type){case"payment_intent.succeeded":e.onPaymentSucceeded&&await e.onPaymentSucceeded(i.data.object);break;case"payment_intent.payment_failed":e.onPaymentFailed&&await e.onPaymentFailed(i.data.object);break;case"customer.subscription.created":e.onSubscriptionCreated&&await e.onSubscriptionCreated(i.data.object);break;case"customer.subscription.updated":e.onSubscriptionUpdated&&await e.onSubscriptionUpdated(i.data.object);break;case"customer.subscription.deleted":e.onSubscriptionDeleted&&await e.onSubscriptionDeleted(i.data.object);break;case"invoice.paid":e.onInvoicePaid&&await e.onInvoicePaid(i.data.object);break;case"invoice.payment_failed":e.onInvoicePaymentFailed&&await e.onInvoicePaymentFailed(i.data.object);break;default:console.log(`Unhandled event type: ${i.type}`)}};export{u as StripeServerAPI,p as StripeWebhookHandler,E as cancelSubscription,b as createNextJSWebhookHandler,P as createStripeCheckoutSession,S as createStripeWebhookHandler,y as createStripeWebhookMiddleware,g as createSubscription,v as handleStripeWebhook,I as processPayment,_ as updateSubscription,C as validateStripeSignature};
|
|
2
2
|
//# sourceMappingURL=server.mjs.map
|
package/dist/server.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/api/stripe-server.ts","../src/shared/constants.ts","../src/server/webhooks/stripe.ts"],"sourcesContent":["import Stripe from 'stripe';\nimport { STRIPE_API_VERSION } from '../../shared/constants';\n\nexport class StripeServerAPI {\n private stripe: Stripe;\n\n constructor(\n secretKey: string,\n options?: {\n apiVersion?: string;\n typescript?: boolean;\n }\n ) {\n this.stripe = new Stripe(secretKey, {\n apiVersion:\n (options?.apiVersion as Stripe.LatestApiVersion) || STRIPE_API_VERSION,\n typescript: true,\n });\n }\n\n // Customer methods\n async createCustomer(params: {\n email: string;\n name?: string;\n phone?: string;\n metadata?: Record<string, string>;\n }) {\n return this.stripe.customers.create({\n email: params.email,\n name: params.name,\n phone: params.phone,\n metadata: params.metadata,\n });\n }\n\n async getCustomer(customerId: string) {\n return this.stripe.customers.retrieve(customerId);\n }\n\n async updateCustomer(\n customerId: string,\n params: {\n email?: string;\n name?: string;\n phone?: string;\n metadata?: Record<string, string>;\n }\n ) {\n return this.stripe.customers.update(customerId, params);\n }\n\n async deleteCustomer(customerId: string) {\n return this.stripe.customers.del(customerId);\n }\n\n // Subscription methods\n async createSubscription(params: {\n customerId: string;\n priceId: string;\n quantity?: number;\n trialPeriodDays?: number;\n metadata?: Record<string, string>;\n paymentBehavior?:\n | 'default_incomplete'\n | 'error_if_incomplete'\n | 'allow_incomplete';\n }) {\n return this.stripe.subscriptions.create({\n customer: params.customerId,\n items: [\n {\n price: params.priceId,\n quantity: params.quantity || 1,\n },\n ],\n trial_period_days: params.trialPeriodDays,\n metadata: params.metadata,\n payment_behavior: params.paymentBehavior || 'default_incomplete',\n payment_settings: {\n save_default_payment_method: 'on_subscription',\n },\n expand: ['latest_invoice.payment_intent'],\n });\n }\n\n async getSubscription(subscriptionId: string) {\n return this.stripe.subscriptions.retrieve(subscriptionId, {\n expand: ['default_payment_method'],\n });\n }\n\n async updateSubscription(\n subscriptionId: string,\n params: {\n priceId?: string;\n quantity?: number;\n metadata?: Record<string, string>;\n cancelAtPeriodEnd?: boolean;\n }\n ) {\n const updateData: Stripe.SubscriptionUpdateParams = {};\n\n if (params.priceId) {\n // Get current subscription to update items\n const subscription = await this.getSubscription(subscriptionId);\n const currentItem = subscription.items.data[0];\n\n updateData.items = [\n {\n id: currentItem.id,\n price: params.priceId,\n quantity: params.quantity || currentItem.quantity,\n },\n ];\n }\n\n if (params.metadata) {\n updateData.metadata = params.metadata;\n }\n\n if (typeof params.cancelAtPeriodEnd === 'boolean') {\n updateData.cancel_at_period_end = params.cancelAtPeriodEnd;\n }\n\n return this.stripe.subscriptions.update(subscriptionId, updateData);\n }\n\n async cancelSubscription(\n subscriptionId: string,\n immediately: boolean = false\n ) {\n if (immediately) {\n return this.stripe.subscriptions.cancel(subscriptionId);\n } else {\n return this.stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n }\n }\n\n async reactivateSubscription(subscriptionId: string) {\n return this.stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n }\n\n async getCustomerSubscriptions(customerId: string) {\n return this.stripe.subscriptions.list({\n customer: customerId,\n expand: ['data.default_payment_method'],\n });\n }\n\n // Checkout methods\n async createCheckoutSession(params: {\n priceId: string;\n customerId?: string;\n customerEmail?: string;\n successUrl: string;\n cancelUrl: string;\n mode?: 'payment' | 'subscription' | 'setup';\n allowPromotionCodes?: boolean;\n billingAddressCollection?: 'auto' | 'required';\n metadata?: Record<string, string>;\n trialPeriodDays?: number;\n }) {\n const sessionParams: Stripe.Checkout.SessionCreateParams = {\n payment_method_types: ['card'],\n line_items: [\n {\n price: params.priceId,\n quantity: 1,\n },\n ],\n mode: params.mode || 'subscription',\n success_url: params.successUrl,\n cancel_url: params.cancelUrl,\n allow_promotion_codes: params.allowPromotionCodes,\n billing_address_collection: params.billingAddressCollection,\n metadata: params.metadata,\n };\n\n if (params.customerId) {\n sessionParams.customer = params.customerId;\n } else if (params.customerEmail) {\n sessionParams.customer_email = params.customerEmail;\n }\n\n if (params.mode === 'subscription' && params.trialPeriodDays) {\n sessionParams.subscription_data = {\n trial_period_days: params.trialPeriodDays,\n };\n }\n\n return this.stripe.checkout.sessions.create(sessionParams);\n }\n\n // Payment Intent methods\n async getPaymentIntent(paymentIntentId: string) {\n return this.stripe.paymentIntents.retrieve(paymentIntentId);\n }\n\n async createPaymentIntent(params: {\n amount: number;\n currency: string;\n customerId?: string;\n paymentMethodTypes?: string[];\n metadata?: Record<string, string>;\n description?: string;\n }) {\n return this.stripe.paymentIntents.create({\n amount: params.amount,\n currency: params.currency,\n customer: params.customerId,\n payment_method_types: params.paymentMethodTypes || ['card'],\n metadata: params.metadata,\n description: params.description,\n });\n }\n\n async confirmPaymentIntent(\n paymentIntentId: string,\n params?: {\n paymentMethod?: string;\n }\n ) {\n return this.stripe.paymentIntents.confirm(paymentIntentId, {\n payment_method: params?.paymentMethod,\n });\n }\n\n // Setup Intent methods (for subscriptions without immediate payment)\n async createSetupIntent(params: {\n customerId: string;\n paymentMethodTypes?: string[];\n metadata?: Record<string, string>;\n }) {\n return this.stripe.setupIntents.create({\n customer: params.customerId,\n payment_method_types: params.paymentMethodTypes || ['card'],\n metadata: params.metadata,\n usage: 'off_session',\n });\n }\n\n // Customer Portal methods\n async createPortalSession(params: { customerId: string; returnUrl: string }) {\n return this.stripe.billingPortal.sessions.create({\n customer: params.customerId,\n return_url: params.returnUrl,\n });\n }\n\n // Payment Method methods\n async getCustomerPaymentMethods(\n customerId: string,\n type: Stripe.PaymentMethodListParams.Type = 'card'\n ) {\n return this.stripe.paymentMethods.list({\n customer: customerId,\n type,\n });\n }\n\n async attachPaymentMethod(paymentMethodId: string, customerId: string) {\n return this.stripe.paymentMethods.attach(paymentMethodId, {\n customer: customerId,\n });\n }\n\n async detachPaymentMethod(paymentMethodId: string) {\n return this.stripe.paymentMethods.detach(paymentMethodId);\n }\n\n async setDefaultPaymentMethod(customerId: string, paymentMethodId: string) {\n return this.stripe.customers.update(customerId, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n }\n\n // Invoice methods\n async getCustomerInvoices(customerId: string, limit: number = 10) {\n return this.stripe.invoices.list({\n customer: customerId,\n limit,\n });\n }\n\n async getInvoice(invoiceId: string) {\n return this.stripe.invoices.retrieve(invoiceId);\n }\n\n // Webhook methods\n constructWebhookEvent(\n payload: string | Buffer,\n signature: string,\n webhookSecret: string\n ) {\n return this.stripe.webhooks.constructEvent(\n payload,\n signature,\n webhookSecret\n );\n }\n\n // Price and Product methods\n async getPrice(priceId: string) {\n return this.stripe.prices.retrieve(priceId, {\n expand: ['product'],\n });\n }\n\n async getPrices(params?: {\n active?: boolean;\n limit?: number;\n product?: string;\n }) {\n return this.stripe.prices.list({\n active: params?.active,\n limit: params?.limit || 10,\n product: params?.product,\n expand: ['data.product'],\n });\n }\n\n async getProduct(productId: string) {\n return this.stripe.products.retrieve(productId);\n }\n\n // Ephemeral Key methods (for mobile)\n async createEphemeralKey(customerId: string, apiVersion: string) {\n return this.stripe.ephemeralKeys.create(\n { customer: customerId },\n { apiVersion }\n );\n }\n}\n","export const STRIPE_API_VERSION = '2023-10-16';\n\nexport const PAYMENT_METHODS = {\n CARD: 'card',\n BANK_ACCOUNT: 'bank_account',\n SEPA_DEBIT: 'sepa_debit',\n IDEAL: 'ideal',\n SOFORT: 'sofort',\n} as const;\n\nexport const SUBSCRIPTION_STATUS = {\n ACTIVE: 'active',\n CANCELED: 'canceled',\n PAST_DUE: 'past_due',\n UNPAID: 'unpaid',\n INCOMPLETE: 'incomplete',\n INCOMPLETE_EXPIRED: 'incomplete_expired',\n TRIALING: 'trialing',\n} as const;\n\nexport const INVOICE_STATUS = {\n DRAFT: 'draft',\n OPEN: 'open',\n PAID: 'paid',\n UNCOLLECTIBLE: 'uncollectible',\n VOID: 'void',\n} as const;\n\nexport const CHECKOUT_MODE = {\n PAYMENT: 'payment',\n SUBSCRIPTION: 'subscription',\n SETUP: 'setup',\n} as const;\n\nexport const BILLING_INTERVALS = {\n DAY: 'day',\n WEEK: 'week',\n MONTH: 'month',\n YEAR: 'year',\n} as const;\n\nexport const CURRENCY_SYMBOLS = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n CAD: 'C$',\n AUD: 'A$',\n CHF: 'CHF',\n CNY: '¥',\n SEK: 'kr',\n NZD: 'NZ$',\n} as const;\n\nexport const DEFAULT_CURRENCY = 'USD';\n\nexport const WEBHOOK_EVENTS = {\n CUSTOMER_SUBSCRIPTION_CREATED: 'customer.subscription.created',\n CUSTOMER_SUBSCRIPTION_UPDATED: 'customer.subscription.updated',\n CUSTOMER_SUBSCRIPTION_DELETED: 'customer.subscription.deleted',\n INVOICE_PAYMENT_SUCCEEDED: 'invoice.payment_succeeded',\n INVOICE_PAYMENT_FAILED: 'invoice.payment_failed',\n CHECKOUT_SESSION_COMPLETED: 'checkout.session.completed',\n PAYMENT_INTENT_SUCCEEDED: 'payment_intent.succeeded',\n PAYMENT_INTENT_PAYMENT_FAILED: 'payment_intent.payment_failed',\n} as const;\n\nexport const ERROR_MESSAGES = {\n PROVIDER_NOT_CONFIGURED: 'Payments provider is not properly configured',\n STRIPE_NOT_LOADED: 'Stripe has not been loaded yet',\n INVALID_PRICE_ID: 'Invalid price ID provided',\n INVALID_CUSTOMER_ID: 'Invalid customer ID provided',\n CHECKOUT_FAILED: 'Checkout session creation failed',\n PAYMENT_FAILED: 'Payment processing failed',\n SUBSCRIPTION_NOT_FOUND: 'Subscription not found',\n CUSTOMER_NOT_FOUND: 'Customer not found',\n} as const;\n","import Stripe from 'stripe';\nimport { StripeServerAPI } from '../api/stripe-server';\nimport { WEBHOOK_EVENTS } from '../../shared/constants';\nimport { Request, Response } from 'express';\nimport { NextApiRequest, NextApiResponse } from 'next';\n\nexport interface WebhookHandlers {\n onCustomerSubscriptionCreated?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onCustomerSubscriptionUpdated?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onCustomerSubscriptionDeleted?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onInvoicePaymentSucceeded?: (invoice: Stripe.Invoice) => Promise<void>;\n onInvoicePaymentFailed?: (invoice: Stripe.Invoice) => Promise<void>;\n onCheckoutSessionCompleted?: (\n session: Stripe.Checkout.Session\n ) => Promise<void>;\n onPaymentIntentSucceeded?: (\n paymentIntent: Stripe.PaymentIntent\n ) => Promise<void>;\n onPaymentIntentPaymentFailed?: (\n paymentIntent: Stripe.PaymentIntent\n ) => Promise<void>;\n}\n\nexport class StripeWebhookHandler {\n private stripeAPI: StripeServerAPI;\n private handlers: WebhookHandlers;\n\n constructor(secretKey: string, handlers: WebhookHandlers = {}) {\n this.stripeAPI = new StripeServerAPI(secretKey);\n this.handlers = handlers;\n }\n\n async handleWebhook(\n payload: string | Buffer,\n signature: string,\n webhookSecret: string\n ): Promise<{ success: boolean; error?: string }> {\n try {\n const event = this.stripeAPI.constructWebhookEvent(\n payload,\n signature,\n webhookSecret\n );\n\n console.log(`Received webhook event: ${event.type}`);\n\n await this.processEvent(event);\n\n return { success: true };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown webhook error';\n console.error('Webhook error:', errorMessage);\n return { success: false, error: errorMessage };\n }\n }\n\n private async processEvent(event: Stripe.Event): Promise<void> {\n switch (event.type) {\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_CREATED:\n await this.handleSubscriptionCreated(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_UPDATED:\n await this.handleSubscriptionUpdated(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_DELETED:\n await this.handleSubscriptionDeleted(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.INVOICE_PAYMENT_SUCCEEDED:\n await this.handleInvoicePaymentSucceeded(\n event.data.object as Stripe.Invoice\n );\n break;\n\n case WEBHOOK_EVENTS.INVOICE_PAYMENT_FAILED:\n await this.handleInvoicePaymentFailed(\n event.data.object as Stripe.Invoice\n );\n break;\n\n case WEBHOOK_EVENTS.CHECKOUT_SESSION_COMPLETED:\n await this.handleCheckoutSessionCompleted(\n event.data.object as Stripe.Checkout.Session\n );\n break;\n\n case WEBHOOK_EVENTS.PAYMENT_INTENT_SUCCEEDED:\n await this.handlePaymentIntentSucceeded(\n event.data.object as Stripe.PaymentIntent\n );\n break;\n\n case WEBHOOK_EVENTS.PAYMENT_INTENT_PAYMENT_FAILED:\n await this.handlePaymentIntentFailed(\n event.data.object as Stripe.PaymentIntent\n );\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n }\n\n private async handleSubscriptionCreated(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription created: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionCreated) {\n await this.handlers.onCustomerSubscriptionCreated(subscription);\n }\n\n // Default behavior: Log subscription details\n\n console.log(\n `Customer ${subscription.customer} subscribed to ${subscription.items.data[0]?.price.id}`\n );\n }\n\n private async handleSubscriptionUpdated(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription updated: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionUpdated) {\n await this.handlers.onCustomerSubscriptionUpdated(subscription);\n }\n\n // Default behavior: Log status changes\n\n console.log(\n `Subscription ${subscription.id} status: ${subscription.status}`\n );\n }\n\n private async handleSubscriptionDeleted(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription deleted: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionDeleted) {\n await this.handlers.onCustomerSubscriptionDeleted(subscription);\n }\n\n // Default behavior: Log cancellation\n\n console.log(\n `Customer ${subscription.customer} cancelled subscription ${subscription.id}`\n );\n }\n\n private async handleInvoicePaymentSucceeded(\n invoice: Stripe.Invoice\n ): Promise<void> {\n console.log(`Invoice payment succeeded: ${invoice.id}`);\n\n if (this.handlers.onInvoicePaymentSucceeded) {\n await this.handlers.onInvoicePaymentSucceeded(invoice);\n }\n\n // Default behavior: Log successful payment\n const subscriptionId = (\n invoice as Stripe.Invoice & { subscription?: string }\n ).subscription;\n if (subscriptionId) {\n console.log(`Payment succeeded for subscription ${subscriptionId}`);\n }\n }\n\n private async handleInvoicePaymentFailed(\n invoice: Stripe.Invoice\n ): Promise<void> {\n console.log(`Invoice payment failed: ${invoice.id}`);\n\n if (this.handlers.onInvoicePaymentFailed) {\n await this.handlers.onInvoicePaymentFailed(invoice);\n }\n\n // Default behavior: Log failed payment\n const subscriptionId = (\n invoice as Stripe.Invoice & { subscription?: string }\n ).subscription;\n if (subscriptionId) {\n console.log(`Payment failed for subscription ${subscriptionId}`);\n }\n }\n\n private async handleCheckoutSessionCompleted(\n session: Stripe.Checkout.Session\n ): Promise<void> {\n console.log(`Checkout session completed: ${session.id}`);\n\n if (this.handlers.onCheckoutSessionCompleted) {\n await this.handlers.onCheckoutSessionCompleted(session);\n }\n\n // Default behavior: Log successful checkout\n if (session.mode === 'subscription') {\n console.log(\n `Subscription checkout completed for customer ${session.customer}`\n );\n } else {\n console.log(\n `Payment checkout completed for customer ${session.customer}`\n );\n }\n }\n\n private async handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent\n ): Promise<void> {\n console.log(`Payment intent succeeded: ${paymentIntent.id}`);\n\n if (this.handlers.onPaymentIntentSucceeded) {\n await this.handlers.onPaymentIntentSucceeded(paymentIntent);\n }\n\n // Default behavior: Log successful payment\n\n console.log(\n `Payment of ${paymentIntent.amount} ${paymentIntent.currency} succeeded`\n );\n }\n\n private async handlePaymentIntentFailed(\n paymentIntent: Stripe.PaymentIntent\n ): Promise<void> {\n console.log(`Payment intent failed: ${paymentIntent.id}`);\n\n if (this.handlers.onPaymentIntentPaymentFailed) {\n await this.handlers.onPaymentIntentPaymentFailed(paymentIntent);\n }\n\n // Default behavior: Log failed payment\n\n console.log(\n `Payment of ${paymentIntent.amount} ${paymentIntent.currency} failed`\n );\n }\n}\n\n// Utility function to create a webhook handler with custom handlers\nexport const createStripeWebhookHandler = (\n secretKey: string,\n handlers: WebhookHandlers = {}\n): StripeWebhookHandler => {\n return new StripeWebhookHandler(secretKey, handlers);\n};\n\n// Express.js middleware for handling Stripe webhooks\nexport const createStripeWebhookMiddleware = (\n secretKey: string,\n webhookSecret: string,\n handlers: WebhookHandlers = {}\n) => {\n const webhookHandler = new StripeWebhookHandler(secretKey, handlers);\n\n return async (req: Request, res: Response) => {\n try {\n const signature = req.headers['stripe-signature'];\n\n if (!signature) {\n return res\n .status(400)\n .json({ error: 'Missing stripe-signature header' });\n }\n\n const result = await webhookHandler.handleWebhook(\n req.body,\n Array.isArray(signature) ? signature[0] : signature,\n webhookSecret\n );\n\n if (result.success) {\n res.status(200).json({ received: true });\n } else {\n res.status(400).json({ error: result.error });\n }\n } catch (error) {\n console.error('Webhook middleware error:', error);\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n};\n\n// Next.js API route handler\nexport const createNextJSWebhookHandler = (\n secretKey: string,\n webhookSecret: string,\n handlers: WebhookHandlers = {}\n) => {\n const webhookHandler = new StripeWebhookHandler(secretKey, handlers);\n\n return async (req: NextApiRequest, res: NextApiResponse) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST');\n return res.status(405).json({ error: 'Method not allowed' });\n }\n\n try {\n const signature = req.headers['stripe-signature'];\n\n if (!signature) {\n return res\n .status(400)\n .json({ error: 'Missing stripe-signature header' });\n }\n\n const result = await webhookHandler.handleWebhook(\n req.body,\n Array.isArray(signature) ? signature[0] : signature,\n webhookSecret\n );\n\n if (result.success) {\n res.status(200).json({ received: true });\n } else {\n res.status(400).json({ error: result.error });\n }\n } catch (error) {\n console.error('Webhook handler error:', error);\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n};\n"],"mappings":"AAAA,OAAOA,MAAY,SCAZ,IAAMC,EAAqB,aAwD3B,IAAMC,EAAiB,CAC5B,8BAA+B,gCAC/B,8BAA+B,gCAC/B,8BAA+B,gCAC/B,0BAA2B,4BAC3B,uBAAwB,yBACxB,2BAA4B,6BAC5B,yBAA0B,2BAC1B,8BAA+B,+BACjC,ED9DO,IAAMC,EAAN,KAAsB,CACnB,OAER,YACEC,EACAC,EAIA,CACA,KAAK,OAAS,IAAIC,EAAOF,EAAW,CAClC,WACGC,GAAS,YAA0CE,EACtD,WAAY,EACd,CAAC,CACH,CAGA,MAAM,eAAeC,EAKlB,CACD,OAAO,KAAK,OAAO,UAAU,OAAO,CAClC,MAAOA,EAAO,MACd,KAAMA,EAAO,KACb,MAAOA,EAAO,MACd,SAAUA,EAAO,QACnB,CAAC,CACH,CAEA,MAAM,YAAYC,EAAoB,CACpC,OAAO,KAAK,OAAO,UAAU,SAASA,CAAU,CAClD,CAEA,MAAM,eACJA,EACAD,EA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AAK,CAAE,MAAO,uBAAwB,CAAC,CACzD,CACF,CACF,EAGaE,EAA6B,CACxCrB,EACAK,EACAJ,EAA4B,CAAC,IAC1B,CACH,IAAMgB,EAAiB,IAAIlB,EAAqBC,EAAWC,CAAQ,EAEnE,MAAO,OAAOiB,EAAqBC,IAAyB,CAC1D,GAAID,EAAI,SAAW,OACjB,OAAAC,EAAI,UAAU,QAAS,MAAM,EACtBA,EAAI,OAAO,GAAG,EAAE,KAAK,CAAE,MAAO,oBAAqB,CAAC,EAG7D,GAAI,CACF,IAAMf,EAAYc,EAAI,QAAQ,kBAAkB,EAEhD,GAAI,CAACd,EACH,OAAOe,EACJ,OAAO,GAAG,EACV,KAAK,CAAE,MAAO,iCAAkC,CAAC,EAGtD,IAAMC,EAAS,MAAMH,EAAe,cAClCC,EAAI,KACJ,MAAM,QAAQd,CAAS,EAAIA,EAAU,CAAC,EAAIA,EAC1CC,CACF,EAEIe,EAAO,QACTD,EAAI,OAAO,GAAG,EAAE,KAAK,CAAE,SAAU,EAAK,CAAC,EAEvCA,EAAI,OAAO,GAAG,EAAE,KAAK,CAAE,MAAOC,EAAO,KAAM,CAAC,CAEhD,OAASb,EAAO,CACd,QAAQ,MAAM,yBAA0BA,CAAK,EAC7CY,EAAI,OAAO,GAAG,EAAE,KAAK,CAAE,MAAO,uBAAwB,CAAC,CACzD,CACF,CACF","names":["Stripe","STRIPE_API_VERSION","WEBHOOK_EVENTS","StripeServerAPI","secretKey","options","Stripe","STRIPE_API_VERSION","params","customerId","subscriptionId","updateData","currentItem","immediately","sessionParams","paymentIntentId","type","paymentMethodId","limit","invoiceId","payload","signature","webhookSecret","priceId","productId","apiVersion","StripeWebhookHandler","secretKey","handlers","StripeServerAPI","payload","signature","webhookSecret","event","error","errorMessage","WEBHOOK_EVENTS","subscription","invoice","subscriptionId","session","paymentIntent","createStripeWebhookHandler","createStripeWebhookMiddleware","webhookHandler","req","res","result","createNextJSWebhookHandler"]}
|
|
1
|
+
{"version":3,"sources":["../src/server/api/stripe-server.ts","../src/shared/constants.ts","../src/server/webhooks/stripe.ts","../src/server/utils/stripe-helpers.ts"],"sourcesContent":["import Stripe from 'stripe';\nimport { STRIPE_API_VERSION } from '../../shared/constants';\n\nexport class StripeServerAPI {\n private stripe: Stripe;\n\n constructor(\n secretKey: string,\n options?: {\n apiVersion?: string;\n typescript?: boolean;\n }\n ) {\n this.stripe = new Stripe(secretKey, {\n apiVersion:\n (options?.apiVersion as Stripe.LatestApiVersion) || STRIPE_API_VERSION,\n typescript: true,\n });\n }\n\n // Customer methods\n async createCustomer(params: {\n email: string;\n name?: string;\n phone?: string;\n metadata?: Record<string, string>;\n }) {\n return this.stripe.customers.create({\n email: params.email,\n name: params.name,\n phone: params.phone,\n metadata: params.metadata,\n });\n }\n\n async getCustomer(customerId: string) {\n return this.stripe.customers.retrieve(customerId);\n }\n\n async updateCustomer(\n customerId: string,\n params: {\n email?: string;\n name?: string;\n phone?: string;\n metadata?: Record<string, string>;\n }\n ) {\n return this.stripe.customers.update(customerId, params);\n }\n\n async deleteCustomer(customerId: string) {\n return this.stripe.customers.del(customerId);\n }\n\n // Subscription methods\n async createSubscription(params: {\n customerId: string;\n priceId: string;\n quantity?: number;\n trialPeriodDays?: number;\n metadata?: Record<string, string>;\n paymentBehavior?:\n | 'default_incomplete'\n | 'error_if_incomplete'\n | 'allow_incomplete';\n }) {\n return this.stripe.subscriptions.create({\n customer: params.customerId,\n items: [\n {\n price: params.priceId,\n quantity: params.quantity || 1,\n },\n ],\n trial_period_days: params.trialPeriodDays,\n metadata: params.metadata,\n payment_behavior: params.paymentBehavior || 'default_incomplete',\n payment_settings: {\n save_default_payment_method: 'on_subscription',\n },\n expand: ['latest_invoice.payment_intent'],\n });\n }\n\n async getSubscription(subscriptionId: string) {\n return this.stripe.subscriptions.retrieve(subscriptionId, {\n expand: ['default_payment_method'],\n });\n }\n\n async updateSubscription(\n subscriptionId: string,\n params: {\n priceId?: string;\n quantity?: number;\n metadata?: Record<string, string>;\n cancelAtPeriodEnd?: boolean;\n }\n ) {\n const updateData: Stripe.SubscriptionUpdateParams = {};\n\n if (params.priceId) {\n // Get current subscription to update items\n const subscription = await this.getSubscription(subscriptionId);\n const currentItem = subscription.items.data[0];\n\n updateData.items = [\n {\n id: currentItem.id,\n price: params.priceId,\n quantity: params.quantity || currentItem.quantity,\n },\n ];\n }\n\n if (params.metadata) {\n updateData.metadata = params.metadata;\n }\n\n if (typeof params.cancelAtPeriodEnd === 'boolean') {\n updateData.cancel_at_period_end = params.cancelAtPeriodEnd;\n }\n\n return this.stripe.subscriptions.update(subscriptionId, updateData);\n }\n\n async cancelSubscription(\n subscriptionId: string,\n immediately: boolean = false\n ) {\n if (immediately) {\n return this.stripe.subscriptions.cancel(subscriptionId);\n } else {\n return this.stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n }\n }\n\n async reactivateSubscription(subscriptionId: string) {\n return this.stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n }\n\n async getCustomerSubscriptions(customerId: string) {\n return this.stripe.subscriptions.list({\n customer: customerId,\n expand: ['data.default_payment_method'],\n });\n }\n\n // Checkout methods\n async createCheckoutSession(params: {\n priceId: string;\n customerId?: string;\n customerEmail?: string;\n successUrl: string;\n cancelUrl: string;\n mode?: 'payment' | 'subscription' | 'setup';\n allowPromotionCodes?: boolean;\n billingAddressCollection?: 'auto' | 'required';\n metadata?: Record<string, string>;\n trialPeriodDays?: number;\n }) {\n const sessionParams: Stripe.Checkout.SessionCreateParams = {\n payment_method_types: ['card'],\n line_items: [\n {\n price: params.priceId,\n quantity: 1,\n },\n ],\n mode: params.mode || 'subscription',\n success_url: params.successUrl,\n cancel_url: params.cancelUrl,\n allow_promotion_codes: params.allowPromotionCodes,\n billing_address_collection: params.billingAddressCollection,\n metadata: params.metadata,\n };\n\n if (params.customerId) {\n sessionParams.customer = params.customerId;\n } else if (params.customerEmail) {\n sessionParams.customer_email = params.customerEmail;\n }\n\n if (params.mode === 'subscription' && params.trialPeriodDays) {\n sessionParams.subscription_data = {\n trial_period_days: params.trialPeriodDays,\n };\n }\n\n return this.stripe.checkout.sessions.create(sessionParams);\n }\n\n // Payment Intent methods\n async getPaymentIntent(paymentIntentId: string) {\n return this.stripe.paymentIntents.retrieve(paymentIntentId);\n }\n\n async createPaymentIntent(params: {\n amount: number;\n currency: string;\n customerId?: string;\n paymentMethodTypes?: string[];\n metadata?: Record<string, string>;\n description?: string;\n }) {\n return this.stripe.paymentIntents.create({\n amount: params.amount,\n currency: params.currency,\n customer: params.customerId,\n payment_method_types: params.paymentMethodTypes || ['card'],\n metadata: params.metadata,\n description: params.description,\n });\n }\n\n async confirmPaymentIntent(\n paymentIntentId: string,\n params?: {\n paymentMethod?: string;\n }\n ) {\n return this.stripe.paymentIntents.confirm(paymentIntentId, {\n payment_method: params?.paymentMethod,\n });\n }\n\n // Setup Intent methods (for subscriptions without immediate payment)\n async createSetupIntent(params: {\n customerId: string;\n paymentMethodTypes?: string[];\n metadata?: Record<string, string>;\n }) {\n return this.stripe.setupIntents.create({\n customer: params.customerId,\n payment_method_types: params.paymentMethodTypes || ['card'],\n metadata: params.metadata,\n usage: 'off_session',\n });\n }\n\n // Customer Portal methods\n async createPortalSession(params: { customerId: string; returnUrl: string }) {\n return this.stripe.billingPortal.sessions.create({\n customer: params.customerId,\n return_url: params.returnUrl,\n });\n }\n\n // Payment Method methods\n async getCustomerPaymentMethods(\n customerId: string,\n type: Stripe.PaymentMethodListParams.Type = 'card'\n ) {\n return this.stripe.paymentMethods.list({\n customer: customerId,\n type,\n });\n }\n\n async attachPaymentMethod(paymentMethodId: string, customerId: string) {\n return this.stripe.paymentMethods.attach(paymentMethodId, {\n customer: customerId,\n });\n }\n\n async detachPaymentMethod(paymentMethodId: string) {\n return this.stripe.paymentMethods.detach(paymentMethodId);\n }\n\n async setDefaultPaymentMethod(customerId: string, paymentMethodId: string) {\n return this.stripe.customers.update(customerId, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n }\n\n // Invoice methods\n async getCustomerInvoices(customerId: string, limit: number = 10) {\n return this.stripe.invoices.list({\n customer: customerId,\n limit,\n });\n }\n\n async getInvoice(invoiceId: string) {\n return this.stripe.invoices.retrieve(invoiceId);\n }\n\n // Webhook methods\n constructWebhookEvent(\n payload: string | Buffer,\n signature: string,\n webhookSecret: string\n ) {\n return this.stripe.webhooks.constructEvent(\n payload,\n signature,\n webhookSecret\n );\n }\n\n // Price and Product methods\n async getPrice(priceId: string) {\n return this.stripe.prices.retrieve(priceId, {\n expand: ['product'],\n });\n }\n\n async getPrices(params?: {\n active?: boolean;\n limit?: number;\n product?: string;\n }) {\n return this.stripe.prices.list({\n active: params?.active,\n limit: params?.limit || 10,\n product: params?.product,\n expand: ['data.product'],\n });\n }\n\n async getProduct(productId: string) {\n return this.stripe.products.retrieve(productId);\n }\n\n // Ephemeral Key methods (for mobile)\n async createEphemeralKey(customerId: string, apiVersion: string) {\n return this.stripe.ephemeralKeys.create(\n { customer: customerId },\n { apiVersion }\n );\n }\n}\n","export const STRIPE_API_VERSION = '2023-10-16';\n\nexport const PAYMENT_METHODS = {\n CARD: 'card',\n BANK_ACCOUNT: 'bank_account',\n SEPA_DEBIT: 'sepa_debit',\n IDEAL: 'ideal',\n SOFORT: 'sofort',\n} as const;\n\nexport const SUBSCRIPTION_STATUS = {\n ACTIVE: 'active',\n CANCELED: 'canceled',\n PAST_DUE: 'past_due',\n UNPAID: 'unpaid',\n INCOMPLETE: 'incomplete',\n INCOMPLETE_EXPIRED: 'incomplete_expired',\n TRIALING: 'trialing',\n} as const;\n\nexport const INVOICE_STATUS = {\n DRAFT: 'draft',\n OPEN: 'open',\n PAID: 'paid',\n UNCOLLECTIBLE: 'uncollectible',\n VOID: 'void',\n} as const;\n\nexport const CHECKOUT_MODE = {\n PAYMENT: 'payment',\n SUBSCRIPTION: 'subscription',\n SETUP: 'setup',\n} as const;\n\nexport const BILLING_INTERVALS = {\n DAY: 'day',\n WEEK: 'week',\n MONTH: 'month',\n YEAR: 'year',\n} as const;\n\nexport const CURRENCY_SYMBOLS = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n CAD: 'C$',\n AUD: 'A$',\n CHF: 'CHF',\n CNY: '¥',\n SEK: 'kr',\n NZD: 'NZ$',\n} as const;\n\nexport const DEFAULT_CURRENCY = 'USD';\n\nexport const WEBHOOK_EVENTS = {\n CUSTOMER_SUBSCRIPTION_CREATED: 'customer.subscription.created',\n CUSTOMER_SUBSCRIPTION_UPDATED: 'customer.subscription.updated',\n CUSTOMER_SUBSCRIPTION_DELETED: 'customer.subscription.deleted',\n INVOICE_PAYMENT_SUCCEEDED: 'invoice.payment_succeeded',\n INVOICE_PAYMENT_FAILED: 'invoice.payment_failed',\n CHECKOUT_SESSION_COMPLETED: 'checkout.session.completed',\n PAYMENT_INTENT_SUCCEEDED: 'payment_intent.succeeded',\n PAYMENT_INTENT_PAYMENT_FAILED: 'payment_intent.payment_failed',\n} as const;\n\nexport const ERROR_MESSAGES = {\n PROVIDER_NOT_CONFIGURED: 'Payments provider is not properly configured',\n STRIPE_NOT_LOADED: 'Stripe has not been loaded yet',\n INVALID_PRICE_ID: 'Invalid price ID provided',\n INVALID_CUSTOMER_ID: 'Invalid customer ID provided',\n CHECKOUT_FAILED: 'Checkout session creation failed',\n PAYMENT_FAILED: 'Payment processing failed',\n SUBSCRIPTION_NOT_FOUND: 'Subscription not found',\n CUSTOMER_NOT_FOUND: 'Customer not found',\n} as const;\n","import Stripe from 'stripe';\nimport { StripeServerAPI } from '../api/stripe-server';\nimport { WEBHOOK_EVENTS } from '../../shared/constants';\nimport { Request, Response } from 'express';\nimport { NextApiRequest, NextApiResponse } from 'next';\n\nexport interface WebhookHandlers {\n onCustomerSubscriptionCreated?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onCustomerSubscriptionUpdated?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onCustomerSubscriptionDeleted?: (\n subscription: Stripe.Subscription\n ) => Promise<void>;\n onInvoicePaymentSucceeded?: (invoice: Stripe.Invoice) => Promise<void>;\n onInvoicePaymentFailed?: (invoice: Stripe.Invoice) => Promise<void>;\n onCheckoutSessionCompleted?: (\n session: Stripe.Checkout.Session\n ) => Promise<void>;\n onPaymentIntentSucceeded?: (\n paymentIntent: Stripe.PaymentIntent\n ) => Promise<void>;\n onPaymentIntentPaymentFailed?: (\n paymentIntent: Stripe.PaymentIntent\n ) => Promise<void>;\n}\n\nexport class StripeWebhookHandler {\n private stripeAPI: StripeServerAPI;\n private handlers: WebhookHandlers;\n\n constructor(secretKey: string, handlers: WebhookHandlers = {}) {\n this.stripeAPI = new StripeServerAPI(secretKey);\n this.handlers = handlers;\n }\n\n async handleWebhook(\n payload: string | Buffer,\n signature: string,\n webhookSecret: string\n ): Promise<{ success: boolean; error?: string }> {\n try {\n const event = this.stripeAPI.constructWebhookEvent(\n payload,\n signature,\n webhookSecret\n );\n\n console.log(`Received webhook event: ${event.type}`);\n\n await this.processEvent(event);\n\n return { success: true };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown webhook error';\n console.error('Webhook error:', errorMessage);\n return { success: false, error: errorMessage };\n }\n }\n\n private async processEvent(event: Stripe.Event): Promise<void> {\n switch (event.type) {\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_CREATED:\n await this.handleSubscriptionCreated(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_UPDATED:\n await this.handleSubscriptionUpdated(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.CUSTOMER_SUBSCRIPTION_DELETED:\n await this.handleSubscriptionDeleted(\n event.data.object as Stripe.Subscription\n );\n break;\n\n case WEBHOOK_EVENTS.INVOICE_PAYMENT_SUCCEEDED:\n await this.handleInvoicePaymentSucceeded(\n event.data.object as Stripe.Invoice\n );\n break;\n\n case WEBHOOK_EVENTS.INVOICE_PAYMENT_FAILED:\n await this.handleInvoicePaymentFailed(\n event.data.object as Stripe.Invoice\n );\n break;\n\n case WEBHOOK_EVENTS.CHECKOUT_SESSION_COMPLETED:\n await this.handleCheckoutSessionCompleted(\n event.data.object as Stripe.Checkout.Session\n );\n break;\n\n case WEBHOOK_EVENTS.PAYMENT_INTENT_SUCCEEDED:\n await this.handlePaymentIntentSucceeded(\n event.data.object as Stripe.PaymentIntent\n );\n break;\n\n case WEBHOOK_EVENTS.PAYMENT_INTENT_PAYMENT_FAILED:\n await this.handlePaymentIntentFailed(\n event.data.object as Stripe.PaymentIntent\n );\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n }\n\n private async handleSubscriptionCreated(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription created: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionCreated) {\n await this.handlers.onCustomerSubscriptionCreated(subscription);\n }\n\n // Default behavior: Log subscription details\n\n console.log(\n `Customer ${subscription.customer} subscribed to ${subscription.items.data[0]?.price.id}`\n );\n }\n\n private async handleSubscriptionUpdated(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription updated: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionUpdated) {\n await this.handlers.onCustomerSubscriptionUpdated(subscription);\n }\n\n // Default behavior: Log status changes\n\n console.log(\n `Subscription ${subscription.id} status: ${subscription.status}`\n );\n }\n\n private async handleSubscriptionDeleted(\n subscription: Stripe.Subscription\n ): Promise<void> {\n console.log(`Subscription deleted: ${subscription.id}`);\n\n if (this.handlers.onCustomerSubscriptionDeleted) {\n await this.handlers.onCustomerSubscriptionDeleted(subscription);\n }\n\n // Default behavior: Log cancellation\n\n console.log(\n `Customer ${subscription.customer} cancelled subscription ${subscription.id}`\n );\n }\n\n private async handleInvoicePaymentSucceeded(\n invoice: Stripe.Invoice\n ): Promise<void> {\n console.log(`Invoice payment succeeded: ${invoice.id}`);\n\n if (this.handlers.onInvoicePaymentSucceeded) {\n await this.handlers.onInvoicePaymentSucceeded(invoice);\n }\n\n // Default behavior: Log successful payment\n const subscriptionId = (\n invoice as Stripe.Invoice & { subscription?: string }\n ).subscription;\n if (subscriptionId) {\n console.log(`Payment succeeded for subscription ${subscriptionId}`);\n }\n }\n\n private async handleInvoicePaymentFailed(\n invoice: Stripe.Invoice\n ): Promise<void> {\n console.log(`Invoice payment failed: ${invoice.id}`);\n\n if (this.handlers.onInvoicePaymentFailed) {\n await this.handlers.onInvoicePaymentFailed(invoice);\n }\n\n // Default behavior: Log failed payment\n const subscriptionId = (\n invoice as Stripe.Invoice & { subscription?: string }\n ).subscription;\n if (subscriptionId) {\n console.log(`Payment failed for subscription ${subscriptionId}`);\n }\n }\n\n private async handleCheckoutSessionCompleted(\n session: Stripe.Checkout.Session\n ): Promise<void> {\n console.log(`Checkout session completed: ${session.id}`);\n\n if (this.handlers.onCheckoutSessionCompleted) {\n await this.handlers.onCheckoutSessionCompleted(session);\n }\n\n // Default behavior: Log successful checkout\n if (session.mode === 'subscription') {\n console.log(\n `Subscription checkout completed for customer ${session.customer}`\n );\n } else {\n console.log(\n `Payment checkout completed for customer ${session.customer}`\n );\n }\n }\n\n private async handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent\n ): Promise<void> {\n console.log(`Payment intent succeeded: ${paymentIntent.id}`);\n\n if (this.handlers.onPaymentIntentSucceeded) {\n await this.handlers.onPaymentIntentSucceeded(paymentIntent);\n }\n\n // Default behavior: Log successful payment\n\n console.log(\n `Payment of ${paymentIntent.amount} ${paymentIntent.currency} succeeded`\n );\n }\n\n private async handlePaymentIntentFailed(\n paymentIntent: Stripe.PaymentIntent\n ): Promise<void> {\n console.log(`Payment intent failed: ${paymentIntent.id}`);\n\n if (this.handlers.onPaymentIntentPaymentFailed) {\n await this.handlers.onPaymentIntentPaymentFailed(paymentIntent);\n }\n\n // Default behavior: Log failed payment\n\n console.log(\n `Payment of ${paymentIntent.amount} ${paymentIntent.currency} failed`\n );\n }\n}\n\n// Utility function to create a webhook handler with custom handlers\nexport const createStripeWebhookHandler = (\n secretKey: string,\n handlers: WebhookHandlers = {}\n): StripeWebhookHandler => {\n return new StripeWebhookHandler(secretKey, handlers);\n};\n\n// Express.js middleware for handling Stripe webhooks\nexport const createStripeWebhookMiddleware = (\n secretKey: string,\n webhookSecret: string,\n handlers: WebhookHandlers = {}\n) => {\n const webhookHandler = new StripeWebhookHandler(secretKey, handlers);\n\n return async (req: Request, res: Response) => {\n try {\n const signature = req.headers['stripe-signature'];\n\n if (!signature) {\n return res\n .status(400)\n .json({ error: 'Missing stripe-signature header' });\n }\n\n const result = await webhookHandler.handleWebhook(\n req.body,\n Array.isArray(signature) ? signature[0] : signature,\n webhookSecret\n );\n\n if (result.success) {\n res.status(200).json({ received: true });\n } else {\n res.status(400).json({ error: result.error });\n }\n } catch (error) {\n console.error('Webhook middleware error:', error);\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n};\n\n// Next.js API route handler\nexport const createNextJSWebhookHandler = (\n secretKey: string,\n webhookSecret: string,\n handlers: WebhookHandlers = {}\n) => {\n const webhookHandler = new StripeWebhookHandler(secretKey, handlers);\n\n return async (req: NextApiRequest, res: NextApiResponse) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST');\n return res.status(405).json({ error: 'Method not allowed' });\n }\n\n try {\n const signature = req.headers['stripe-signature'];\n\n if (!signature) {\n return res\n .status(400)\n .json({ error: 'Missing stripe-signature header' });\n }\n\n const result = await webhookHandler.handleWebhook(\n req.body,\n Array.isArray(signature) ? signature[0] : signature,\n webhookSecret\n );\n\n if (result.success) {\n res.status(200).json({ received: true });\n } else {\n res.status(400).json({ error: result.error });\n }\n } catch (error) {\n console.error('Webhook handler error:', error);\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n};\n","import Stripe from 'stripe';\r\n\r\nexport interface CreateCheckoutSessionOptions {\r\n priceId: string;\r\n customerId?: string;\r\n successUrl: string;\r\n cancelUrl: string;\r\n mode?: 'payment' | 'subscription' | 'setup';\r\n metadata?: Record<string, string>;\r\n}\r\n\r\nexport interface ProcessPaymentOptions {\r\n amount: number;\r\n currency: string;\r\n paymentMethodId: string;\r\n customerId?: string;\r\n description?: string;\r\n metadata?: Record<string, string>;\r\n}\r\n\r\nexport interface CreateSubscriptionOptions {\r\n customerId: string;\r\n priceId: string;\r\n paymentMethodId?: string;\r\n trialPeriodDays?: number;\r\n metadata?: Record<string, string>;\r\n}\r\n\r\nexport interface UpdateSubscriptionOptions {\r\n subscriptionId: string;\r\n priceId?: string;\r\n quantity?: number;\r\n metadata?: Record<string, string>;\r\n}\r\n\r\n/**\r\n * Create a Stripe checkout session\r\n */\r\nexport const createStripeCheckoutSession = async (\r\n stripe: Stripe,\r\n options: CreateCheckoutSessionOptions\r\n): Promise<Stripe.Checkout.Session> => {\r\n const {\r\n priceId,\r\n customerId,\r\n successUrl,\r\n cancelUrl,\r\n mode = 'subscription',\r\n metadata = {},\r\n } = options;\r\n\r\n const sessionParams: Stripe.Checkout.SessionCreateParams = {\r\n mode,\r\n success_url: successUrl,\r\n cancel_url: cancelUrl,\r\n line_items: [\r\n {\r\n price: priceId,\r\n quantity: 1,\r\n },\r\n ],\r\n metadata,\r\n };\r\n\r\n if (customerId) {\r\n sessionParams.customer = customerId;\r\n } else {\r\n sessionParams.customer_creation = 'always';\r\n }\r\n\r\n if (mode === 'subscription') {\r\n sessionParams.subscription_data = {\r\n metadata,\r\n };\r\n }\r\n\r\n return await stripe.checkout.sessions.create(sessionParams);\r\n};\r\n\r\n/**\r\n * Process a one-time payment\r\n */\r\nexport const processPayment = async (\r\n stripe: Stripe,\r\n options: ProcessPaymentOptions\r\n): Promise<Stripe.PaymentIntent> => {\r\n const {\r\n amount,\r\n currency,\r\n paymentMethodId,\r\n customerId,\r\n description,\r\n metadata = {},\r\n } = options;\r\n\r\n const paymentIntentParams: Stripe.PaymentIntentCreateParams = {\r\n amount,\r\n currency,\r\n payment_method: paymentMethodId,\r\n confirmation_method: 'manual',\r\n confirm: true,\r\n return_url: 'https://your-website.com/return',\r\n metadata,\r\n };\r\n\r\n if (customerId) {\r\n paymentIntentParams.customer = customerId;\r\n }\r\n\r\n if (description) {\r\n paymentIntentParams.description = description;\r\n }\r\n\r\n return await stripe.paymentIntents.create(paymentIntentParams);\r\n};\r\n\r\n/**\r\n * Create a subscription\r\n */\r\nexport const createSubscription = async (\r\n stripe: Stripe,\r\n options: CreateSubscriptionOptions\r\n): Promise<Stripe.Subscription> => {\r\n const {\r\n customerId,\r\n priceId,\r\n paymentMethodId,\r\n trialPeriodDays,\r\n metadata = {},\r\n } = options;\r\n\r\n const subscriptionParams: Stripe.SubscriptionCreateParams = {\r\n customer: customerId,\r\n items: [\r\n {\r\n price: priceId,\r\n },\r\n ],\r\n metadata,\r\n };\r\n\r\n if (paymentMethodId) {\r\n subscriptionParams.default_payment_method = paymentMethodId;\r\n }\r\n\r\n if (trialPeriodDays) {\r\n subscriptionParams.trial_period_days = trialPeriodDays;\r\n }\r\n\r\n return await stripe.subscriptions.create(subscriptionParams);\r\n};\r\n\r\n/**\r\n * Update a subscription\r\n */\r\nexport const updateSubscription = async (\r\n stripe: Stripe,\r\n options: UpdateSubscriptionOptions\r\n): Promise<Stripe.Subscription> => {\r\n const { subscriptionId, priceId, quantity, metadata } = options;\r\n\r\n const subscription = await stripe.subscriptions.retrieve(subscriptionId);\r\n \r\n const updateParams: Stripe.SubscriptionUpdateParams = {};\r\n\r\n if (priceId) {\r\n updateParams.items = [\r\n {\r\n id: subscription.items.data[0].id,\r\n price: priceId,\r\n quantity: quantity || 1,\r\n },\r\n ];\r\n }\r\n\r\n if (metadata) {\r\n updateParams.metadata = metadata;\r\n }\r\n\r\n return await stripe.subscriptions.update(subscriptionId, updateParams);\r\n};\r\n\r\n/**\r\n * Cancel a subscription\r\n */\r\nexport const cancelSubscription = async (\r\n stripe: Stripe,\r\n subscriptionId: string,\r\n cancelAtPeriodEnd: boolean = true\r\n): Promise<Stripe.Subscription> => {\r\n if (cancelAtPeriodEnd) {\r\n return await stripe.subscriptions.update(subscriptionId, {\r\n cancel_at_period_end: true,\r\n });\r\n } else {\r\n return await stripe.subscriptions.cancel(subscriptionId);\r\n }\r\n};\r\n\r\n/**\r\n * Validate Stripe webhook signature\r\n */\r\nexport const validateStripeSignature = (\r\n payload: string | Buffer,\r\n signature: string,\r\n endpointSecret: string\r\n): Stripe.Event => {\r\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {\r\n apiVersion: '2024-06-20',\r\n });\r\n\r\n return stripe.webhooks.constructEvent(payload, signature, endpointSecret);\r\n};\r\n\r\n/**\r\n * Handle common Stripe webhook events\r\n */\r\nexport const handleStripeWebhook = async (\r\n event: Stripe.Event,\r\n handlers: {\r\n onPaymentSucceeded?: (paymentIntent: Stripe.PaymentIntent) => Promise<void>;\r\n onPaymentFailed?: (paymentIntent: Stripe.PaymentIntent) => Promise<void>;\r\n onSubscriptionCreated?: (subscription: Stripe.Subscription) => Promise<void>;\r\n onSubscriptionUpdated?: (subscription: Stripe.Subscription) => Promise<void>;\r\n onSubscriptionDeleted?: (subscription: Stripe.Subscription) => Promise<void>;\r\n onInvoicePaid?: (invoice: Stripe.Invoice) => Promise<void>;\r\n onInvoicePaymentFailed?: (invoice: Stripe.Invoice) => Promise<void>;\r\n }\r\n): Promise<void> => {\r\n switch (event.type) {\r\n case 'payment_intent.succeeded':\r\n if (handlers.onPaymentSucceeded) {\r\n await handlers.onPaymentSucceeded(event.data.object as Stripe.PaymentIntent);\r\n }\r\n break;\r\n\r\n case 'payment_intent.payment_failed':\r\n if (handlers.onPaymentFailed) {\r\n await handlers.onPaymentFailed(event.data.object as Stripe.PaymentIntent);\r\n }\r\n break;\r\n\r\n case 'customer.subscription.created':\r\n if (handlers.onSubscriptionCreated) {\r\n await handlers.onSubscriptionCreated(event.data.object as Stripe.Subscription);\r\n }\r\n break;\r\n\r\n case 'customer.subscription.updated':\r\n if (handlers.onSubscriptionUpdated) {\r\n await handlers.onSubscriptionUpdated(event.data.object as Stripe.Subscription);\r\n }\r\n break;\r\n\r\n case 'customer.subscription.deleted':\r\n if (handlers.onSubscriptionDeleted) {\r\n await handlers.onSubscriptionDeleted(event.data.object as Stripe.Subscription);\r\n }\r\n break;\r\n\r\n case 'invoice.paid':\r\n if (handlers.onInvoicePaid) {\r\n await handlers.onInvoicePaid(event.data.object as Stripe.Invoice);\r\n }\r\n break;\r\n\r\n case 'invoice.payment_failed':\r\n if (handlers.onInvoicePaymentFailed) {\r\n await handlers.onInvoicePaymentFailed(event.data.object as Stripe.Invoice);\r\n }\r\n break;\r\n\r\n default:\r\n console.log(`Unhandled event type: ${event.type}`);\r\n }\r\n};\r\n\r\n"],"mappings":"AAAA,OAAOA,MAAY,SCAZ,IAAMC,EAAqB,aAwD3B,IAAMC,EAAiB,CAC5B,8BAA+B,gCAC/B,8BAA+B,gCAC/B,8BAA+B,gCAC/B,0BAA2B,4BAC3B,uBAAwB,yBACxB,2BAA4B,6BAC5B,yBAA0B,2BAC1B,8BAA+B,+BACjC,ED9DO,IAAMC,EAAN,KAAsB,CACnB,OAER,YACEC,EACAC,EAIA,CACA,KAAK,OAAS,IAAIC,EAAOF,EAAW,CAClC,WACGC,GAAS,YAA0CE,EACtD,WAAY,EACd,CAAC,CACH,CAGA,MAAM,eAAeC,EAKlB,CACD,OAAO,KAAK,OAAO,UAAU,OAAO,CAClC,MAAOA,EAAO,MACd,KAAMA,EAAO,KACb,MAAOA,EAAO,MACd,SAAUA,EAAO,QACnB,CAAC,CACH,CAEA,MAAM,YAAYC,EAAoB,CACpC,OAAO,KAAK,OAAO,UAAU,SAASA,CAAU,CAClD,CAEA,MAAM,eACJA,EACAD,EAMA,CACA,OAAO,KAAK,OAAO,UAAU,OAAOC,EAAYD,CAAM,CACxD,CAEA,MAAM,eAAeC,EAAoB,CACvC,OAAO,KAAK,OAAO,UAAU,IAAIA,CAAU,CAC7C,CAGA,MAAM,mBAAmBD,EAUtB,CACD,OAAO,KAAK,OAAO,cA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WAAY,YACd,CAAC,EAEa,SAAS,eAAe4B,EAASC,EAAWC,CAAc,EAM7DC,EAAsB,MACjCC,EACAC,IASkB,CAClB,OAAQD,EAAM,KAAM,CAClB,IAAK,2BACCC,EAAS,oBACX,MAAMA,EAAS,mBAAmBD,EAAM,KAAK,MAA8B,EAE7E,MAEF,IAAK,gCACCC,EAAS,iBACX,MAAMA,EAAS,gBAAgBD,EAAM,KAAK,MAA8B,EAE1E,MAEF,IAAK,gCACCC,EAAS,uBACX,MAAMA,EAAS,sBAAsBD,EAAM,KAAK,MAA6B,EAE/E,MAEF,IAAK,gCACCC,EAAS,uBACX,MAAMA,EAAS,sBAAsBD,EAAM,KAAK,MAA6B,EAE/E,MAEF,IAAK,gCACCC,EAAS,uBACX,MAAMA,EAAS,sBAAsBD,EAAM,KAAK,MAA6B,EAE/E,MAEF,IAAK,eACCC,EAAS,eACX,MAAMA,EAAS,cAAcD,EAAM,KAAK,MAAwB,EAElE,MAEF,IAAK,yBACCC,EAAS,wBACX,MAAMA,EAAS,uBAAuBD,EAAM,KAAK,MAAwB,EAE3E,MAEF,QACE,QAAQ,IAAI,yBAAyBA,EAAM,IAAI,EAAE,CACrD,CACF","names":["Stripe","STRIPE_API_VERSION","WEBHOOK_EVENTS","StripeServerAPI","secretKey","options","Stripe","STRIPE_API_VERSION","params","customerId","subscriptionId","updateData","currentItem","immediately","sessionParams","paymentIntentId","type","paymentMethodId","limit","invoiceId","payload","signature","webhookSecret","priceId","productId","apiVersion","StripeWebhookHandler","secretKey","handlers","StripeServerAPI","payload","signature","webhookSecret","event","error","errorMessage","WEBHOOK_EVENTS","subscription","invoice","subscriptionId","session","paymentIntent","createStripeWebhookHandler","createStripeWebhookMiddleware","webhookHandler","req","res","result","createNextJSWebhookHandler","Stripe","createStripeCheckoutSession","stripe","options","priceId","customerId","successUrl","cancelUrl","mode","metadata","sessionParams","processPayment","amount","currency","paymentMethodId","description","paymentIntentParams","createSubscription","trialPeriodDays","subscriptionParams","updateSubscription","subscriptionId","quantity","subscription","updateParams","cancelSubscription","cancelAtPeriodEnd","validateStripeSignature","payload","signature","endpointSecret","handleStripeWebhook","event","handlers"]}
|