@stacksjs/payments 0.70.86 → 0.70.88

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/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/payments",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.86",
5
+ "version": "0.70.88",
6
6
  "description": "The Stacks payments package. Currently supporting Stripe.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -67,9 +67,9 @@
67
67
  }
68
68
  },
69
69
  "devDependencies": {
70
- "@stacksjs/config": "0.70.86",
70
+ "@stacksjs/config": "0.70.88",
71
71
  "better-dx": "^0.2.16",
72
- "@stacksjs/utils": "0.70.86",
72
+ "@stacksjs/utils": "0.70.88",
73
73
  "@stripe/stripe-js": "^8.7.0",
74
74
  "stripe": "^21.0.1"
75
75
  }
@@ -1,9 +0,0 @@
1
- import type { UserModel } from '@stacksjs/orm';
2
- import type Stripe from 'stripe';
3
- export declare const manageCharge: ManageCharge;
4
- export declare interface ManageCharge {
5
- createPayment: (user: UserModel, amount: number, options: Stripe.PaymentIntentCreateParams) => Promise<Stripe.Response<Stripe.PaymentIntent>>
6
- findPayment: (id: string) => Promise<Stripe.PaymentIntent | null>
7
- refund: (paymentIntentId: string, options?: Stripe.RefundCreateParams) => Promise<Stripe.Response<Stripe.Refund>>
8
- charge: (user: UserModel, amount: number, paymentMethod: string, options: Stripe.PaymentIntentCreateParams) => Promise<Stripe.Response<Stripe.PaymentIntent>>
9
- }
@@ -1,6 +0,0 @@
1
- import type { UserModel } from '@stacksjs/orm';
2
- import type Stripe from 'stripe';
3
- export declare const manageCheckout: Checkout;
4
- export declare interface Checkout {
5
- create: (user: UserModel, params: Stripe.Checkout.SessionCreateParams) => Promise<Stripe.Response<Stripe.Checkout.Session>>
6
- }
@@ -1,15 +0,0 @@
1
- import type { StripeCustomerOptions } from '@stacksjs/types';
2
- import type { UserModel } from '@stacksjs/orm';
3
- import type Stripe from 'stripe';
4
- export declare const manageCustomer: ManageCustomer;
5
- export declare interface ManageCustomer {
6
- stripeId: (user: UserModel) => string
7
- hasStripeId: (user: UserModel) => boolean
8
- createStripeCustomer: (user: UserModel, options: Stripe.CustomerCreateParams) => Promise<Stripe.Response<Stripe.Customer>>
9
- updateStripeCustomer: (user: UserModel, options: Stripe.CustomerUpdateParams) => Promise<Stripe.Response<Stripe.Customer>>
10
- createOrGetStripeUser: (user: UserModel, options: Stripe.CustomerCreateParams) => Promise<Stripe.Response<Stripe.Customer>>
11
- retrieveStripeUser: (user: UserModel) => Promise<Stripe.Response<Stripe.Customer> | undefined>
12
- createOrUpdateStripeUser: (user: UserModel, options: Stripe.CustomerCreateParams) => Promise<Stripe.Response<Stripe.Customer>>
13
- deleteStripeUser: (user: UserModel) => Promise<Stripe.Response<Stripe.DeletedCustomer>>
14
- syncStripeCustomerDetails: (user: UserModel, options: StripeCustomerOptions) => Promise<Stripe.Response<Stripe.Customer>>
15
- }
@@ -1,13 +0,0 @@
1
- // Core Billable Modules
2
- export * from './charge';
3
- export * from './checkout';
4
- export * from './customer';
5
- export * from './intent';
6
- export * from './invoice';
7
- export * from './payment-method';
8
- export * from './price';
9
- export * from './product';
10
- export * from './setup-products';
11
- export * from './subscription';
12
- export * from './transaction';
13
- export * from './webhook';
@@ -1,6 +0,0 @@
1
- import type { UserModel } from '@stacksjs/orm';
2
- import type Stripe from 'stripe';
3
- export declare const manageSetupIntent: SetupIntent;
4
- export declare interface SetupIntent {
5
- create: (user: UserModel, params: Stripe.SetupIntentCreateParams) => Promise<Stripe.Response<Stripe.SetupIntent>>
6
- }
@@ -1,6 +0,0 @@
1
- import type { UserModel } from '@stacksjs/orm';
2
- import type Stripe from 'stripe';
3
- export declare const manageInvoice: ManageInvoice;
4
- export declare interface ManageInvoice {
5
- list: (user: UserModel) => Promise<Stripe.Response<Stripe.ApiList<Stripe.Invoice>>>
6
- }
@@ -1,18 +0,0 @@
1
- import { PaymentMethod } from '@stacksjs/orm';
2
- import type { ModelRow, UserModel } from '@stacksjs/orm';
3
- import type { Selectable } from '@stacksjs/database';
4
- import type Stripe from 'stripe';
5
- export declare const managePaymentMethod: ManagePaymentMethod;
6
- export declare interface ManagePaymentMethod {
7
- addPaymentMethod: (user: UserModel, paymentMethod: string | Stripe.PaymentMethod) => Promise<Stripe.Response<Stripe.PaymentMethod>>
8
- updatePaymentMethod: (user: UserModel, paymentMethodId: string, updateParams?: Stripe.PaymentMethodUpdateParams) => Promise<Stripe.Response<Stripe.PaymentMethod>>
9
- setUserDefaultPayment: (user: UserModel, paymentMethodId: string) => Promise<Stripe.Response<Stripe.Customer>>
10
- setDefaultPaymentMethod: (user: UserModel, paymentMethodId: number) => Promise<Stripe.Response<Stripe.Customer>>
11
- storePaymentMethod: (user: UserModel, paymentMethodId: Stripe.PaymentMethod) => Promise<PaymentMethodInstance>
12
- deletePaymentMethod: (user: UserModel, paymentMethodId: string | number) => Promise<Stripe.Response<Stripe.PaymentMethod>>
13
- retrievePaymentMethod: (user: UserModel, paymentMethodId: number) => Promise<PaymentMethodInstance | undefined>
14
- retrieveDefaultPaymentMethod: (user: UserModel) => Promise<PaymentMethodInstance | undefined>
15
- listPaymentMethods: (user: UserModel, cardType?: string) => Promise<Selectable<PaymentMethodsTable>[]>
16
- }
17
- declare type PaymentMethodInstance = NonNullable<Awaited<ReturnType<typeof PaymentMethod.find>>>;
18
- declare type PaymentMethodsTable = ModelRow<typeof PaymentMethod>;
@@ -1,6 +0,0 @@
1
- import type Stripe from 'stripe';
2
- export declare const managePrice: PriceManager;
3
- export declare interface PriceManager {
4
- retrieveByLookupKey: (lookupKey: string) => Promise<Stripe.Price | undefined>
5
- createOrGet: (lookupKey: string, params: Stripe.PriceCreateParams) => Promise<Stripe.Price>
6
- }
@@ -1,37 +0,0 @@
1
- import type Stripe from 'stripe';
2
- export declare const manageProduct: ProductManager;
3
- export declare const managePriceExtended: ExtendedPriceManager;
4
- export declare const manageCoupon: CouponManager;
5
- export declare interface ProductManager {
6
- create: (params: Stripe.ProductCreateParams) => Promise<Stripe.Response<Stripe.Product>>
7
- retrieve: (productId: string) => Promise<Stripe.Response<Stripe.Product>>
8
- update: (productId: string, params: Stripe.ProductUpdateParams) => Promise<Stripe.Response<Stripe.Product>>
9
- list: (params?: Stripe.ProductListParams) => Promise<Stripe.Response<Stripe.ApiList<Stripe.Product>>>
10
- archive: (productId: string) => Promise<Stripe.Response<Stripe.Product>>
11
- createWithPrice: (product: Stripe.ProductCreateParams, price: Omit<Stripe.PriceCreateParams, 'product'>) => Promise<{ product: Stripe.Product, price: Stripe.Price }>
12
- search: (query: string, params?: Stripe.ProductSearchParams) => Promise<Stripe.Response<Stripe.ApiSearchResult<Stripe.Product>>>
13
- }
14
- // =============================================================================
15
- // Extended Price Management
16
- // =============================================================================
17
- export declare interface ExtendedPriceManager {
18
- create: (params: Stripe.PriceCreateParams) => Promise<Stripe.Response<Stripe.Price>>
19
- retrieve: (priceId: string) => Promise<Stripe.Response<Stripe.Price>>
20
- update: (priceId: string, params: Stripe.PriceUpdateParams) => Promise<Stripe.Response<Stripe.Price>>
21
- list: (params?: Stripe.PriceListParams) => Promise<Stripe.Response<Stripe.ApiList<Stripe.Price>>>
22
- listByProduct: (productId: string, params?: Stripe.PriceListParams) => Promise<Stripe.Response<Stripe.ApiList<Stripe.Price>>>
23
- search: (query: string, params?: Stripe.PriceSearchParams) => Promise<Stripe.Response<Stripe.ApiSearchResult<Stripe.Price>>>
24
- archive: (priceId: string) => Promise<Stripe.Response<Stripe.Price>>
25
- }
26
- // =============================================================================
27
- // Coupon and Promotion Code Management
28
- // =============================================================================
29
- export declare interface CouponManager {
30
- create: (params: Stripe.CouponCreateParams) => Promise<Stripe.Response<Stripe.Coupon>>
31
- retrieve: (couponId: string) => Promise<Stripe.Response<Stripe.Coupon>>
32
- update: (couponId: string, params: Stripe.CouponUpdateParams) => Promise<Stripe.Response<Stripe.Coupon>>
33
- delete: (couponId: string) => Promise<Stripe.Response<Stripe.DeletedCoupon>>
34
- list: (params?: Stripe.CouponListParams) => Promise<Stripe.Response<Stripe.ApiList<Stripe.Coupon>>>
35
- createPromotionCode: (params: Stripe.PromotionCodeCreateParams) => Promise<Stripe.Response<Stripe.PromotionCode>>
36
- retrievePromotionCode: (code: string) => Promise<Stripe.PromotionCode | null>
37
- }
@@ -1,2 +0,0 @@
1
- import type { Result } from '@stacksjs/error-handling';
2
- export declare function createStripeProduct(): Promise<Result<string, Error>>;
@@ -1,12 +0,0 @@
1
- import type { UserModel } from '@stacksjs/orm';
2
- import type Stripe from 'stripe';
3
- export declare const manageSubscription: SubscriptionManager;
4
- export declare interface SubscriptionManager {
5
- create: (user: UserModel, type: string, lookupKey: string, params: Partial<Stripe.SubscriptionCreateParams>) => Promise<Stripe.Response<Stripe.Subscription>>
6
- update: (user: UserModel, type: string, lookupKey: string, params: Partial<Stripe.SubscriptionUpdateParams>) => Promise<Stripe.Response<Stripe.Subscription>>
7
- cancel: (subscriptionId: string, params?: Partial<Stripe.SubscriptionCreateParams>) => Promise<Stripe.Response<Stripe.Subscription>>
8
- retrieve: (user: UserModel, subscriptionId: string) => Promise<Stripe.Response<Stripe.Subscription>>
9
- isValid: (user: UserModel, type: string) => Promise<boolean>
10
- isIncomplete: (user: UserModel, type: string) => Promise<boolean>
11
- }
12
- declare type SubscriptionsTable = Record<string, unknown>;
@@ -1,14 +0,0 @@
1
- import { PaymentTransaction } from '@stacksjs/orm';
2
- import type { ModelRow, UserModel } from '@stacksjs/orm';
3
- export declare const manageTransaction: ManageTransaction;
4
- export declare interface StoreTransactionOptions {
5
- brand: string
6
- provider_id: string
7
- description?: string
8
- type?: string
9
- }
10
- export declare interface ManageTransaction {
11
- store: (user: UserModel, productId: number, options: StoreTransactionOptions) => Promise<PaymentTransactionsTable | undefined>
12
- list: (user: UserModel) => Promise<PaymentTransactionsTable[]>
13
- }
14
- declare type PaymentTransactionsTable = ModelRow<typeof PaymentTransaction>;
@@ -1,155 +0,0 @@
1
- import type Stripe from 'stripe';
2
- /**
3
- * Register a webhook event handler
4
- */
5
- export declare function onWebhookEvent(eventType: WebhookEventType, handler: WebhookHandler): void;
6
- /**
7
- * Register multiple webhook handlers at once
8
- */
9
- export declare function registerWebhookHandlers(handlerMap: Record<WebhookEventType, WebhookHandler>): void;
10
- /**
11
- * Construct and verify a webhook event from the raw request.
12
- *
13
- * `tolerance` (in seconds) controls how much clock skew between Stripe and
14
- * this server is acceptable before signatures are rejected. Stripe's SDK
15
- * default is 300s; tightening this is recommended in production but the
16
- * previous code dropped the value entirely, so a configured tolerance was
17
- * silently ignored.
18
- */
19
- export declare function constructEvent(payload: string | Buffer, signature: string, secret: string, tolerance?: number): Stripe.Event;
20
- /**
21
- * Async variant of {@link constructEvent}. Some runtimes (notably Bun) resolve
22
- * the Stripe SDK's crypto provider to WebCrypto's `SubtleCrypto`, which is
23
- * async-only — the synchronous `constructEvent` then throws
24
- * "SubtleCryptoProvider cannot be used in a synchronous context". Verifying via
25
- * `constructEventAsync` works across Node and Bun, so webhook processing uses
26
- * this path.
27
- */
28
- export declare function constructEventAsync(payload: string | Buffer, signature: string, secret: string, tolerance?: number): Promise<Stripe.Event>;
29
- /**
30
- * Handle an incoming webhook event
31
- */
32
- export declare function handleWebhookEvent(event: Stripe.Event): Promise<{ handled: boolean, eventType: string, errors?: string[] }>;
33
- /**
34
- * Process a webhook request
35
- */
36
- export declare function processWebhook(payload: string | Buffer, signature: string, config: WebhookConfig): Promise<{ success: boolean, eventType?: string, error?: string }>;
37
- /**
38
- * Register payment intent handlers
39
- */
40
- export declare function onPaymentIntent(handlers: {
41
- succeeded?: WebhookHandler
42
- failed?: WebhookHandler
43
- created?: WebhookHandler
44
- canceled?: WebhookHandler
45
- }): void;
46
- /**
47
- * Register subscription handlers
48
- */
49
- export declare function onSubscription(handlers: {
50
- created?: WebhookHandler
51
- updated?: WebhookHandler
52
- deleted?: WebhookHandler
53
- trialWillEnd?: WebhookHandler
54
- }): void;
55
- /**
56
- * Register invoice handlers
57
- */
58
- export declare function onInvoice(handlers: {
59
- paid?: WebhookHandler
60
- paymentFailed?: WebhookHandler
61
- created?: WebhookHandler
62
- finalized?: WebhookHandler
63
- }): void;
64
- /**
65
- * Register checkout session handlers
66
- */
67
- export declare function onCheckout(handlers: {
68
- completed?: WebhookHandler
69
- expired?: WebhookHandler
70
- }): void;
71
- /**
72
- * Register charge handlers
73
- */
74
- export declare function onCharge(handlers: {
75
- succeeded?: WebhookHandler
76
- failed?: WebhookHandler
77
- refunded?: WebhookHandler
78
- disputed?: WebhookHandler
79
- }): void;
80
- /**
81
- * Extract payment intent from event
82
- */
83
- export declare function getPaymentIntent(event: Stripe.Event): Stripe.PaymentIntent | null;
84
- /**
85
- * Extract subscription from event
86
- */
87
- export declare function getSubscription(event: Stripe.Event): Stripe.Subscription | null;
88
- /**
89
- * Extract invoice from event
90
- */
91
- export declare function getInvoice(event: Stripe.Event): Stripe.Invoice | null;
92
- /**
93
- * Extract checkout session from event
94
- */
95
- export declare function getCheckoutSession(event: Stripe.Event): Stripe.Checkout.Session | null;
96
- /**
97
- * Extract charge from event
98
- */
99
- export declare function getCharge(event: Stripe.Event): Stripe.Charge | null;
100
- /**
101
- * Extract customer from event
102
- */
103
- export declare function getCustomer(event: Stripe.Event): Stripe.Customer | null;
104
- declare const handlers: Map<WebhookEventType, WebhookHandler[]>;
105
- export declare const manageWebhook: {
106
- onWebhookEvent: typeof onWebhookEvent;
107
- registerWebhookHandlers: typeof registerWebhookHandlers;
108
- constructEvent: typeof constructEvent;
109
- constructEventAsync: typeof constructEventAsync;
110
- handleWebhookEvent: typeof handleWebhookEvent;
111
- processWebhook: typeof processWebhook;
112
- onPaymentIntent: typeof onPaymentIntent;
113
- onSubscription: typeof onSubscription;
114
- onInvoice: typeof onInvoice;
115
- onCheckout: typeof onCheckout;
116
- onCharge: typeof onCharge;
117
- getPaymentIntent: typeof getPaymentIntent;
118
- getSubscription: typeof getSubscription;
119
- getInvoice: typeof getInvoice;
120
- getCheckoutSession: typeof getCheckoutSession;
121
- getCharge: typeof getCharge;
122
- getCustomer: typeof getCustomer
123
- };
124
- export declare interface WebhookConfig {
125
- secret: string
126
- tolerance?: number
127
- }
128
- export type WebhookEventType = | 'payment_intent.succeeded'
129
- | 'payment_intent.payment_failed'
130
- | 'payment_intent.created'
131
- | 'payment_intent.canceled'
132
- | 'customer.subscription.created'
133
- | 'customer.subscription.updated'
134
- | 'customer.subscription.deleted'
135
- | 'customer.subscription.trial_will_end'
136
- | 'customer.created'
137
- | 'customer.updated'
138
- | 'customer.deleted'
139
- | 'invoice.paid'
140
- | 'invoice.payment_failed'
141
- | 'invoice.finalized'
142
- | 'invoice.created'
143
- | 'checkout.session.completed'
144
- | 'checkout.session.expired'
145
- | 'charge.succeeded'
146
- | 'charge.failed'
147
- | 'charge.refunded'
148
- | 'charge.dispute.created'
149
- | 'charge.dispute.closed'
150
- | 'payment_method.attached'
151
- | 'payment_method.detached'
152
- | 'setup_intent.succeeded'
153
- | 'setup_intent.setup_failed'
154
- | string;
155
- export type WebhookHandler = (_event: Stripe.Event) => Promise<void> | void;
@@ -1,8 +0,0 @@
1
- import type Stripe from 'stripe';
2
- /**
3
- * Lazy-initialized Stripe instance.
4
- * Only throws when you actually try to use Stripe, not at module load time.
5
- * This allows the payments package to be imported without a configured key
6
- * (e.g., in tests, CLI, or environments that don't use Stripe).
7
- */
8
- export declare const stripe: Stripe;
@@ -1,26 +0,0 @@
1
- /**
2
- * Build a deterministic Stripe idempotency key for an operation.
3
- * The `scope` should be a stable string identifying the call site
4
- * (e.g. `'customer.create'`, `'subscription.create'`); `parts` are
5
- * any extra identifying values (user id, lookup key, etc.) that
6
- * uniquely scope the operation within that user's lifetime.
7
- *
8
- * @param scope - stable operation name; never user input
9
- * @param parts - identifying values appended after scope (coerced
10
- * to string; nullish values are skipped)
11
- */
12
- export declare function stacksIdempotencyKey(scope: string, ...parts: Array<string | number | null | undefined>): string;
13
- /**
14
- * Build a one-shot idempotency key for operations that are NOT
15
- * naturally retryable (a unique-per-attempt key that won't collide
16
- * with anything). Used when the caller WANTS a fresh Stripe object
17
- * each time but still wants the safety of a single network retry
18
- * within a single attempt. The key includes a random suffix so
19
- * sequential attempts produce different keys.
20
- *
21
- * Used for payment intents, checkout sessions — operations where
22
- * "create another one" is the right semantic on a retry by the
23
- * caller, but where a single network blip during a single attempt
24
- * still benefits from in-flight idempotency.
25
- */
26
- export declare function freshIdempotencyKey(scope: string, ...parts: Array<string | number | null | undefined>): string;
package/dist/index.d.ts DELETED
@@ -1,16 +0,0 @@
1
- export type * as Stripe from 'stripe';
2
- /**
3
- * Payments Package
4
- *
5
- * Provides payment processing capabilities with Stripe integration.
6
- */
7
- // Main Payment facade
8
- export * from './payment';
9
- export { default as Payment } from './payment';
10
- // Billable modules
11
- export * from './billable/index';
12
- // Stripe driver and SDK
13
- export * from './drivers/stripe';
14
- // Idempotency-key helpers — passed to every Stripe create/update so
15
- // retries don't produce duplicate objects (stacksjs/stacks#1876 X-1).
16
- export { freshIdempotencyKey, stacksIdempotencyKey } from './idempotency';
package/dist/index.js DELETED
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{createRequire as t}from"module";import{services as u}from"@stacksjs/config";var e=t(import.meta.url);function TT(){try{return e("stripe")}catch{throw Error("Stripe payments are being used but the `stripe` package is not installed. "+"It is an opt-in dependency \u2014 run `bun add stripe` to enable server-side Stripe payments.")}}var b=null,_=new Proxy({},{get(T,x){if(!b){let w=u?.stripe?.secretKey;if(!w)throw Error("Stripe secret key is not configured. Set STRIPE_SECRET_KEY in your .env file.");let $="2026-03-25.dahlia",z=u?.stripe?.apiVersion;if(z&&z!==$)throw Error(`Stripe API version ${z} does not match the installed SDK version ${$}`);b=new(TT())(w,{apiVersion:$})}return b[x]}});import{config as wT}from"@stacksjs/config";import{log as _T}from"@stacksjs/logging";import{createHash as d}from"crypto";var I="stacks",y="v1",xT=255;function D(T,...x){let w=x.filter((Q)=>Q!==null&&Q!==void 0&&Q!=="").map((Q)=>String(Q)).join(":"),$=w?`${I}:${T}:${w}:${y}`:`${I}:${T}:${y}`;if($.length<=xT)return $;let z=d("sha256").update(w).digest("hex").slice(0,32);return`${I}:${T}:${z}:${y}`}function W(T,...x){let w=d("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,16);return D(T,...x,w)}function i(){let T=wT||{};return(T.payment?.currency||T.billing?.currency||process.env.STRIPE_CURRENCY||"usd").toLowerCase()}var C=(()=>{async function T(z,Q,X){let B={currency:i(),amount:Q};if(z.hasStripeId())B.customer=z.stripe_id??void 0;let H={...B,...X};return await _.paymentIntents.create(H,{idempotencyKey:W("payment_intent.create",z.id,Q)})}async function x(z){try{return await _.paymentIntents.retrieve(z)}catch(Q){return _T.error(Q),null}}async function w(z,Q={}){if(!z||typeof z!=="string")throw Error("[payments/refund] paymentIntentId is required");if(Q.amount!=null){if(typeof Q.amount!=="number"||!Number.isFinite(Q.amount)||Q.amount<=0)throw Error("[payments/refund] amount must be a positive finite number");try{let J=await _.paymentIntents.retrieve(z),L=J.amount_received??J.amount;if(L&&Q.amount>L)throw Error(`[payments/refund] amount ${Q.amount} exceeds captured amount ${L}`)}catch(J){if(J instanceof Error&&J.message.startsWith("[payments/refund]"))throw J}}let{idempotencyKey:X,...B}=Q,H={payment_intent:z,...B},N={idempotencyKey:X||`refund:${z}:${B.amount??"full"}`};return await _.refunds.create(H,N)}async function $(z,Q,X,B){let N={...{confirmation_method:"automatic",confirm:!0,payment_method:X,currency:i(),amount:Q},...B};return await T(z,Q,N)}return{createPayment:T,charge:$,findPayment:x,refund:w}})();import{config as FT}from"@stacksjs/config";function a(T,x){if(!T)return;let w;try{w=new URL(T)}catch{throw Error(`[payments/checkout] ${x} is not a valid URL: ${T}`)}let $=FT?.app?.url;if(!$)return;let z;try{z=new URL($.startsWith("http")?$:`https://${$}`).origin}catch{return}if(w.origin!==z)throw Error(`[payments/checkout] ${x} origin (${w.origin}) does not match app origin (${z})`)}var l=(()=>{async function T(x,w){let $=w.customer||x.stripe_id;if(!$)throw Error("User has no Stripe customer");a(w.success_url,"success_url"),a(w.cancel_url,"cancel_url");let Q={...{customer:$,mode:"payment",success_url:w.success_url,cancel_url:w.cancel_url},...w};return await _.checkout.sessions.create(Q,{idempotencyKey:W("checkout.session.create",x.id)})}return{create:T}})();var O=(()=>{function T(F){return F.stripe_id||""}function x(F){return{line1:F.address?.line1,city:F.address?.city,state:F.address?.state,postal_code:F.address?.postal_code,country:F.address?.country}}function w(){return[]}function $(F){return F}function z(F){return Boolean(F.stripe_id)}async function Q(F,Z={}){if(z(F))throw Error("Customer already created");if(!Z.name&&G(F))Z.name=G(F);if(!Z.email&&R(F))Z.email=R(F);let A=await _.customers.create(Z,{idempotencyKey:D("customer.create",F.id)});return await F.update({stripe_id:A.id}),A}async function X(F,Z={}){if(!F.stripe_id)throw Error("User does not have a Stripe customer ID. Create a customer first.");return await _.customers.update(F.stripe_id,Z,{idempotencyKey:D("customer.update",F.id,F.stripe_id)})}async function B(F){if(!z(F))throw Error("User does not have a Stripe ID");try{if(!F.stripe_id)throw Error("User has no Stripe ID");let Z=await _.customers.del(F.stripe_id);return await F.update({stripe_id:""}),Z}catch(Z){if(Z.statusCode===404)throw Error("Customer not found in Stripe");throw Z}}async function H(F,Z={}){if(!z(F))return await Q(F,Z);try{let A=await _.customers.retrieve(F.stripe_id);if(A.deleted)throw Error("Customer was deleted");return A}catch(A){if(A.statusCode===404)return await Q(F,Z);throw A}}async function N(F){if(!z(F))return;try{let Z=await _.customers.retrieve(F.stripe_id);if(Z.deleted)throw Error("Customer was deleted in Stripe");return Z}catch(Z){if(Z.statusCode===404)throw Error("Customer not found in Stripe");throw Z}}async function J(F,Z){if(!z(F))return await Q(F,Z);try{if((await _.customers.retrieve(F.stripe_id)).deleted)return await Q(F,Z);return await X(F,Z)}catch(A){if(A.statusCode===404)return await Q(F,Z);throw A}}async function L(F,Z){return await X(F,{name:G(F),email:R(F),address:x(Z),preferred_locales:w(),metadata:Z.metadata?$(Z.metadata):{}})}function G(F){return F.name||""}function R(F){return F.email||""}return{stripeId:T,hasStripeId:z,createStripeCustomer:Q,updateStripeCustomer:X,createOrGetStripeUser:H,createOrUpdateStripeUser:J,deleteStripeUser:B,retrieveStripeUser:N,syncStripeCustomerDetails:L}})();var p=(()=>{async function T(x){if(!x.hasStripeId())throw Error("Customer does not exist in Stripe");if(!x.stripe_id)throw Error("User has no Stripe ID");return await _.invoices.list({customer:x.stripe_id,expand:["data.payment_intent.payment_method"]})}return{list:T}})();import{db as V}from"@stacksjs/database";import{PaymentMethod as h}from"@stacksjs/orm";var k=(()=>{async function T(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G;if(typeof L==="string")G=await _.paymentMethods.retrieve(L);else G=L;if(G.customer!==J.stripe_id)G=await _.paymentMethods.attach(G.id,{customer:J.stripe_id});return await $(J,G),G}async function x(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G=await _.paymentMethods.retrieve(L),R=await V.selectFrom("payment_methods").where("provider_id","=",L).selectAll().executeTakeFirst();if(!J.stripe_id)throw Error("User has no Stripe ID");if(G.customer!==J.stripe_id)await _.paymentMethods.attach(G.id,{customer:J.stripe_id});let F=await _.customers.update(J.stripe_id,{invoice_settings:{default_payment_method:L}});if(await V.updateTable("payment_methods").set({is_default:!1}).where("user_id","=",J.id).executeTakeFirst(),R)await z(R);return F}async function w(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G=await V.selectFrom("payment_methods").where("id","=",L).selectAll().executeTakeFirst();if(!G?.provider_id)throw Error(`Payment method with id ${L} not found`);let R=await _.paymentMethods.retrieve(String(G.provider_id));if(R.customer!==J.stripe_id)await _.paymentMethods.attach(R.id,{customer:J.stripe_id});if(!J.stripe_id)throw Error("User has no Stripe ID");let F=await _.customers.update(J.stripe_id,{invoice_settings:{default_payment_method:String(G.provider_id)}});return await V.updateTable("payment_methods").set({is_default:!1}).where("user_id","=",J.id).executeTakeFirst(),await V.updateTable("payment_methods").set({is_default:!0}).where("id","=",L).executeTakeFirst(),F}async function $(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");if(!L.card?.brand||!L.card?.exp_year||!L.card?.exp_month)throw Error("Invalid payment method: missing required card details");let G={type:"card",last_four:String(L.card.last4),brand:L.card.brand,exp_year:L.card.exp_year,exp_month:L.card.exp_month,user_id:J.id,provider_id:L.id};if(L.customer!==J.stripe_id)await _.paymentMethods.attach(L.id,{customer:J.stripe_id});return await h.create(G)}async function z(J){return await J.update({is_default:!0})}async function Q(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G=typeof L==="string"?await V.selectFrom("payment_methods").where("provider_id","=",L).selectAll().executeTakeFirst():await h.find(L);if(!G?.provider_id)throw Error(`Payment method with id ${L} not found`);if((await _.paymentMethods.retrieve(String(G.provider_id))).customer!==J.stripe_id)throw Error("Payment method does not belong to this customer");return await G.delete(),await _.paymentMethods.detach(String(G.provider_id))}async function X(J,L,G){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");if((await _.paymentMethods.retrieve(L)).customer!==J.stripe_id)throw Error("Payment method does not belong to this customer");return await _.paymentMethods.update(L,G)}async function B(J){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");return await V.selectFrom("payment_methods").selectAll().where("user_id","=",J.id).execute()}async function H(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");return await V.selectFrom("payment_methods").where("id","=",L).selectAll().executeTakeFirst()}async function N(J){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");return await h.where("user_id",J.id).where("is_default",!0).first()}return{addPaymentMethod:T,deletePaymentMethod:Q,retrieveDefaultPaymentMethod:N,updatePaymentMethod:X,listPaymentMethods:B,setDefaultPaymentMethod:w,storePaymentMethod:$,retrievePaymentMethod:H,setUserDefaultPayment:x}})();var E=(()=>{async function T(w){let $=await _.prices.list({lookup_keys:[w]});if(!$.data.length)return;return $.data[0]}async function x(w,$){let z=await T(w);if(z)return z;return await _.prices.create({...$,lookup_key:w})}return{retrieveByLookupKey:T,createOrGet:x}})();var c=(()=>{async function T(B){return await _.products.create(B)}async function x(B){return await _.products.retrieve(B)}async function w(B,H){return await _.products.update(B,H)}async function $(B={}){return await _.products.list({active:!0,...B})}async function z(B){return await _.products.update(B,{active:!1})}async function Q(B,H){let N=await _.products.create(B),J=await _.prices.create({...H,product:N.id});return{product:N,price:J}}async function X(B,H={query:""}){return await _.products.search({...H,query:B})}return{create:T,retrieve:x,update:w,list:$,archive:z,createWithPrice:Q,search:X}})(),$T=(()=>{async function T(B){return await _.prices.create(B)}async function x(B){return await _.prices.retrieve(B)}async function w(B,H){return await _.prices.update(B,H)}async function $(B={}){return await _.prices.list({active:!0,...B})}async function z(B,H={}){return await _.prices.list({product:B,active:!0,...H})}async function Q(B,H={query:""}){return await _.prices.search({...H,query:B})}async function X(B){return await _.prices.update(B,{active:!1})}return{create:T,retrieve:x,update:w,list:$,listByProduct:z,search:Q,archive:X}})(),M=(()=>{async function T(B){return await _.coupons.create(B)}async function x(B){return await _.coupons.retrieve(B)}async function w(B,H){return await _.coupons.update(B,H)}async function $(B){return await _.coupons.del(B)}async function z(B={}){return await _.coupons.list(B)}async function Q(B){return await _.promotionCodes.create(B)}async function X(B){try{let H=await _.promotionCodes.list({code:B,active:!0});if(H.data.length>0)return H.data[0]??null;return null}catch{return null}}return{create:T,retrieve:x,update:w,delete:$,list:z,createPromotionCode:Q,retrievePromotionCode:X}})();import{db as f}from"@stacksjs/database";import{HttpError as zT}from"@stacksjs/error-handling";import{isUniqueViolation as BT}from"@stacksjs/orm";var P=(()=>{async function T(G,R,F,Z){let A=await E.retrieveByLookupKey(F);if(!A)throw Error("Price does not exist in Stripe");let U=[{price:A.id,quantity:1}],j={...{customer:await O.createOrGetStripeUser(G,{}).then((g)=>{if(!g||!g.id)throw Error("Customer does not exist in Stripe");return g.id}),payment_behavior:"allow_incomplete",expand:["latest_invoice.payment_intent"],items:U},...Z},K=await _.subscriptions.create(j,{idempotencyKey:D("subscription.create",G.id,R,F)});return await N(G,R,F,K),K}async function x(G,R,F,Z={}){let A=await E.retrieveByLookupKey(F),U=await G?.activeSubscription();if(!A)throw Error("New price does not exist in Stripe");if(!U)throw Error("No active subscription for user!");let q=U.subscription?.provider_id;if(!q)throw Error("Active subscription has no provider ID");let S=await _.subscriptions.retrieve(q);if(!S)throw Error("Subscription does not exist in Stripe");let j=S.items.data[0]?.id;if(!j)throw Error("No subscription items found in the subscription");await _.subscriptions.update(q,{items:[{id:j,price:A.id,quantity:1}],proration_behavior:"create_prorations"},{idempotencyKey:D("subscription.update",q,A.id)});let K=await _.subscriptions.retrieve(q);if(!U.subscription?.id)throw Error("Active subscription has no database ID");return await J(U.subscription.id,R,K),K}async function w(G,R){if(!await _.subscriptions.retrieve(G))throw Error("Subscription does not exist or does not belong to the user");let Z=await _.subscriptions.cancel(G,R,{idempotencyKey:D("subscription.cancel",G)});return await z(G),Z}async function $(G,R){if(!G.hasStripeId())throw Error("Customer does not exist in Stripe");return await _.subscriptions.retrieve(R)}async function z(G){await f.updateTable("subscriptions").set({provider_status:"canceled"}).where("provider_id","=",G).executeTakeFirst()}function Q(G){return G.provider_status==="active"}function X(G){return G.provider_status==="trialing"}async function B(G,R){let F=await f.selectFrom("subscriptions").where("user_id","=",G.id).where("type","=",R).selectAll().executeTakeFirst();if(!F)return!1;return F.provider_status==="incomplete"}async function H(G,R){let F=await f.selectFrom("subscriptions").where("user_id","=",G.id).where("type","=",R).selectAll().executeTakeFirst();if(!F)return!1;let Z=await Q(F),A=await X(F);return Z||A}async function N(G,R,F,Z){let A=Z.items.data[0];if(!A)throw Error("Stripe subscription contains no line items \u2014 cannot store subscription");let U=L({user_id:G.id,type:R,unit_price:Number(A.price.unit_amount),provider_id:Z.id,provider_status:Z.status,provider_price_id:A.price.id,quantity:A.quantity,trial_ends_at:Z.trial_end!=null?String(Z.trial_end):void 0,ends_at:Z.current_period_end!=null?String(Z.current_period_end):void 0,provider_type:"stripe",last_used_at:Z.current_period_end!=null?String(Z.current_period_end):void 0}),q;try{q=await f.insertInto("subscriptions").values(U).executeTakeFirst()}catch(j){if(BT(j))throw new zT(409,"A subscription with this provider ID already exists");throw j}if(!q)throw Error("Failed to insert subscription record");return await f.selectFrom("subscriptions").where("id","=",Number(q.insertId)).selectAll().executeTakeFirst()}async function J(G,R,F){let Z=await f.selectFrom("subscriptions").where("id","=",G).selectAll().executeTakeFirst(),A=F.items.data[0];if(!A)throw Error("Stripe subscription contains no line items \u2014 cannot update subscription");return await f?.updateTable("subscriptions").set({type:R,provider_price_id:A.price.id,unit_price:Number(A.price.unit_amount)}).where("id","=",G).executeTakeFirst(),Z}function L(G){return Object.fromEntries(Object.entries(G).filter(([R,F])=>F!=null))}return{create:T,update:x,isValid:H,isIncomplete:B,cancel:w,retrieve:$}})();var n=(()=>{async function T(x,w){let Q={...{customer:await O.createOrGetStripeUser(x,{}).then((X)=>{if(!X||!X.id)throw Error("Customer does not exist in Stripe");return X.id}),payment_method_types:["card"]},...w};return await _.setupIntents.create(Q,{idempotencyKey:W("setup_intent.create",x.id)})}return{create:T}})();var m=new Map;function Y(T,x){let w=m.get(T)||[];w.push(x),m.set(T,w)}function GT(T){for(let[x,w]of Object.entries(T))Y(x,w)}function JT(T,x,w,$){if($!=null&&Number.isFinite($)&&$>0)return _.webhooks.constructEvent(T,x,w,$);return _.webhooks.constructEvent(T,x,w)}async function o(T,x,w,$){if($!=null&&Number.isFinite($)&&$>0)return await _.webhooks.constructEventAsync(T,x,w,$);return await _.webhooks.constructEventAsync(T,x,w)}async function r(T){let x=m.get(T.type)||[];if(x.length===0)return{handled:!1,eventType:T.type};let w=[];for(let $ of x)try{await $(T)}catch(z){w.push(z instanceof Error?z.message:String(z))}return{handled:!0,eventType:T.type,...w.length>0?{errors:w}:{}}}async function QT(T,x,w){try{let $=await o(T,x,w.secret,w.tolerance),z=await r($);if(z.errors&&z.errors.length>0)return{success:!1,eventType:z.eventType,error:z.errors.join("; ")};return{success:!0,eventType:z.eventType}}catch($){return{success:!1,error:$ instanceof Error?$.message:"Unknown error"}}}function ZT(T){if(T.succeeded)Y("payment_intent.succeeded",T.succeeded);if(T.failed)Y("payment_intent.payment_failed",T.failed);if(T.created)Y("payment_intent.created",T.created);if(T.canceled)Y("payment_intent.canceled",T.canceled)}function LT(T){if(T.created)Y("customer.subscription.created",T.created);if(T.updated)Y("customer.subscription.updated",T.updated);if(T.deleted)Y("customer.subscription.deleted",T.deleted);if(T.trialWillEnd)Y("customer.subscription.trial_will_end",T.trialWillEnd)}function AT(T){if(T.paid)Y("invoice.paid",T.paid);if(T.paymentFailed)Y("invoice.payment_failed",T.paymentFailed);if(T.created)Y("invoice.created",T.created);if(T.finalized)Y("invoice.finalized",T.finalized)}function RT(T){if(T.completed)Y("checkout.session.completed",T.completed);if(T.expired)Y("checkout.session.expired",T.expired)}function HT(T){if(T.succeeded)Y("charge.succeeded",T.succeeded);if(T.failed)Y("charge.failed",T.failed);if(T.refunded)Y("charge.refunded",T.refunded);if(T.disputed)Y("charge.dispute.created",T.disputed)}function XT(T){if(T.type.startsWith("payment_intent."))return T.data.object;return null}function YT(T){if(T.type.startsWith("customer.subscription."))return T.data.object;return null}function NT(T){if(T.type.startsWith("invoice."))return T.data.object;return null}function qT(T){if(T.type.startsWith("checkout.session."))return T.data.object;return null}function UT(T){if(T.type.startsWith("charge."))return T.data.object;return null}function DT(T){if(T.type.startsWith("customer.")&&!T.type.includes("subscription"))return T.data.object;return null}var Jx={onWebhookEvent:Y,registerWebhookHandlers:GT,constructEvent:JT,constructEventAsync:o,handleWebhookEvent:r,processWebhook:QT,onPaymentIntent:ZT,onSubscription:LT,onInvoice:AT,onCheckout:RT,onCharge:HT,getPaymentIntent:XT,getSubscription:YT,getInvoice:NT,getCheckoutSession:qT,getCharge:UT,getCustomer:DT};async function Dx(T,x,w,$={}){return C.charge(T,x,w,$)}async function Ox(T,x,w={}){return C.createPayment(T,x,w)}async function Vx(T,x,w={}){return C.refund(T,{amount:x,...w})}async function jx(T,x,w={}){return l.create(T,{line_items:x,mode:"payment",...w})}async function fx(T,x,w={}){return l.create(T,{line_items:[{price:x,quantity:1}],mode:"subscription",...w})}async function Wx(T,x,w={}){return P.create(T,"default",x,w)}async function Kx(T,x=!1){return P.cancel(T,{prorate:!x,invoice_now:x})}async function Ex(T,x="default"){return P.isValid(T,x)}async function Px(T,x,w="default"){return P.update(T,w,x,{})}async function Sx(T,x={}){return O.createOrGetStripeUser(T,x)}async function Cx(T,x){return O.updateStripeCustomer(T,x)}async function kx(T){return O.deleteStripeUser(T)}async function Mx(T,x){return k.addPaymentMethod(T,x)}async function vx(T,x){return k.setUserDefaultPayment(T,x)}async function gx(T,x){return k.deletePaymentMethod(T,x)}async function bx(T,x={}){return n.create(T,x)}async function Ix(T){return p.list(T)}async function yx(T,x={}){return _.invoices.create({customer:T,...x})}async function lx(T){return _.invoices.pay(T)}async function hx(T,x,w={}){let{currency:$="usd",interval:z,description:Q,metadata:X}=w,B={unit_amount:x,currency:$};if(z)B.recurring={interval:z};return c.createWithPrice({name:T,description:Q,metadata:X},B)}async function cx(T){return E.retrieveByLookupKey(T)}async function mx(T={}){return c.list(T)}async function ux(T){let x={duration:T.duration||"once"};if(T.percentOff)x.percent_off=T.percentOff;else if(T.amountOff)x.amount_off=T.amountOff,x.currency=T.currency||"usd";if(T.name)x.name=T.name;if(T.durationInMonths)x.duration_in_months=T.durationInMonths;if(T.maxRedemptions)x.max_redemptions=T.maxRedemptions;return M.create(x)}async function dx(T,x,w={}){return M.createPromotionCode({promotion:{type:"coupon",coupon:T},code:x,...w})}async function ix(T){return M.retrievePromotionCode(T)}function ax(T,x){let w=globalThis.config||{},$=(x||w.payment?.currency||w.billing?.currency||process.env.STRIPE_CURRENCY||"usd").toLowerCase(),z=w.app?.locale||"en-US";return new Intl.NumberFormat(z,{style:"currency",currency:$.toUpperCase()}).format(T/100)}function px(T){return Math.round(T*100)}function nx(T){return T/100}import{saas as OT}from"@stacksjs/config";import{err as VT,ok as jT}from"@stacksjs/error-handling";import{log as fT}from"@stacksjs/logging";import{stripe as s}from"@stacksjs/payments";async function Tw(){let T=OT.plans;try{if(T!==void 0&&T.length)for(let x of T){let w=await s.products.create({name:x.productName,description:x.description,metadata:x.metadata});for(let $ of x.pricing)if(w){let z={unit_amount:$.price,currency:$.currency,product:w.id,lookup_key:$.key};if($.interval)z.recurring={interval:$.interval};await s.prices.create(z)}}return jT("Migrations generated")}catch(x){let w=x instanceof Error?x:Error(String(x));return fT.error(w),VT(w)}}import{db as v}from"@stacksjs/database";var _w=(()=>{async function T(w,$,z){let Q=await v.selectFrom("payment_products").where("id","=",$).selectAll().executeTakeFirst();if(!Q)throw Error(`Payment product with id ${$} not found.`);let X={name:Q.name,description:z.description??"",amount:Q.unit_price,brand:z.brand,type:z.type??"one-time",provider_id:z.provider_id,user_id:w.id},B=await v.insertInto("payment_transactions").values(X).executeTakeFirst();if(!B)throw Error("Failed to insert payment transaction");return await v.selectFrom("payment_transactions").where("id","=",Number(B.insertId)).selectAll().executeTakeFirst()}async function x(w){return await v.selectFrom("payment_transactions").where("user_id","=",w.id).selectAll().execute()}return{store:T,list:x}})();export{ix as validatePromoCode,Cx as updateCustomer,nx as toDollars,px as toCents,fx as subscriptionCheckout,Wx as subscribe,_ as stripe,Aw as stacksIdempotencyKey,vx as setDefaultPaymentMethod,gx as removePaymentMethod,GT as registerWebhookHandlers,Vx as refund,QT as processWebhook,lx as payInvoice,Y as onWebhookEvent,LT as onSubscription,ZT as onPaymentIntent,AT as onInvoice,RT as onCheckout,HT as onCharge,Jx as manageWebhook,_w as manageTransaction,P as manageSubscription,n as manageSetupIntent,c as manageProduct,$T as managePriceExtended,E as managePrice,k as managePaymentMethod,p as manageInvoice,O as manageCustomer,M as manageCoupon,l as manageCheckout,C as manageCharge,mx as listProducts,Ex as hasActiveSubscription,r as handleWebhookEvent,YT as getSubscription,cx as getPrice,XT as getPaymentIntent,Sx as getOrCreateCustomer,Ix as getInvoices,NT as getInvoice,DT as getCustomer,qT as getCheckoutSession,UT as getCharge,Lw as freshIdempotencyKey,ax as formatAmount,kx as deleteCustomer,Tw as createStripeProduct,bx as createSetupIntent,dx as createPromoCode,hx as createProduct,Ox as createPayment,yx as createInvoice,ux as createCoupon,o as constructEventAsync,JT as constructEvent,jx as checkout,Dx as charge,Px as changeSubscription,Kx as cancelSubscription,Mx as addPaymentMethod,Gw as Payment};
package/dist/payment.d.ts DELETED
@@ -1,182 +0,0 @@
1
- import type { UserModel } from '@stacksjs/orm';
2
- import type Stripe from 'stripe';
3
- /**
4
- * Create a one-time charge
5
- */
6
- export declare function charge(user: UserModel, amount: number, paymentMethod: string, options?: Partial<Stripe.PaymentIntentCreateParams>): Promise<Stripe.PaymentIntent>;
7
- /**
8
- * Create a payment intent (for client-side confirmation)
9
- */
10
- export declare function createPayment(user: UserModel, amount: number, options?: Partial<Stripe.PaymentIntentCreateParams>): Promise<Stripe.PaymentIntent>;
11
- /**
12
- * Refund a payment
13
- */
14
- export declare function refund(paymentIntentId: string, amount?: number, options?: Partial<Stripe.RefundCreateParams>): Promise<Stripe.Refund>;
15
- /**
16
- * Create a Stripe Checkout session
17
- */
18
- export declare function checkout(user: UserModel, lineItems: Stripe.Checkout.SessionCreateParams.LineItem[], options?: Partial<Stripe.Checkout.SessionCreateParams>): Promise<Stripe.Checkout.Session>;
19
- /**
20
- * Create a subscription checkout session
21
- */
22
- export declare function subscriptionCheckout(user: UserModel, priceId: string, options?: Partial<Stripe.Checkout.SessionCreateParams>): Promise<Stripe.Checkout.Session>;
23
- /**
24
- * Create a new subscription
25
- */
26
- export declare function subscribe(user: UserModel, lookupKey: string, options?: Partial<Stripe.SubscriptionCreateParams>): Promise<Stripe.Subscription>;
27
- /**
28
- * Cancel a subscription
29
- */
30
- export declare function cancelSubscription(subscriptionId: string, immediately?: boolean): Promise<Stripe.Subscription>;
31
- /**
32
- * Check if user has an active subscription
33
- */
34
- export declare function hasActiveSubscription(user: UserModel, type?: string): Promise<boolean>;
35
- /**
36
- * Update subscription to a new price
37
- */
38
- export declare function changeSubscription(user: UserModel, newLookupKey: string, type?: string): Promise<Stripe.Subscription>;
39
- /**
40
- * Get or create a Stripe customer for a user
41
- */
42
- export declare function getOrCreateCustomer(user: UserModel, options?: Stripe.CustomerCreateParams): Promise<Stripe.Customer>;
43
- /**
44
- * Update customer details
45
- */
46
- export declare function updateCustomer(user: UserModel, options: Stripe.CustomerCreateParams): Promise<Stripe.Customer>;
47
- /**
48
- * Delete a customer from Stripe
49
- */
50
- export declare function deleteCustomer(user: UserModel): Promise<Stripe.DeletedCustomer>;
51
- /**
52
- * Add a payment method to a customer
53
- */
54
- export declare function addPaymentMethod(user: UserModel, paymentMethodId: string): Promise<Stripe.PaymentMethod>;
55
- /**
56
- * Set the default payment method
57
- */
58
- export declare function setDefaultPaymentMethod(user: UserModel, paymentMethodId: string): Promise<Stripe.Customer>;
59
- /**
60
- * Remove a payment method.
61
- * Accepts either a numeric database ID or a Stripe payment method ID string (pm_xxx).
62
- */
63
- export declare function removePaymentMethod(user: UserModel, paymentMethodId: string | number): Promise<Stripe.PaymentMethod>;
64
- /**
65
- * Create a setup intent for adding payment methods
66
- */
67
- export declare function createSetupIntent(user: UserModel, options?: Partial<Stripe.SetupIntentCreateParams>): Promise<Stripe.SetupIntent>;
68
- /**
69
- * Get user's invoices
70
- */
71
- export declare function getInvoices(user: UserModel): Promise<Stripe.ApiList<Stripe.Invoice>>;
72
- /**
73
- * Create an invoice
74
- */
75
- export declare function createInvoice(customerId: string, options?: Partial<Stripe.InvoiceCreateParams>): Promise<Stripe.Invoice>;
76
- /**
77
- * Pay an invoice
78
- */
79
- export declare function payInvoice(invoiceId: string): Promise<Stripe.Invoice>;
80
- /**
81
- * Create a product with a price
82
- */
83
- export declare function createProduct(name: string, price: number, options?: {
84
- currency?: string
85
- interval?: 'day' | 'week' | 'month' | 'year'
86
- description?: string
87
- metadata?: Stripe.MetadataParam
88
- }): Promise<{ product: Stripe.Product, price: Stripe.Price }>;
89
- /**
90
- * Get a price by lookup key
91
- */
92
- export declare function getPrice(lookupKey: string): Promise<Stripe.Price | undefined>;
93
- /**
94
- * List all products
95
- */
96
- export declare function listProducts(options?: Stripe.ProductListParams): Promise<Stripe.ApiList<Stripe.Product>>;
97
- /**
98
- * Create a discount coupon
99
- */
100
- export declare function createCoupon(options: {
101
- percentOff?: number
102
- amountOff?: number
103
- currency?: string
104
- duration?: 'forever' | 'once' | 'repeating'
105
- durationInMonths?: number
106
- name?: string
107
- maxRedemptions?: number
108
- }): Promise<Stripe.Coupon>;
109
- /**
110
- * Create a promotion code from a coupon
111
- */
112
- export declare function createPromoCode(couponId: string, code: string, options?: Partial<Stripe.PromotionCodeCreateParams>): Promise<Stripe.PromotionCode>;
113
- /**
114
- * Validate a promo code
115
- */
116
- export declare function validatePromoCode(code: string): Promise<Stripe.PromotionCode | null>;
117
- /**
118
- * Format amount for display.
119
- *
120
- * Currency defaults to the project's configured payment currency
121
- * (`config.payment.currency` / `STRIPE_CURRENCY`), falling back to USD only
122
- * when nothing else is set. Locale follows the same pattern via
123
- * `config.app.locale` so EU merchants see €1.234,56 not $1,234.56.
124
- */
125
- export declare function formatAmount(amount: number, currency?: string): string;
126
- /**
127
- * Convert dollars to cents
128
- */
129
- export declare function toCents(dollars: number): number;
130
- /**
131
- * Convert cents to dollars
132
- */
133
- export declare function toDollars(cents: number): number;
134
- // =============================================================================
135
- // Payment Facade Object
136
- // =============================================================================
137
- export declare const Payment: {
138
- charge: typeof charge;
139
- createPayment: typeof createPayment;
140
- refund: typeof refund;
141
- checkout: typeof checkout;
142
- subscriptionCheckout: typeof subscriptionCheckout;
143
- subscribe: typeof subscribe;
144
- cancelSubscription: typeof cancelSubscription;
145
- hasActiveSubscription: typeof hasActiveSubscription;
146
- changeSubscription: typeof changeSubscription;
147
- getOrCreateCustomer: typeof getOrCreateCustomer;
148
- updateCustomer: typeof updateCustomer;
149
- deleteCustomer: typeof deleteCustomer;
150
- addPaymentMethod: typeof addPaymentMethod;
151
- setDefaultPaymentMethod: typeof setDefaultPaymentMethod;
152
- removePaymentMethod: typeof removePaymentMethod;
153
- createSetupIntent: typeof createSetupIntent;
154
- getInvoices: typeof getInvoices;
155
- createInvoice: typeof createInvoice;
156
- payInvoice: typeof payInvoice;
157
- createProduct: typeof createProduct;
158
- getPrice: typeof getPrice;
159
- listProducts: typeof listProducts;
160
- createCoupon: typeof createCoupon;
161
- createPromoCode: typeof createPromoCode;
162
- validatePromoCode: typeof validatePromoCode;
163
- formatAmount: typeof formatAmount;
164
- toCents: typeof toCents;
165
- toDollars: typeof toDollars;
166
- webhook: unknown;
167
- onPaymentIntent: typeof onPaymentIntent;
168
- onSubscription: typeof onSubscription;
169
- onInvoice: typeof onInvoice;
170
- onCheckout: typeof onCheckout;
171
- onCharge: typeof onCharge;
172
- processWebhook: typeof processWebhook;
173
- stripe: typeof stripe;
174
- customer: unknown;
175
- subscription: unknown;
176
- invoice: unknown;
177
- paymentMethod: unknown;
178
- product: unknown;
179
- price: unknown;
180
- coupon: unknown
181
- };
182
- export default Payment;